@optimystic/db-p2p 0.2.2 → 0.2.3

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
@@ -1,37 +1,37 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.OptimysticDbP2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var OptimysticDbP2P=(()=>{var RD=Object.create;var ah=Object.defineProperty;var ND=Object.getOwnPropertyDescriptor;var BD=Object.getOwnPropertyNames;var UD=Object.getPrototypeOf,KD=Object.prototype.hasOwnProperty;var te=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var C=(r,e)=>()=>(r&&(e=r(r=0)),e);var At=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),z=(r,e)=>{for(var t in e)ah(r,t,{get:e[t],enumerable:!0})},z5=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of BD(e))!KD.call(r,s)&&s!==t&&ah(r,s,{get:()=>e[s],enumerable:!(n=ND(e,s))||n.enumerable});return r};var ae=(r,e,t)=>(t=r!=null?RD(UD(r)):{},z5(e||!r||!r.__esModule?ah(t,"default",{value:r,enumerable:!0}):t,r)),$5=r=>z5(ah({},"__esModule",{value:!0}),r);function rs(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}var cc=C(()=>{});function ce(r=0){return rs(Am.Buffer.alloc(r))}function tt(r=0){return rs(Am.Buffer.allocUnsafe(r))}var Am,rt=C(()=>{Am=te("node:buffer");cc()});function Ae(r){if(r<jD)return 1;if(r<YD)return 2;if(r<XD)return 3;if(r<Cm)return 4;if(r<Tm)return 5;if(r<_m)return 6;if(r<Pm)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function In(r,e,t=0){switch(Ae(r)){case 8:e[t++]=r&255|Se,r/=128;case 7:e[t++]=r&255|Se,r/=128;case 6:e[t++]=r&255|Se,r/=128;case 5:e[t++]=r&255|Se,r/=128;case 4:e[t++]=r&255|Se,r>>>=7;case 3:e[t++]=r&255|Se,r>>>=7;case 2:e[t++]=r&255|Se,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function QD(r,e,t=0){switch(Ae(r)){case 8:e.set(t++,r&255|Se),r/=128;case 7:e.set(t++,r&255|Se),r/=128;case 6:e.set(t++,r&255|Se),r/=128;case 5:e.set(t++,r&255|Se),r/=128;case 4:e.set(t++,r&255|Se),r>>>=7;case 3:e.set(t++,r&255|Se),r>>>=7;case 2:e.set(t++,r&255|Se),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Dm(r,e){let t=r[e],n=0;if(n+=t&Ct,t<Se||(t=r[e+1],n+=(t&Ct)<<7,t<Se)||(t=r[e+2],n+=(t&Ct)<<14,t<Se)||(t=r[e+3],n+=(t&Ct)<<21,t<Se)||(t=r[e+4],n+=(t&Ct)*Cm,t<Se)||(t=r[e+5],n+=(t&Ct)*Tm,t<Se)||(t=r[e+6],n+=(t&Ct)*_m,t<Se)||(t=r[e+7],n+=(t&Ct)*Pm,t<Se))return n;throw new RangeError("Could not decode varint")}function JD(r,e){let t=r.get(e),n=0;if(n+=t&Ct,t<Se||(t=r.get(e+1),n+=(t&Ct)<<7,t<Se)||(t=r.get(e+2),n+=(t&Ct)<<14,t<Se)||(t=r.get(e+3),n+=(t&Ct)<<21,t<Se)||(t=r.get(e+4),n+=(t&Ct)*Cm,t<Se)||(t=r.get(e+5),n+=(t&Ct)*Tm,t<Se)||(t=r.get(e+6),n+=(t&Ct)*_m,t<Se)||(t=r.get(e+7),n+=(t&Ct)*Pm,t<Se))return n;throw new RangeError("Could not decode varint")}function Vr(r,e,t=0){return e==null&&(e=tt(Ae(r))),e instanceof Uint8Array?In(r,e,t):QD(r,e,t)}function jt(r,e=0){return r instanceof Uint8Array?Dm(r,e):JD(r,e)}var jD,YD,XD,Cm,Tm,_m,Pm,Se,Ct,gr=C(()=>{rt();jD=Math.pow(2,7),YD=Math.pow(2,14),XD=Math.pow(2,21),Cm=Math.pow(2,28),Tm=Math.pow(2,35),_m=Math.pow(2,42),Pm=Math.pow(2,49),Se=128,Ct=127});function Ee(r,e){return rs(G5.Buffer.concat(r,e))}var G5,bt=C(()=>{G5=te("node:buffer");cc()});function W(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Ne=C(()=>{});function W5(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function hh(r){return!!r?.[j5]}var j5,U,Be=C(()=>{rt();bt();Ne();j5=Symbol.for("@achingbrain/uint8arraylist");U=class r{bufs;length;[j5]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(hh(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(hh(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=W5(this.bufs,e);return t.buf[t.index]}set(e,t){let n=W5(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(hh(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Ee(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ee(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!hh(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let d=0;d<o;d++)i[d]=-1;for(let d=0;d<s;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let p=l;p>=0;p--){let f=this.get(d+p);if(n[p]!==f){u=Math.max(1,p-a[f]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=tt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=ce(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=ce(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=ce(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=tt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=ce(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=ce(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=ce(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=ce(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=ce(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!W(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}}});var X5,Q5=C(()=>{X5=Symbol.for("@libp2p/connection")});var J5=C(()=>{});var Z5=C(()=>{});var ex=C(()=>{});var Mm,tx=C(()=>{Mm=Symbol.for("@libp2p/content-routing")});var rr,yh,bh,B,Xo,hc,zs,Tn,wh,ns,dc,$s,Qo,ss,xh,vh,Eh,Rt,Sh,Gr,Dr,Ih,os,Hs,fc,Ah,Jo,is,rx=C(()=>{rr=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},yh=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},bh=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},B=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Xo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},hc=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},zs=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},Tn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},wh=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},ns=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},dc=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},$s=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Qo=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},ss=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},xh=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},vh=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Eh=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Rt=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},Sh=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Gr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Dr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},Ih=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}},os=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Hs=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},fc=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Ah=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Jo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},is=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});var Ch,as,Th,_h,nx=C(()=>{Ch=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},as=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Th=class extends as{constructor(e,t){super(!0,e,t)}},_h=class extends as{constructor(e,t){super(!1,e,t)}}});var sx=C(()=>{});var ox=C(()=>{});var ix=C(()=>{});var ax=C(()=>{});var pc,cx=C(()=>{pc=Symbol.for("@libp2p/peer-discovery")});function cs(r){return!!r?.[Ph]}var Ph,lx=C(()=>{Ph=Symbol.for("@libp2p/peer-id")});var ux=C(()=>{});var Om,hx=C(()=>{Om=Symbol.for("@libp2p/peer-routing")});var mc,dx=C(()=>{mc="keep-alive"});var fx=C(()=>{});function Dh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function kh(...r){let e=[];for(let t of r)Dh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Lh(...r){let e=[];for(let t of r)Dh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var px=C(()=>{});var mx=C(()=>{});var gx=C(()=>{});var yx=C(()=>{});var bx=C(()=>{});var Mh,gc,wx=C(()=>{Mh=Symbol.for("@libp2p/transport");(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(gc||(gc={}))});var xx,Y,vx=C(()=>{xx=te("node:events"),Y=(r,...e)=>{try{(0,xx.setMaxListeners)(r,...e)}catch{}}});var me,Ue=C(()=>{vx();me=class extends EventTarget{#e=new Map;constructor(){super(),Y(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}});var nt,yc,V=C(()=>{Q5();J5();Z5();ex();tx();rx();nx();sx();ox();ix();ax();cx();lx();ux();hx();dx();fx();px();mx();gx();yx();bx();wx();Ue();nt=Symbol.for("@libp2p/service-capabilities"),yc=Symbol.for("@libp2p/service-dependencies")});function Ex(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ls(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var vX,bc=C(()=>{vX=new Uint8Array(0)});function rk(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var nk,sk,Sx,Ix=C(()=>{nk=rk,sk=nk,Sx=sk});function Ax(r,e){return new Bm({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Cx({name:r,prefix:e,encode:t,decode:n}){return new Um(r,e,t,n)}function Zo({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Sx(t,r);return Cx({prefix:e,name:r,encode:n,decode:o=>ls(s(o))})}function ok(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function ik(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function ak(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Wr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=ak(n);return Cx({prefix:e,name:r,encode(o){return ik(o,n,t)},decode(o){return ok(o,s,t,r)}})}var Rm,Nm,Bm,Um,Oh=C(()=>{bc();Ix();Rm=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Nm=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 Ax(this,e)}},Bm=class{decoders;constructor(e){this.decoders=e}or(e){return Ax(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};Um=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Rm(e,t,n),this.decoder=new Nm(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var wt,_X,ei=C(()=>{Oh();wt=Zo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),_X=Zo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var wc,kX,LX,MX,OX,RX,NX,BX,UX,Tx=C(()=>{Oh();wc=Wr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),kX=Wr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),LX=Wr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),MX=Wr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),OX=Wr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),RX=Wr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),NX=Wr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),BX=Wr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),UX=Wr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Rh,zX,_x=C(()=>{Oh();Rh=Zo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zX=Zo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});function kx(r,e,t){e=e||[],t=t||0;for(var n=t;r>=hk;)e[t++]=r&255|Px,r/=128;for(;r&uk;)e[t++]=r&255|Px,r>>>=7;return e[t]=r|0,kx.bytes=t-n+1,e}function Km(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Km.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Dx)<<s:(i&Dx)*Math.pow(2,s),s+=7}while(i>=fk);return Km.bytes=o-n,t}var ck,Px,lk,uk,hk,dk,fk,Dx,pk,mk,gk,yk,bk,wk,xk,vk,Ek,Sk,Ik,Ak,xc,Lx=C(()=>{ck=kx,Px=128,lk=127,uk=~lk,hk=Math.pow(2,31);dk=Km,fk=128,Dx=127;pk=Math.pow(2,7),mk=Math.pow(2,14),gk=Math.pow(2,21),yk=Math.pow(2,28),bk=Math.pow(2,35),wk=Math.pow(2,42),xk=Math.pow(2,49),vk=Math.pow(2,56),Ek=Math.pow(2,63),Sk=function(r){return r<pk?1:r<mk?2:r<gk?3:r<yk?4:r<bk?5:r<wk?6:r<xk?7:r<vk?8:r<Ek?9:10},Ik={encode:ck,decode:dk,encodingLength:Sk},Ak=Ik,xc=Ak});function vc(r,e=0){return[xc.decode(r,e),xc.decode.bytes]}function ti(r,e,t=0){return xc.encode(r,e,t),e}function ri(r){return xc.encodingLength(r)}var Fm=C(()=>{Lx()});function us(r,e){let t=e.byteLength,n=ri(r),s=n+ri(t),o=new Uint8Array(s+t);return ti(r,o,0),ti(t,o,n),o.set(e,s),new ni(r,t,e,o)}function Ox(r){let e=ls(r),[t,n]=vc(e),[s,o]=vc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ni(t,s,i,e)}function Rx(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ex(r.bytes,t.bytes)}}var ni,Nh=C(()=>{bc();Fm();ni=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}}});var Bx=C(()=>{});function Ux(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Tk(t,zm(r),e??wt.encoder);default:return _k(t,zm(r),e??wc.encoder)}}function zm(r){let e=Kx.get(r);if(e==null){let t=new Map;return Kx.set(r,t),t}return e}function Ck(r,e){switch(r[0]){case"Q":{let t=e??wt;return[wt.prefix,t.decode(`${wt.prefix}${r}`)]}case wt.prefix:{let t=e??wt;return[wt.prefix,t.decode(r)]}case wc.prefix:{let t=e??wc;return[wc.prefix,t.decode(r)]}case Rh.prefix:{let t=e??Rh;return[Rh.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Tk(r,e,t){let{prefix:n}=t;if(n!==wt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function _k(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}function Fx(r,e,t){let n=ri(r),s=n+ri(e),o=new Uint8Array(s+t.byteLength);return ti(r,o,0),ti(e,o,n),o.set(t,s),o}var Kx,jr,Ec,Pk,Dk,Sc=C(()=>{Tx();_x();ei();bc();Nh();Fm();Bx();Kx=new WeakMap;jr=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ec)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Pk)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=us(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Rx(e.multihash,n.multihash)}toString(e){return Ux(this,e)}toJSON(){return{"/":Ux(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Fx(n,s,o.bytes))}else if(t[Dk]===!0){let{version:n,multihash:s,code:o}=t,i=Ox(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ec)throw new Error(`Version 0 CID must use dag-pb (code: ${Ec}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Fx(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ec,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=ls(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ni(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=vc(e.subarray(t));return t+=p,d},s=n(),o=Ec;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Ck(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return zm(o).set(n,e),o}};Ec=112,Pk=18;Dk=Symbol.for("@ipld/js-cid/CID")});function Lk(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return us(zx,$x(r))}var zx,kk,$x,si,Bh=C(()=>{bc();Nh();zx=0,kk="identity",$x=ls;si={code:zx,name:kk,encode:$x,digest:Lk}});function Hx(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function br(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function qx(r){return new TextEncoder().encode(r)}function Vx(r){return new TextDecoder().decode(r)}var eQ,_n=C(()=>{eQ=new Uint8Array(0)});function Mk(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var Ok,Rk,Wx,jx=C(()=>{Ok=Mk,Rk=Ok,Wx=Rk});function Yx(r,e){return new qm({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function oi({name:r,prefix:e,encode:t,decode:n}){return new Vm(r,e,t,n)}function hs({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Wx(t,r);return oi({prefix:e,name:r,encode:n,decode:o=>br(s(o))})}function Nk(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Bk(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Uk(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function $e({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Uk(n);return oi({prefix:e,name:r,encode(o){return Bk(o,n,t)},decode(o){return Nk(o,s,t,r)}})}var $m,Hm,qm,Vm,kr=C(()=>{_n();jx();$m=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Hm=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 Yx(this,e)}},qm=class{decoders;constructor(e){this.decoders=e}or(e){return Yx(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};Vm=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new $m(e,t,n),this.decoder=new Hm(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var Gm={};z(Gm,{base10:()=>Kk});var Kk,Xx=C(()=>{kr();Kk=hs({prefix:"9",name:"base10",alphabet:"0123456789"})});var Wm={};z(Wm,{base16:()=>Fk,base16upper:()=>zk});var Fk,zk,Qx=C(()=>{kr();Fk=$e({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zk=$e({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var jm={};z(jm,{base2:()=>$k});var $k,Jx=C(()=>{kr();$k=$e({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var Ym={};z(Ym,{base256emoji:()=>Wk});function Vk(r){return r.reduce((e,t)=>(e+=Hk[t],e),"")}function Gk(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=qk[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Zx,Hk,qk,Wk,e4=C(()=>{kr();Zx=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}"),Hk=Zx.reduce((r,e,t)=>(r[t]=e,r),[]),qk=Zx.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);Wk=oi({prefix:"\u{1F680}",name:"base256emoji",encode:Vk,decode:Gk})});var Xm={};z(Xm,{base32:()=>ii,base32hex:()=>Qk,base32hexpad:()=>Zk,base32hexpadupper:()=>e7,base32hexupper:()=>Jk,base32pad:()=>Yk,base32padupper:()=>Xk,base32upper:()=>jk,base32z:()=>t7});var ii,jk,Yk,Xk,Qk,Jk,Zk,e7,t7,Qm=C(()=>{kr();ii=$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jk=$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Yk=$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Xk=$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qk=$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Jk=$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zk=$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),e7=$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),t7=$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Jm={};z(Jm,{base36:()=>Ic,base36upper:()=>r7});var Ic,r7,Zm=C(()=>{kr();Ic=hs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),r7=hs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var e0={};z(e0,{base58btc:()=>Yr,base58flickr:()=>n7});var Yr,n7,t0=C(()=>{kr();Yr=hs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),n7=hs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var r0={};z(r0,{base64:()=>s7,base64pad:()=>o7,base64url:()=>i7,base64urlpad:()=>a7});var s7,o7,i7,a7,t4=C(()=>{kr();s7=$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),o7=$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),i7=$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),a7=$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var n0={};z(n0,{base8:()=>c7});var c7,r4=C(()=>{kr();c7=$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var s0={};z(s0,{identity:()=>l7});var l7,n4=C(()=>{_n();kr();l7=oi({prefix:"\0",name:"identity",encode:r=>Vx(r),decode:r=>qx(r)})});var gQ,yQ,s4=C(()=>{gQ=new TextEncoder,yQ=new TextDecoder});var o4=C(()=>{_n()});function c4(r,e,t){e=e||[],t=t||0;for(var n=t;r>=m7;)e[t++]=r&255|i4,r/=128;for(;r&p7;)e[t++]=r&255|i4,r>>>=7;return e[t]=r|0,c4.bytes=t-n+1,e}function o0(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw o0.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&a4)<<s:(i&a4)*Math.pow(2,s),s+=7}while(i>=y7);return o0.bytes=o-n,t}var d7,i4,f7,p7,m7,g7,y7,a4,b7,w7,x7,v7,E7,S7,I7,A7,C7,T7,_7,P7,Ac,l4=C(()=>{d7=c4,i4=128,f7=127,p7=~f7,m7=Math.pow(2,31);g7=o0,y7=128,a4=127;b7=Math.pow(2,7),w7=Math.pow(2,14),x7=Math.pow(2,21),v7=Math.pow(2,28),E7=Math.pow(2,35),S7=Math.pow(2,42),I7=Math.pow(2,49),A7=Math.pow(2,56),C7=Math.pow(2,63),T7=function(r){return r<b7?1:r<w7?2:r<x7?3:r<v7?4:r<E7?5:r<S7?6:r<I7?7:r<A7?8:r<C7?9:10},_7={encode:d7,decode:g7,encodingLength:T7},P7=_7,Ac=P7});function Cc(r,e=0){return[Ac.decode(r,e),Ac.decode.bytes]}function ai(r,e,t=0){return Ac.encode(r,e,t),e}function ci(r){return Ac.encodingLength(r)}var Kh=C(()=>{l4()});function ui(r,e){let t=e.byteLength,n=ci(r),s=n+ci(t),o=new Uint8Array(s+t);return ai(r,o,0),ai(t,o,n),o.set(e,s),new li(r,t,e,o)}function u4(r){let e=br(r),[t,n]=Cc(e),[s,o]=Cc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new li(t,s,i,e)}function h4(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Hx(r.bytes,t.bytes)}}var li,_c=C(()=>{_n();Kh();li=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}}});var i0={};z(i0,{identity:()=>L7});function k7(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ui(d4,f4(r))}var d4,D7,f4,L7,p4=C(()=>{_n();_c();d4=0,D7="identity",f4=br;L7={code:d4,name:D7,encode:f4,digest:k7}});function c0({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new a0(r,e,t,n,s)}function m4(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ui(e,r)}var M7,a0,l0=C(()=>{_c();M7=20;a0=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??M7,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?m4(n,this.code,t?.truncate):n.then(s=>m4(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var h0={};z(h0,{sha256:()=>O7,sha512:()=>R7});var u0,O7,R7,y4=C(()=>{u0=ae(te("crypto"),1);_n();l0();O7=c0({name:"sha2-256",code:18,encode:r=>br(u0.default.createHash("sha256").update(r).digest())}),R7=c0({name:"sha2-512",code:19,encode:r=>br(u0.default.createHash("sha512").update(r).digest())})});var d0=C(()=>{});function b4(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return B7(t,f0(r),e??Yr.encoder);default:return U7(t,f0(r),e??ii.encoder)}}function f0(r){let e=w4.get(r);if(e==null){let t=new Map;return w4.set(r,t),t}return e}function N7(r,e){switch(r[0]){case"Q":{let t=e??Yr;return[Yr.prefix,t.decode(`${Yr.prefix}${r}`)]}case Yr.prefix:{let t=e??Yr;return[Yr.prefix,t.decode(r)]}case ii.prefix:{let t=e??ii;return[ii.prefix,t.decode(r)]}case Ic.prefix:{let t=e??Ic;return[Ic.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function B7(r,e,t){let{prefix:n}=t;if(n!==Yr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function U7(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}function x4(r,e,t){let n=ci(r),s=n+ci(e),o=new Uint8Array(s+t.byteLength);return ai(r,o,0),ai(e,o,n),o.set(t,s),o}var w4,Fh,Pc,K7,F7,v4=C(()=>{Qm();Zm();t0();_n();_c();Kh();d0();w4=new WeakMap;Fh=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Pc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==K7)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ui(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&h4(e.multihash,n.multihash)}toString(e){return b4(this,e)}toJSON(){return{"/":b4(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??x4(n,s,o.bytes))}else if(t[F7]===!0){let{version:n,multihash:s,code:o}=t,i=u4(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Pc)throw new Error(`Version 0 CID must use dag-pb (code: ${Pc}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=x4(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pc,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=br(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new li(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=Cc(e.subarray(t));return t+=p,d},s=n(),o=Pc;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=N7(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return f0(o).set(n,e),o}};Pc=112,K7=18;F7=Symbol.for("@ipld/js-cid/CID")});var E4=C(()=>{});var S4=C(()=>{});var I4=C(()=>{});var A4=C(()=>{});var C4=C(()=>{E4();S4();I4();d0();A4()});var T4=C(()=>{_n();v4();_c();l0();Kh();C4()});var p0,FQ,_4=C(()=>{Xx();Qx();Jx();e4();Qm();Zm();t0();t4();r4();n4();s4();o4();p4();y4();T4();p0={...s0,...jm,...n0,...Gm,...Wm,...Xm,...Jm,...e0,...r0,...Ym},FQ={...h0,...i0}});function D4(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var P4,m0,z7,zh,g0=C(()=>{_4();rt();P4=D4("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),m0=D4("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=tt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),z7={utf8:P4,"utf-8":P4,hex:p0.base16,latin1:m0,ascii:m0,binary:m0,...p0},zh=z7});function D(r,e="utf8"){let t=zh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?rs(k4.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var k4,re=C(()=>{k4=te("node:buffer");g0();cc()});function T(r,e="utf8"){let t=zh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?L4.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var L4,ie=C(()=>{L4=te("node:buffer");g0()});function Pn(r,e={offset:0}){let t=r[e.offset]&$7;if(e.offset++,M4[t]!=null)return M4[t](r,e);throw new Error("No decoder for tag "+t)}function kc(r,e){let t=0;if((r[e.offset]&y0)===y0){let n=r[e.offset]&H7,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Dc(r,e){kc(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Pn(r,e);if(n===null)break;t.push(n)}return t}function q7(r,e){let t=kc(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function V7(r,e){let t=kc(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function G7(r,e){return e.offset++,null}function W7(r,e){let t=kc(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function j7(r,e){let t=kc(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Y7(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new U;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function $h(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Y7(r.byteLength);return new U(Uint8Array.from([e.byteLength|y0]),e)}function Nt(r){let e=new U,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new U(Uint8Array.from([2]),$h(e),e)}function Lc(r){let e=Uint8Array.from([0]),t=new U(e,r);return new U(Uint8Array.from([3]),$h(t),t)}function O4(r){return new U(Uint8Array.from([4]),$h(r),r)}function Lr(r,e=48){let t=new U;for(let n of r)t.append(n);return new U(Uint8Array.from([e]),$h(t),t)}var $7,y0,H7,M4,b0=C(()=>{Be();$7=parseInt("11111",2),y0=parseInt("10000000",2),H7=parseInt("01111111",2),M4={0:Dc,1:Dc,2:q7,3:W7,4:j7,5:G7,6:V7,16:Dc,22:Dc,48:Dc}});async function R4(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function N4(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function B4(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var w0=C(()=>{});function S0(r){let e=Pn(r);return U4(e)}function U4(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===x0*2+1)return n=T(e.subarray(t,t+x0),"base64url"),s=T(e.subarray(t+x0),"base64url"),new qs({...Z7,key_ops:["verify"],x:n,y:s});if(e.byteLength===v0*2+1)return n=T(e.subarray(t,t+v0),"base64url"),s=T(e.subarray(t+v0),"base64url"),new qs({...eL,key_ops:["verify"],x:n,y:s});if(e.byteLength===E0*2+1)return n=T(e.subarray(t,t+E0),"base64url"),s=T(e.subarray(t+E0),"base64url"),new qs({...tL,key_ops:["verify"],x:n,y:s});throw new B(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function K4(r){return Lr([Nt(Uint8Array.from([1])),O4(D(r.d??"","base64url")),Lr([z4(r.crv)],160),Lr([Lc(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function F4(r){return Lr([Nt(Uint8Array.from([1])),Lr([z4(r.crv)],160),Lr([Lc(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function z4(r){if(r==="P-256")return X7;if(r==="P-384")return Q7;if(r==="P-521")return J7;throw new B(`Invalid curve ${r}`)}async function $4(r="P-256"){let e=await R4(r);return new Hh(e.privateKey)}var X7,Q7,J7,Z7,eL,tL,x0,v0,E0,I0=C(()=>{V();Be();re();ie();b0();H4();w0();X7=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Q7=Uint8Array.from([6,5,43,129,4,0,34]),J7=Uint8Array.from([6,5,43,129,4,0,35]),Z7={ext:!0,kty:"EC",crv:"P-256"},eL={ext:!0,kty:"EC",crv:"P-384"},tL={ext:!0,kty:"EC",crv:"P-521"},x0=32,v0=48,E0=66});var qs,Hh,H4=C(()=>{ei();Sc();Bh();Ne();Bt();I0();w0();qs=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=F4(this.jwk)),this._raw}toMultihash(){return si.digest(dt(this))}toCID(){return jr.createV1(114,this.toMultihash())}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async verify(e,t,n){return B4(this.jwk,t,e,n)}},Hh=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new qs({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=K4(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async sign(e,t){return N4(this.jwk,e,t)}}});function oL(r){let t=Vs.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",x:"",d:T(r,"base64url"),kty:"OKP"}}).export({format:"jwk"});if(t.x==null||t.x==="")throw new Error("Could not export JWK public key");return D(t.x,"base64url")}function q4(){let r=rL("ed25519",{publicKeyEncoding:{type:"spki",format:"jwk"},privateKeyEncoding:{type:"pkcs8",format:"jwk"}}),e=D(r.privateKey.d,"base64url"),t=D(r.publicKey.x,"base64url");return{privateKey:Ee([e,t],e.byteLength+t.byteLength),publicKey:t}}function V4(r,e){if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');let t,n;if(r.byteLength===qh)t=r.subarray(0,32),n=r.subarray(32);else if(r.byteLength===nL)t=r.subarray(0,32),n=oL(t);else throw new TypeError('"key" must be 64 or 32 bytes in length.');let s=Vs.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",d:T(t,"base64url"),x:T(n,"base64url"),kty:"OKP"}});return Vs.default.sign(null,e instanceof Uint8Array?e:e.subarray(),s)}function G4(r,e,t){if(r.byteLength!==Mc)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==sL)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=Vs.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:T(r,"base64url"),kty:"OKP"}});return Vs.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}var Vs,rL,Mc,qh,nL,sL,A0=C(()=>{Vs=ae(te("crypto"),1);bt();re();ie();rL=Vs.default.generateKeyPairSync,Mc=32,qh=64,nL=32,sL=64});function C0(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var j4=C(()=>{bt();re()});var Oc,Vh,Y4=C(()=>{ei();Sc();Bh();Ne();j4();Bt();T0();A0();Oc=class{type="Ed25519";raw;constructor(e){this.raw=Gh(e,Mc)}toMultihash(){return si.digest(dt(this))}toCID(){return jr.createV1(114,this.toMultihash())}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=G4(this.raw,t,e);return C0(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}},Vh=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Gh(e,qh),this.publicKey=new Oc(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=V4(this.raw,e);return C0(n)?n.then(s=>(t?.signal?.throwIfAborted(),s)):(t?.signal?.throwIfAborted(),n)}}});function _0(r){return r=Gh(r,Mc),new Oc(r)}async function X4(){let{privateKey:r,publicKey:e}=q4();return new Vh(r,e)}function Gh(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new B(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var T0=C(()=>{V();Y4();A0()});function Q4(r,e,t){P0[0]=r,e[t]=ds[0],e[t+1]=ds[1],e[t+2]=ds[2],e[t+3]=ds[3]}function J4(r,e){return ds[0]=r[e],ds[1]=r[e+1],ds[2]=r[e+2],ds[3]=r[e+3],P0[0]}function Z4(r,e,t){D0[0]=r,e[t]=Tt[0],e[t+1]=Tt[1],e[t+2]=Tt[2],e[t+3]=Tt[3],e[t+4]=Tt[4],e[t+5]=Tt[5],e[t+6]=Tt[6],e[t+7]=Tt[7]}function ev(r,e){return Tt[0]=r[e],Tt[1]=r[e+1],Tt[2]=r[e+2],Tt[3]=r[e+3],Tt[4]=r[e+4],Tt[5]=r[e+5],Tt[6]=r[e+6],Tt[7]=r[e+7],D0[0]}var P0,ds,D0,Tt,k0=C(()=>{P0=new Float32Array([-0]),ds=new Uint8Array(P0.buffer);D0=new Float64Array([-0]),Tt=new Uint8Array(D0.buffer)});var iL,aL,nr,Gs,tv,L0=C(()=>{iL=BigInt(Number.MAX_SAFE_INTEGER),aL=BigInt(Number.MIN_SAFE_INTEGER),nr=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Gs;if(e<iL&&e>aL)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>tv&&(s=0n,++n>tv&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return Gs;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Gs}},Gs=new nr(0,0);Gs.toBigInt=function(){return 0n};Gs.zzEncode=Gs.zzDecode=function(){return this};Gs.length=function(){return 1};tv=4294967296n});function rv(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function nv(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function M0(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}var O0=C(()=>{});function Mr(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Wh(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function N0(r){return new R0(r instanceof Uint8Array?r:r.subarray())}var R0,B0=C(()=>{gr();k0();L0();O0();R0=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Mr(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Mr(this,4);return Wh(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Mr(this,4);return Wh(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Mr(this,4);let e=J4(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Mr(this,4);let e=ev(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Mr(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return nv(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Mr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Mr(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new nr(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Mr(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Mr(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Mr(this,8);let e=Wh(this.buf,this.pos+=4),t=Wh(this.buf,this.pos+=4);return new nr(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Dm(this.buf,this.pos);return this.pos+=Ae(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}});function Q(r,e,t){let n=N0(r);return e.decode(n,void 0,t)}var ov=C(()=>{B0()});function U0(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return tt(i);s+i>e&&(n=tt(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var iv=C(()=>{rt()});function K0(){}function lL(r){return globalThis.Buffer!=null?tt(r):cL(r)}function F0(r,e,t){e[t]=r&255}function uL(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function jh(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Rc(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function hL(r,e,t){e.set(r,t)}function dL(r,e,t){e.set(r,t)}function fL(r,e,t){r.length<40?M0(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function H0(){return new Nc}var Ws,z0,cL,Nc,$0,q0=C(()=>{gr();rt();re();k0();L0();iv();O0();Ws=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};z0=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},cL=U0();Nc=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ws(K0,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ws(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new $0((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(jh,10,nr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=nr.fromBigInt(e);return this._push(jh,t.length(),t)}uint64Number(e){return this._push(In,Ae(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=nr.fromBigInt(e).zzEncode();return this._push(jh,t.length(),t)}sint64Number(e){let t=nr.fromNumber(e).zzEncode();return this._push(jh,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(F0,1,e?1:0)}fixed32(e){return this._push(Rc,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=nr.fromBigInt(e);return this._push(Rc,4,t.lo)._push(Rc,4,t.hi)}fixed64Number(e){let t=nr.fromNumber(e);return this._push(Rc,4,t.lo)._push(Rc,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Q4,4,e)}double(e){return this._push(Z4,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(F0,1,0):this.uint32(t)._push(hL,t,e)}string(e){let t=rv(e);return t!==0?this.uint32(t)._push(M0,t,e):this._push(F0,1,0)}fork(){return this.states=new z0(this),this.head=this.tail=new Ws(K0,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ws(K0,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=lL(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};$0=class extends Ws{next;constructor(e,t){super(uL,e,t),this.next=void 0}};globalThis.Buffer!=null&&(Nc.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(dL,e,r),this},Nc.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(fL,e,r),this})});function J(r,e){let t=H0();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var av=C(()=>{q0()});function Yh(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}var hi,V0=C(()=>{(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(hi||(hi={}))});function sr(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,i){let a=e(o);i.int32(a)},n=function(o){let i=o.int32();return e(i)};return Yh("enum",hi.VARINT,t,n)}var cv=C(()=>{V0()});function Z(r,e){return Yh("message",hi.LENGTH_DELIMITED,r,e)}var lv=C(()=>{V0()});var _e,Bc,wr=C(()=>{ov();av();cv();lv();B0();q0();_e=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Bc=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}});var Je,G0,Xr,W0,j0=C(()=>{wr();(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Je||(Je={}));(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(G0||(G0={}));(function(r){r.codec=()=>sr(G0)})(Je||(Je={}));(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Je.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Je.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Xr||(Xr={}));(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Je.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Je.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(W0||(W0={}))});function Uc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function xr(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function ge(r,e,t=""){let n=Uc(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function js(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");xr(r.outputLen),xr(r.blockLen)}function di(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function dv(r,e){ge(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function kn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Xh(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Or(r,e){return r<<32-e|r>>>e}function Ys(r){if(ge(r),fv)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=pL[r[t]];return e}function hv(r){if(r>=Dn._0&&r<=Dn._9)return r-Dn._0;if(r>=Dn.A&&r<=Dn.F)return r-(Dn.A-10);if(r>=Dn.a&&r<=Dn.f)return r-(Dn.a-10)}function Xs(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(fv)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=hv(r.charCodeAt(o)),a=hv(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function Rr(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];ge(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function pv(r,e={}){let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function Qr(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var fv,pL,Dn,mv,Jr=C(()=>{fv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",pL=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));Dn={_0:48,_9:57,A:65,F:70,a:97,f:102};mv=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])})});function fs(r){if(isNaN(r)||r<=0)throw new B("random bytes length must be a Number bigger than 0");return Qr(r)}var gv=C(()=>{V();Jr()});function yv(r,e,t){return r&e^~r&t}function bv(r,e,t){return r&e^r&t^e&t}var Qh,Ln,wv=C(()=>{Jr();Qh=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Xh(this.buffer)}update(e){di(this),ge(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=Xh(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){di(this),dv(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,kn(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let d=i;d<s;d++)t[d]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=Xh(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ln=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var mL,ps,Y0,X0,Yt,Kc=C(()=>{wv();Jr();mL=Uint32Array.from([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]),ps=new Uint32Array(64),Y0=class extends Qh{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)ps[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=ps[d-15],f=ps[d-2],h=Or(p,7)^Or(p,18)^p>>>3,m=Or(f,17)^Or(f,19)^f>>>10;ps[d]=m+ps[d-7]+h+ps[d-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let p=Or(a,6)^Or(a,11)^Or(a,25),f=u+p+yv(a,c,l)+mL[d]+ps[d]|0,m=(Or(n,2)^Or(n,13)^Or(n,22))+bv(n,s,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=s,s=n,n=f+m|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){kn(ps)}destroy(){this.set(0,0,0,0,0,0,0,0),kn(this.buffer)}},X0=class extends Y0{A=Ln[0]|0;B=Ln[1]|0;C=Ln[2]|0;D=Ln[3]|0;E=Ln[4]|0;F=Ln[5]|0;G=Ln[6]|0;H=Ln[7]|0;constructor(){super(32)}},Yt=pv(()=>new X0,mv(1))});var fi,Fc,xv=C(()=>{ei();Sc();Ne();Q0();fi=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=zc.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return jr.createV1(114,this._multihash)}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return Ev(this.jwk,t,e,n)}},Fc=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=zc.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return vv(this.jwk,e,t)}}});var zc={};z(zc,{MAX_RSA_KEY_SIZE:()=>J0,generateRSAKeyPair:()=>a2,jwkToJWKKeyPair:()=>Iv,jwkToPkcs1:()=>wL,jwkToPkix:()=>r2,jwkToRSAPrivateKey:()=>i2,pkcs1MessageToJwk:()=>e2,pkcs1MessageToRSAPrivateKey:()=>n2,pkcs1ToJwk:()=>bL,pkcs1ToRSAPrivateKey:()=>Sv,pkixMessageToJwk:()=>t2,pkixMessageToRSAPublicKey:()=>o2,pkixToJwk:()=>xL,pkixToRSAPublicKey:()=>s2});function bL(r){let e=Pn(r);return e2(e)}function e2(r){return{n:T(r[1],"base64url"),e:T(r[2],"base64url"),d:T(r[3],"base64url"),p:T(r[4],"base64url"),q:T(r[5],"base64url"),dp:T(r[6],"base64url"),dq:T(r[7],"base64url"),qi:T(r[8],"base64url"),kty:"RSA"}}function wL(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new B("JWK was missing components");return Lr([Nt(Uint8Array.from([0])),Nt(D(r.n,"base64url")),Nt(D(r.e,"base64url")),Nt(D(r.d,"base64url")),Nt(D(r.p,"base64url")),Nt(D(r.q,"base64url")),Nt(D(r.dp,"base64url")),Nt(D(r.dq,"base64url")),Nt(D(r.qi,"base64url"))]).subarray()}function xL(r){let e=Pn(r,{offset:0});return t2(e)}function t2(r){let e=Pn(r[1],{offset:0});return{kty:"RSA",n:T(e[0],"base64url"),e:T(e[1],"base64url")}}function r2(r){if(r.n==null||r.e==null)throw new B("JWK was missing components");return Lr([yL,Lc(Lr([Nt(D(r.n,"base64url")),Nt(D(r.e,"base64url"))]))]).subarray()}function Sv(r){let e=Pn(r);return n2(e)}function n2(r){let e=e2(r);return i2(e)}function s2(r,e){if(r.byteLength>=gL)throw new Xo("Key size is too large");let t=Pn(r,{offset:0});return o2(t,r,e)}function o2(r,e,t){let n=t2(r);if(t==null){let s=Yt(Xr.encode({Type:Je.RSA,Data:e}));t=us(Z0,s)}return new fi(n,t)}function i2(r){if(Cv(r)>J0)throw new B("Key size is too large");let e=Iv(r),t=Yt(Xr.encode({Type:Je.RSA,Data:r2(e.publicKey)})),n=us(Z0,t);return new Fc(e.privateKey,new fi(e.publicKey,n))}async function a2(r){if(r>J0)throw new B("Key size is too large");let e=await Av(r),t=Yt(Xr.encode({Type:Je.RSA,Data:r2(e.publicKey)})),n=us(Z0,t);return new Fc(e.privateKey,new fi(e.publicKey,n))}function Iv(r){if(r==null)throw new B("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var J0,Z0,gL,yL,c2=C(()=>{V();Kc();Nh();re();ie();j0();b0();xv();Q0();J0=8192,Z0=18,gL=1062,yL=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0])});async function Av(r,e){let t=await vL("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function vv(r,e,t){t?.signal?.throwIfAborted();let n=Jh.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)n.update(e);else for(let s of e)n.update(s);return n.sign({format:"jwk",key:r})}function Ev(r,e,t,n){n?.signal?.throwIfAborted();let s=Jh.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)s.update(t);else for(let o of t)s.update(o);return s.verify({format:"jwk",key:r},e)}function Cv(r){if(r.kty!=="RSA")throw new B("Invalid key type");if(r.n==null)throw new B("Invalid key modulus");return D(r.n,"base64url").length*8}var Jh,Tv,vL,Q0=C(()=>{Jh=ae(te("node:crypto"),1),Tv=te("node:util");V();re();c2();vL=(0,Tv.promisify)(Jh.default.generateKeyPair)});function $c(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function _v(r){if(typeof r=="bigint"){if(!Zh(r))throw new Error("positive bigint expected, got "+r)}else xr(r);return r}function Hc(r){let e=_v(r).toString(16);return e.length&1?"0"+e:e}function Pv(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?u2:BigInt("0x"+r)}function pi(r){return Pv(Ys(r))}function mi(r){return Pv(Ys(td(ge(r)).reverse()))}function ed(r,e){xr(e),r=_v(r);let t=Xs(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function qc(r,e){return ed(r,e).reverse()}function td(r){return Uint8Array.from(r)}function EL(r,e,t){return Zh(r)&&Zh(e)&&Zh(t)&&e<=r&&r<t}function Vc(r,e,t,n){if(!EL(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function h2(r){let e;for(e=0;r>u2;r>>=l2,e+=1);return e}function Dv(r,e,t){if(xr(r,"hashLen"),xr(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=g=>new Uint8Array(g),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},p=(...g)=>t(l,Rr(c,...g)),f=(g=s)=>{l=p(o,g),c=p(),g.length!==0&&(l=p(i,g),c=p())},h=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,y=[];for(;g<e;){c=p();let b=c.slice();y.push(b),g+=c.length}return Rr(...y)};return(g,y)=>{d(),f(g);let b;for(;!(b=y(h()));)f();return d(),b}}function Qs(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,a){let c=r[o];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(e,!1),s(t,!0)}function d2(r){let e=new WeakMap;return(t,...n)=>{let s=e.get(t);if(s!==void 0)return s;let o=r(t,...n);return e.set(t,o),o}}var u2,l2,Zh,Gc,Wc=C(()=>{Jr();Jr();u2=BigInt(0),l2=BigInt(1);Zh=r=>typeof r=="bigint"&&u2<=r;Gc=r=>(l2<<BigInt(r))-l2});function Ut(r,e){let t=r%e;return t>=Kt?t:e+t}function Me(r,e,t){let n=r;for(;e-- >Kt;)n*=n,n%=t;return n}function kv(r,e){if(r===Kt)throw new Error("invert: expected non-zero number");if(e<=Kt)throw new Error("invert: expected positive modulus, got "+e);let t=Ut(r,e),n=e,s=Kt,o=_t,i=_t,a=Kt;for(;t!==Kt;){let l=n/t,u=n%t,d=s-i*l,p=o-a*l;n=t,t=u,s=i,o=a,i=d,a=p}if(n!==_t)throw new Error("invert: does not exist");return Ut(s,e)}function p2(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Uv(r,e){let t=(r.ORDER+_t)/Ov,n=r.pow(e,t);return p2(r,n,e),n}function AL(r,e){let t=(r.ORDER-Rv)/Nv,n=r.mul(e,Js),s=r.pow(n,t),o=r.mul(e,s),i=r.mul(r.mul(o,Js),s),a=r.mul(o,r.sub(i,r.ONE));return p2(r,a,e),a}function CL(r){let e=gi(r),t=Kv(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+SL)/Bv;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),d=a.mul(l,s),p=a.mul(l,o),f=a.eql(a.sqr(u),c),h=a.eql(a.sqr(d),c);l=a.cmov(l,u,f),u=a.cmov(p,d,h);let m=a.eql(a.sqr(u),c),g=a.cmov(l,u,m);return p2(a,g,c),g}}function Kv(r){if(r<Mv)throw new Error("sqrt is not defined for small field");let e=r-_t,t=0;for(;e%Js===Kt;)e/=Js,t++;let n=Js,s=gi(r);for(;Lv(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Uv;let o=s.pow(n,e),i=(e+_t)/Js;return function(c,l){if(c.is0(l))return l;if(Lv(c,l)!==1)throw new Error("Cannot find square root");let u=t,d=c.mul(c.ONE,o),p=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let h=1,m=c.sqr(p);for(;!c.eql(m,c.ONE);)if(h++,m=c.sqr(m),h===u)throw new Error("Cannot find square root");let g=_t<<BigInt(u-h-1),y=c.pow(d,g);u=h,d=c.sqr(y),p=c.mul(p,d),f=c.mul(f,y)}return f}}function TL(r){return r%Ov===Mv?Uv:r%Nv===Rv?AL:r%Bv===IL?CL(r):Kv(r)}function m2(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=_L.reduce((n,s)=>(n[s]="function",n),e);return Qs(r,t),r}function PL(r,e,t){if(t<Kt)throw new Error("invalid exponent, negatives unsupported");if(t===Kt)return r.ONE;if(t===_t)return e;let n=r.ONE,s=e;for(;t>Kt;)t&_t&&(n=r.mul(n,s)),s=r.sqr(s),t>>=_t;return n}function jc(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),s=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),o=r.inv(s);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),o),n}function Lv(r,e){let t=(r.ORDER-_t)/Js,n=r.pow(e,t),s=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function DL(r,e){e!==void 0&&xr(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function gi(r,e={}){return new f2(r,e)}function Fv(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function g2(r){let e=Fv(r);return e+Math.ceil(e/2)}function y2(r,e,t=!1){ge(r);let n=r.length,s=Fv(e),o=g2(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?mi(r):pi(r),a=Ut(i,e-_t)+_t;return t?qc(a,s):ed(a,s)}var Kt,_t,Js,Mv,Ov,Rv,SL,Nv,IL,Bv,_L,f2,yi=C(()=>{Wc();Kt=BigInt(0),_t=BigInt(1),Js=BigInt(2),Mv=BigInt(3),Ov=BigInt(4),Rv=BigInt(5),SL=BigInt(7),Nv=BigInt(8),IL=BigInt(9),Bv=BigInt(16);_L=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];f2=class{ORDER;BITS;BYTES;isLE;ZERO=Kt;ONE=_t;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Kt)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=DL(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Ut(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Kt<=e&&e<this.ORDER}is0(e){return e===Kt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&_t)===_t}neg(e){return Ut(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Ut(e*e,this.ORDER)}add(e,t){return Ut(e+t,this.ORDER)}sub(e,t){return Ut(e-t,this.ORDER)}mul(e,t){return Ut(e*t,this.ORDER)}pow(e,t){return PL(this,e,t)}div(e,t){return Ut(e*kv(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return kv(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=TL(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?qc(e,this.BYTES):ed(e,this.BYTES)}fromBytes(e,t=!1){ge(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?mi(e):pi(e);if(a&&(c=Ut(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return jc(this,e)}cmov(e,t,n){return n?t:e}}});function Yc(r,e){let t=e.negate();return r?t:e}function v2(r,e){let t=jc(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function qv(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function b2(r,e){qv(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),s=2**r,o=Gc(r),i=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function zv(r,e,t){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Zs);let l=e*n,u=l+Math.abs(a)-1,d=a===0,p=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:p,isNegF:f,offsetF:l}}function x2(r){return Vv.get(r)||1}function $v(r){if(r!==bi)throw new Error("invalid wNAF")}function Gv(r,e,t,n){let s=e,o=r.ZERO,i=r.ZERO;for(;t>bi||n>bi;)t&Zs&&(o=o.add(s)),n&Zs&&(i=i.add(s)),s=s.double(),t>>=Zs,n>>=Zs;return{p1:o,p2:i}}function Hv(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return m2(e),e}else return gi(r,{isLE:t})}function Wv(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>bi))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Hv(e.p,t.Fp,n),o=Hv(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function nd(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var bi,Zs,w2,Vv,rd,E2=C(()=>{Wc();yi();bi=BigInt(0),Zs=BigInt(1);w2=new WeakMap,Vv=new WeakMap;rd=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let s=e;for(;t>bi;)t&Zs&&(n=n.add(s)),s=s.double(),t>>=Zs;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=b2(t,this.bits),o=[],i=e,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=b2(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:f}=zv(n,a,i);n=c,u?o=o.add(Yc(p,t[f])):s=s.add(Yc(d,t[l]))}return $v(n),{p:s,f:o}}wNAFUnsafe(e,t,n,s=this.ZERO){let o=b2(e,this.bits);for(let i=0;i<o.windows&&n!==bi;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=zv(n,i,o);if(n=a,!l){let d=t[c];s=s.add(u?d.negate():d)}}return $v(n),s}getPrecomputes(e,t,n){let s=w2.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(s=n(s)),w2.set(t,s))),s}cached(e,t,n){let s=x2(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){let o=x2(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,s)}createCache(e,t){qv(t,this.bits),Vv.set(e,t),w2.delete(e)}hasCache(e){return x2(e)!==1}}});var sd,wi,S2=C(()=>{Jr();sd=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(js(e),ge(t,void 0,"key"),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 n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),kn(s)}update(e){return di(this),this.iHash.update(e),this}digestInto(e){di(this),ge(e,this.outputLen,"output"),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||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wi=(r,e,t)=>new sd(r,e).update(t).digest();wi.create=(r,e)=>new sd(r,e)});function kL(r,e,t){let[[n,s],[o,i]]=e,a=jv(i*r,t),c=jv(-s*r,t),l=r-a*n-c*o,u=-a*s-c*i,d=l<Mn,p=u<Mn;d&&(l=-l),p&&(u=-u);let f=Gc(Math.ceil(h2(t)/2))+xi;if(l<Mn||l>=f||u<Mn||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:d,k1:l,k2neg:p,k2:u}}function A2(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function I2(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return $c(t.lowS,"lowS"),$c(t.prehash,"prehash"),t.format!==void 0&&A2(t.format),t}function Xv(r,e={}){let t=Wv("weierstrass",r,e),{Fp:n,Fn:s}=t,o=t.CURVE,{h:i,n:a}=o;Qs(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Jv(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(H,L,P){let{x:_,y:M}=L.toAffine(),O=n.toBytes(_);if($c(P,"isCompressed"),P){u();let R=!n.isOdd(M);return Rr(Qv(R),O)}else return Rr(Uint8Array.of(4),O,n.toBytes(M))}function p(H){ge(H,void 0,"Point");let{publicKey:L,publicKeyUncompressed:P}=l,_=H.length,M=H[0],O=H.subarray(1);if(_===L&&(M===2||M===3)){let R=n.fromBytes(O);if(!n.isValid(R))throw new Error("bad point: is not on curve, wrong x");let k=m(R),N;try{N=n.sqrt(k)}catch(ve){let ue=ve instanceof Error?": "+ve.message:"";throw new Error("bad point: is not on curve, sqrt error"+ue)}u();let K=n.isOdd(N);return(M&1)===1!==K&&(N=n.neg(N)),{x:R,y:N}}else if(_===P&&M===4){let R=n.BYTES,k=n.fromBytes(O.subarray(0,R)),N=n.fromBytes(O.subarray(R,R*2));if(!g(k,N))throw new Error("bad point: is not on curve");return{x:k,y:N}}else throw new Error(`bad point: got length ${_}, expected compressed=${L} or uncompressed=${P}`)}let f=e.toBytes||d,h=e.fromBytes||p;function m(H){let L=n.sqr(H),P=n.mul(L,H);return n.add(n.add(P,n.mul(H,o.a)),o.b)}function g(H,L){let P=n.sqr(L),_=m(H);return n.eql(P,_)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(o.a,od),LL),b=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(y,b)))throw new Error("bad curve params: a or b");function E(H,L,P=!1){if(!n.isValid(L)||P&&n.is0(L))throw new Error(`bad point coordinate ${H}`);return L}function w(H){if(!(H instanceof A))throw new Error("Weierstrass Point expected")}function v(H){if(!c||!c.basises)throw new Error("no endo");return kL(H,c.basises,s.ORDER)}let S=d2((H,L)=>{let{X:P,Y:_,Z:M}=H;if(n.eql(M,n.ONE))return{x:P,y:_};let O=H.is0();L==null&&(L=O?n.ONE:n.inv(M));let R=n.mul(P,L),k=n.mul(_,L),N=n.mul(M,L);if(O)return{x:n.ZERO,y:n.ZERO};if(!n.eql(N,n.ONE))throw new Error("invZ was invalid");return{x:R,y:k}}),x=d2(H=>{if(H.is0()){if(e.allowInfinityPoint&&!n.is0(H.Y))return;throw new Error("bad point: ZERO")}let{x:L,y:P}=H.toAffine();if(!n.isValid(L)||!n.isValid(P))throw new Error("bad point: x or y not field elements");if(!g(L,P))throw new Error("bad point: equation left != right");if(!H.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function I(H,L,P,_,M){return P=new A(n.mul(P.X,H),P.Y,P.Z),L=Yc(_,L),P=Yc(M,P),L.add(P)}class A{static BASE=new A(o.Gx,o.Gy,n.ONE);static ZERO=new A(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(L,P,_){this.X=E("x",L),this.Y=E("y",P,!0),this.Z=E("z",_),Object.freeze(this)}static CURVE(){return o}static fromAffine(L){let{x:P,y:_}=L||{};if(!L||!n.isValid(P)||!n.isValid(_))throw new Error("invalid affine point");if(L instanceof A)throw new Error("projective point not allowed");return n.is0(P)&&n.is0(_)?A.ZERO:new A(P,_,n.ONE)}static fromBytes(L){let P=A.fromAffine(h(ge(L,void 0,"point")));return P.assertValidity(),P}static fromHex(L){return A.fromBytes(Xs(L))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(L=8,P=!0){return ee.createCache(this,L),P||this.multiply(od),this}assertValidity(){x(this)}hasEvenY(){let{y:L}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(L)}equals(L){w(L);let{X:P,Y:_,Z:M}=this,{X:O,Y:R,Z:k}=L,N=n.eql(n.mul(P,k),n.mul(O,M)),K=n.eql(n.mul(_,k),n.mul(R,M));return N&&K}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){let{a:L,b:P}=o,_=n.mul(P,od),{X:M,Y:O,Z:R}=this,k=n.ZERO,N=n.ZERO,K=n.ZERO,F=n.mul(M,M),ve=n.mul(O,O),ue=n.mul(R,R),se=n.mul(M,O);return se=n.add(se,se),K=n.mul(M,R),K=n.add(K,K),k=n.mul(L,K),N=n.mul(_,ue),N=n.add(k,N),k=n.sub(ve,N),N=n.add(ve,N),N=n.mul(k,N),k=n.mul(se,k),K=n.mul(_,K),ue=n.mul(L,ue),se=n.sub(F,ue),se=n.mul(L,se),se=n.add(se,K),K=n.add(F,F),F=n.add(K,F),F=n.add(F,ue),F=n.mul(F,se),N=n.add(N,F),ue=n.mul(O,R),ue=n.add(ue,ue),F=n.mul(ue,se),k=n.sub(k,F),K=n.mul(ue,ve),K=n.add(K,K),K=n.add(K,K),new A(k,N,K)}add(L){w(L);let{X:P,Y:_,Z:M}=this,{X:O,Y:R,Z:k}=L,N=n.ZERO,K=n.ZERO,F=n.ZERO,ve=o.a,ue=n.mul(o.b,od),se=n.mul(P,O),pe=n.mul(_,R),Te=n.mul(M,k),Qe=n.add(P,_),be=n.add(O,R);Qe=n.mul(Qe,be),be=n.add(se,pe),Qe=n.sub(Qe,be),be=n.add(P,M);let et=n.add(O,k);return be=n.mul(be,et),et=n.add(se,Te),be=n.sub(be,et),et=n.add(_,M),N=n.add(R,k),et=n.mul(et,N),N=n.add(pe,Te),et=n.sub(et,N),F=n.mul(ve,be),N=n.mul(ue,Te),F=n.add(N,F),N=n.sub(pe,F),F=n.add(pe,F),K=n.mul(N,F),pe=n.add(se,se),pe=n.add(pe,se),Te=n.mul(ve,Te),be=n.mul(ue,be),pe=n.add(pe,Te),Te=n.sub(se,Te),Te=n.mul(ve,Te),be=n.add(be,Te),se=n.mul(pe,be),K=n.add(K,se),se=n.mul(et,be),N=n.mul(Qe,N),N=n.sub(N,se),se=n.mul(Qe,pe),F=n.mul(et,F),F=n.add(F,se),new A(N,K,F)}subtract(L){return this.add(L.negate())}is0(){return this.equals(A.ZERO)}multiply(L){let{endo:P}=e;if(!s.isValidNot0(L))throw new Error("invalid scalar: out of range");let _,M,O=R=>ee.cached(this,R,k=>v2(A,k));if(P){let{k1neg:R,k1:k,k2neg:N,k2:K}=v(L),{p:F,f:ve}=O(k),{p:ue,f:se}=O(K);M=ve.add(se),_=I(P.beta,F,ue,R,N)}else{let{p:R,f:k}=O(L);_=R,M=k}return v2(A,[_,M])[0]}multiplyUnsafe(L){let{endo:P}=e,_=this;if(!s.isValid(L))throw new Error("invalid scalar: out of range");if(L===Mn||_.is0())return A.ZERO;if(L===xi)return _;if(ee.hasCache(this))return this.multiply(L);if(P){let{k1neg:M,k1:O,k2neg:R,k2:k}=v(L),{p1:N,p2:K}=Gv(A,_,O,k);return I(P.beta,N,K,M,R)}else return ee.unsafe(_,L)}toAffine(L){return S(this,L)}isTorsionFree(){let{isTorsionFree:L}=e;return i===xi?!0:L?L(A,this):ee.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:L}=e;return i===xi?this:L?L(A,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(L=!0){return $c(L,"isCompressed"),this.assertValidity(),f(A,this,L)}toHex(L=!0){return Ys(this.toBytes(L))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let j=s.BITS,ee=new rd(A,e.endo?Math.ceil(j/2):j);return A.BASE.precompute(8),A}function Qv(r){return Uint8Array.of(r?2:3)}function Jv(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ML(r,e={}){let{Fn:t}=r,n=e.randomBytes||Qr,s=Object.assign(Jv(r.Fp,t),{seed:g2(t.ORDER)});function o(f){try{let h=t.fromBytes(f);return t.isValidNot0(h)}catch{return!1}}function i(f,h){let{publicKey:m,publicKeyUncompressed:g}=s;try{let y=f.length;return h===!0&&y!==m||h===!1&&y!==g?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=n(s.seed)){return y2(ge(f,s.seed,"seed"),t.ORDER)}function c(f,h=!0){return r.BASE.multiply(t.fromBytes(f)).toBytes(h)}function l(f){let{secretKey:h,publicKey:m,publicKeyUncompressed:g}=s;if(!Uc(f)||"_lengths"in t&&t._lengths||h===m)return;let y=ge(f,void 0,"key").length;return y===m||y===g}function u(f,h,m=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(h)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(f);return r.fromBytes(h).multiply(g).toBytes(m)}let d={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},p=nd(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:r,utils:d,lengths:s})}function Zv(r,e,t={}){js(e),Qs(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Qr,s=t.hmac||((P,_)=>wi(e,P,_)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:p,lengths:f}=ML(r,t),h={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Yv<o.ORDER;function g(P){let _=a>>xi;return P>_}function y(P,_){if(!i.isValidNot0(_))throw new Error(`invalid signature ${P}: out of range 1..Point.Fn.ORDER`);return _}function b(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function E(P,_){A2(_);let M=f.signature,O=_==="compact"?M:_==="recovered"?M+1:void 0;return ge(P,O)}class w{r;s;recovery;constructor(_,M,O){if(this.r=y("r",_),this.s=y("s",M),O!=null){if(b(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(_,M=h.format){E(_,M);let O;if(M==="der"){let{r:K,s:F}=ms.toSig(ge(_));return new w(K,F)}M==="recovered"&&(O=_[0],M="compact",_=_.subarray(1));let R=f.signature/2,k=_.subarray(0,R),N=_.subarray(R,R*2);return new w(i.fromBytes(k),i.fromBytes(N),O)}static fromHex(_,M){return this.fromBytes(Xs(_),M)}assertRecovery(){let{recovery:_}=this;if(_==null)throw new Error("invalid recovery id: must be present");return _}addRecoveryBit(_){return new w(this.r,this.s,_)}recoverPublicKey(_){let{r:M,s:O}=this,R=this.assertRecovery(),k=R===2||R===3?M+a:M;if(!o.isValid(k))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let N=o.toBytes(k),K=r.fromBytes(Rr(Qv((R&1)===0),N)),F=i.inv(k),ve=S(ge(_,void 0,"msgHash")),ue=i.create(-ve*F),se=i.create(O*F),pe=r.BASE.multiplyUnsafe(ue).add(K.multiplyUnsafe(se));if(pe.is0())throw new Error("invalid recovery: point at infinify");return pe.assertValidity(),pe}hasHighS(){return g(this.s)}toBytes(_=h.format){if(A2(_),_==="der")return Xs(ms.hexFromSig(this));let{r:M,s:O}=this,R=i.toBytes(M),k=i.toBytes(O);return _==="recovered"?(b(),Rr(Uint8Array.of(this.assertRecovery()),R,k)):Rr(R,k)}toHex(_){return Ys(this.toBytes(_))}}let v=t.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");let M=pi(_),O=_.length*8-c;return O>0?M>>BigInt(O):M},S=t.bits2int_modN||function(_){return i.create(v(_))},x=Gc(c);function I(P){return Vc("num < 2^"+c,P,Mn,x),i.toBytes(P)}function A(P,_){return ge(P,void 0,"message"),_?ge(e(P),void 0,"prehashed message"):P}function j(P,_,M){let{lowS:O,prehash:R,extraEntropy:k}=I2(M,h);P=A(P,R);let N=S(P),K=i.fromBytes(_);if(!i.isValidNot0(K))throw new Error("invalid private key");let F=[I(K),I(N)];if(k!=null&&k!==!1){let pe=k===!0?n(f.secretKey):k;F.push(ge(pe,void 0,"extraEntropy"))}let ve=Rr(...F),ue=N;function se(pe){let Te=v(pe);if(!i.isValidNot0(Te))return;let Qe=i.inv(Te),be=r.BASE.multiply(Te).toAffine(),et=i.create(be.x);if(et===Mn)return;let Wo=i.create(Qe*i.create(ue+et*K));if(Wo===Mn)return;let ih=(be.x===et?0:2)|Number(be.y&xi),ac=Wo;return O&&g(Wo)&&(ac=i.neg(Wo),ih^=1),new w(et,ac,m?void 0:ih)}return{seed:ve,k2sig:se}}function ee(P,_,M={}){let{seed:O,k2sig:R}=j(P,_,M);return Dv(e.outputLen,i.BYTES,s)(O,R).toBytes(M.format)}function H(P,_,M,O={}){let{lowS:R,prehash:k,format:N}=I2(O,h);if(M=ge(M,void 0,"publicKey"),_=A(_,k),!Uc(P)){let K=P instanceof w?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+K)}E(P,N);try{let K=w.fromBytes(P,N),F=r.fromBytes(M);if(R&&K.hasHighS())return!1;let{r:ve,s:ue}=K,se=S(_),pe=i.inv(ue),Te=i.create(se*pe),Qe=i.create(ve*pe),be=r.BASE.multiplyUnsafe(Te).add(F.multiplyUnsafe(Qe));return be.is0()?!1:i.create(be.x)===ve}catch{return!1}}function L(P,_,M={}){let{prehash:O}=I2(M,h);return _=A(_,O),w.fromBytes(P,"recovered").recoverPublicKey(_).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:p,lengths:f,Point:r,sign:ee,verify:H,recoverPublicKey:L,Signature:w,hash:e})}var jv,C2,ms,Mn,xi,Yv,od,LL,eE=C(()=>{S2();Jr();Wc();E2();yi();jv=(r,e)=>(r+(r>=0?e:-e)/Yv)/e;C2=class extends Error{constructor(e=""){super(e)}},ms={Err:C2,_tlv:{encode:(r,e)=>{let{Err:t}=ms;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=Hc(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?Hc(s.length/2|128):"";return Hc(r)+o+s+e},decode(r,e){let{Err:t}=ms,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=ms;if(r<Mn)throw new e("integer: negative integers are not allowed");let t=Hc(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=ms;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return pi(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=ms,s=ge(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=ms,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},Mn=BigInt(0),xi=BigInt(1),Yv=BigInt(2),od=BigInt(3),LL=BigInt(4)});function RL(r){let e=_2.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Me(u,t,e)*u%e,p=Me(d,t,e)*u%e,f=Me(p,tE,e)*l%e,h=Me(f,s,e)*f%e,m=Me(h,o,e)*h%e,g=Me(m,a,e)*m%e,y=Me(g,c,e)*g%e,b=Me(y,a,e)*m%e,E=Me(b,t,e)*u%e,w=Me(E,i,e)*h%e,v=Me(w,n,e)*l%e,S=Me(v,tE,e);if(!T2.eql(T2.sqr(S),r))throw new Error("Cannot find square root");return S}var _2,OL,tE,T2,NL,st,eo=C(()=>{Kc();yi();eE();_2={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},OL={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},tE=BigInt(2);T2=gi(_2.p,{sqrt:RL}),NL=Xv(_2,{Fp:T2,endo:OL}),st=Zv(NL,Yt)});var id,ad,rE=C(()=>{id=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},ad=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}});function nE(r,e,t){t?.signal?.throwIfAborted();let n=P2.default.createHash("sha256");if(e instanceof Uint8Array)n.update(e);else for(let o of e)n.update(o);let s=n.digest();try{return st.sign(s,r,{prehash:!1,format:"der"})}catch(o){throw new id(String(o))}}function sE(r,e,t,n){n?.signal?.throwIfAborted();let s=P2.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return st.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new ad(String(i))}}var P2,oE=C(()=>{P2=ae(te("node:crypto"),1);eo();rE()});var Xc,cd,iE=C(()=>{ei();Sc();Bh();Ne();Bt();D2();oE();Xc=class{type="secp256k1";raw;_key;constructor(e){this._key=lE(e),this.raw=aE(this._key)}toMultihash(){return si.digest(dt(this))}toCID(){return jr.createV1(114,this.toMultihash())}toString(){return wt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return sE(this._key,t,e,n)}},cd=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=cE(e),this.publicKey=new Xc(t??uE(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return nE(this.raw,e,t)}}});function k2(r){return new Xc(r)}async function hE(){let r=BL();return new cd(r)}function aE(r){return st.Point.fromBytes(r).toBytes()}function cE(r){try{return st.getPublicKey(r,!0),r}catch(e){throw new hc(String(e))}}function lE(r){try{return st.Point.fromBytes(r),r}catch(e){throw new Xo(String(e))}}function uE(r){try{return st.getPublicKey(r,!0)}catch(e){throw new hc(String(e))}}function BL(){return st.utils.randomSecretKey()}var D2=C(()=>{V();eo();iE()});async function dE(r,e){if(r==="Ed25519")return X4();if(r==="secp256k1")return hE();if(r==="RSA")return a2(UL(e));if(r==="ECDSA")return $4(KL(e));throw new is}function Ft(r,e){let{Type:t,Data:n}=Xr.decode(r),s=n??new Uint8Array;switch(t){case Je.RSA:return s2(s,e);case Je.Ed25519:return _0(s);case Je.secp256k1:return k2(s);case Je.ECDSA:return S0(s);default:throw new is}}function fE(r){let{Type:e,Data:t}=Xr.decode(r.digest),n=t??new Uint8Array;switch(e){case Je.Ed25519:return _0(n);case Je.secp256k1:return k2(n);case Je.ECDSA:return S0(n);default:throw new is}}function dt(r){return Xr.encode({Type:Je[r.type],Data:r.raw})}function UL(r){return r==null?2048:parseInt(r,10)}function KL(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new B("Unsupported curve, should be P-256, P-384 or P-521")}var Bt=C(()=>{V();I0();T0();j0();c2();D2()});function pE(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Nr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var Mee,vi=C(()=>{Mee=new Uint8Array(0)});function FL(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var zL,$L,mE,gE=C(()=>{zL=FL,$L=zL,mE=$L});function yE(r,e){return new O2({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function bE({name:r,prefix:e,encode:t,decode:n}){return new R2(r,e,t,n)}function Ei({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=mE(t,r);return bE({prefix:e,name:r,encode:n,decode:o=>Nr(s(o))})}function HL(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function qL(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function VL(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Zr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=VL(n);return bE({prefix:e,name:r,encode(o){return qL(o,n,t)},decode(o){return HL(o,s,t,r)}})}var L2,M2,O2,R2,ld=C(()=>{vi();gE();L2=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},M2=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 yE(this,e)}},O2=class{decoders;constructor(e){this.decoders=e}or(e){return yE(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};R2=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new L2(e,t,n),this.decoder=new M2(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var or,Fee,ud=C(()=>{ld();or=Ei({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Fee=Ei({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var Qc,Hee,qee,Vee,Gee,Wee,jee,Yee,Xee,wE=C(()=>{ld();Qc=Zr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Hee=Zr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qee=Zr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Vee=Zr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gee=Zr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Wee=Zr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jee=Zr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Yee=Zr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xee=Zr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var hd,Zee,xE=C(()=>{ld();hd=Ei({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zee=Ei({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});function SE(r,e,t){e=e||[],t=t||0;for(var n=t;r>=YL;)e[t++]=r&255|vE,r/=128;for(;r&jL;)e[t++]=r&255|vE,r>>>=7;return e[t]=r|0,SE.bytes=t-n+1,e}function N2(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw N2.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&EE)<<s:(i&EE)*Math.pow(2,s),s+=7}while(i>=QL);return N2.bytes=o-n,t}var GL,vE,WL,jL,YL,XL,QL,EE,JL,ZL,eM,tM,rM,nM,sM,oM,iM,aM,cM,lM,Jc,IE=C(()=>{GL=SE,vE=128,WL=127,jL=~WL,YL=Math.pow(2,31);XL=N2,QL=128,EE=127;JL=Math.pow(2,7),ZL=Math.pow(2,14),eM=Math.pow(2,21),tM=Math.pow(2,28),rM=Math.pow(2,35),nM=Math.pow(2,42),sM=Math.pow(2,49),oM=Math.pow(2,56),iM=Math.pow(2,63),aM=function(r){return r<JL?1:r<ZL?2:r<eM?3:r<tM?4:r<rM?5:r<nM?6:r<sM?7:r<oM?8:r<iM?9:10},cM={encode:GL,decode:XL,encodingLength:aM},lM=cM,Jc=lM});function Zc(r,e=0){return[Jc.decode(r,e),Jc.decode.bytes]}function Si(r,e,t=0){return Jc.encode(r,e,t),e}function Ii(r){return Jc.encodingLength(r)}var B2=C(()=>{IE()});function Ci(r,e){let t=e.byteLength,n=Ii(r),s=n+Ii(t),o=new Uint8Array(s+t);return Si(r,o,0),Si(t,o,n),o.set(e,s),new Ai(r,t,e,o)}function el(r){let e=Nr(r),[t,n]=Zc(e),[s,o]=Zc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ai(t,s,i,e)}function CE(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&pE(r.bytes,t.bytes)}}var Ai,tl=C(()=>{vi();B2();Ai=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}}});var TE=C(()=>{});function _E(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return hM(t,U2(r),e??or.encoder);default:return dM(t,U2(r),e??Qc.encoder)}}function U2(r){let e=PE.get(r);if(e==null){let t=new Map;return PE.set(r,t),t}return e}function uM(r,e){switch(r[0]){case"Q":{let t=e??or;return[or.prefix,t.decode(`${or.prefix}${r}`)]}case or.prefix:{let t=e??or;return[or.prefix,t.decode(r)]}case Qc.prefix:{let t=e??Qc;return[Qc.prefix,t.decode(r)]}case hd.prefix:{let t=e??hd;return[hd.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function hM(r,e,t){let{prefix:n}=t;if(n!==or.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function dM(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}function DE(r,e,t){let n=Ii(r),s=n+Ii(e),o=new Uint8Array(s+t.byteLength);return Si(r,o,0),Si(e,o,n),o.set(t,s),o}var PE,to,rl,fM,pM,K2=C(()=>{wE();xE();ud();vi();tl();B2();TE();PE=new WeakMap;to=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==rl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==fM)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ci(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&CE(e.multihash,n.multihash)}toString(e){return _E(this,e)}toJSON(){return{"/":_E(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??DE(n,s,o.bytes))}else if(t[pM]===!0){let{version:n,multihash:s,code:o}=t,i=el(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==rl)throw new Error(`Version 0 CID must use dag-pb (code: ${rl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=DE(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,rl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Nr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Ai(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=Zc(e.subarray(t));return t+=p,d},s=n(),o=rl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=uM(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return U2(o).set(n,e),o}};rl=112,fM=18;pM=Symbol.for("@ipld/js-cid/CID")});function gM(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ci(kE,LE(r))}var kE,mM,LE,fd,F2=C(()=>{vi();tl();kE=0,mM="identity",LE=Nr;fd={code:kE,name:mM,encode:LE,digest:gM}});function $2({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new z2(r,e,t,n,s)}function ME(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ci(e,r)}var yM,z2,OE=C(()=>{tl();yM=20;z2=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??yM,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?ME(n,this.code,t?.truncate):n.then(s=>ME(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var H2,RE,mte,NE=C(()=>{H2=ae(te("crypto"),1);vi();OE();RE=$2({name:"sha2-256",code:18,encode:r=>Nr(H2.default.createHash("sha256").update(r).digest())}),mte=$2({name:"sha2-512",code:19,encode:r=>Nr(H2.default.createHash("sha512").update(r).digest())})});var BE,bM,nl,sl,ol,il,wM,al,UE=C(()=>{V();ud();K2();F2();Ne();re();ie();BE=Symbol.for("nodejs.util.inspect.custom"),bM=114,nl=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ph]=!0;toString(){return this.string==null&&(this.string=or.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return to.createV1(bM,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[BE](){return`PeerId(${this.toString()})`}},sl=class extends nl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ol=class extends nl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},il=class extends nl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},wM=2336,al=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=fd.digest(D(this.url))}[BE](){return`PeerId(${this.url})`}[Ph]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return to.createV1(wM,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=T(e)),e.toString()===this.toString())}}});var V2={};z(V2,{peerIdFromCID:()=>en,peerIdFromMultihash:()=>Br,peerIdFromPrivateKey:()=>q2,peerIdFromPublicKey:()=>On,peerIdFromString:()=>de});function de(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=el(or.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return en(to.parse(r));if(e==null)throw new B('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=el(e.decode(r))}return Br(t)}function On(r){if(r.type==="Ed25519")return new ol({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new il({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new sl({multihash:r.toCID().multihash,publicKey:r});throw new is}function q2(r){return On(r.publicKey)}function Br(r){if(EM(r))return new sl({multihash:r});if(vM(r))try{let e=fE(r);if(e.type==="Ed25519")return new ol({multihash:r,publicKey:e});if(e.type==="secp256k1")return new il({multihash:r,publicKey:e})}catch{let t=T(r.digest);return new al(new URL(t))}throw new vh("Supplied PeerID Multihash is invalid")}function en(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==xM&&r.code!==KE)throw new xh("Supplied PeerID CID is invalid");if(r.code===KE){let e=T(r.multihash.digest);return new al(new URL(e))}return Br(r.multihash)}function vM(r){return r.code===fd.code}function EM(r){return r.code===RE.code}var xM,KE,ke=C(()=>{Bt();V();ud();K2();tl();F2();NE();ie();UE();xM=114,KE=2336});var Tg=C(()=>{"use strict"});var PS=At(($ie,_S)=>{var Oi=1e3,Ri=Oi*60,Ni=Ri*60,oo=Ni*24,GR=oo*7,WR=oo*365.25;_S.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return jR(r);if(t==="number"&&isFinite(r))return e.long?XR(r):YR(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function jR(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*WR;case"weeks":case"week":case"w":return t*GR;case"days":case"day":case"d":return t*oo;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Ni;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ri;case"seconds":case"second":case"secs":case"sec":case"s":return t*Oi;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function YR(r){var e=Math.abs(r);return e>=oo?Math.round(r/oo)+"d":e>=Ni?Math.round(r/Ni)+"h":e>=Ri?Math.round(r/Ri)+"m":e>=Oi?Math.round(r/Oi)+"s":r+"ms"}function XR(r){var e=Math.abs(r);return e>=oo?xd(r,e,oo,"day"):e>=Ni?xd(r,e,Ni,"hour"):e>=Ri?xd(r,e,Ri,"minute"):e>=Oi?xd(r,e,Oi,"second"):r+" ms"}function xd(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var $g=At((Hie,DS)=>{function QR(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=s,t.enabled=a,t.humanize=PS(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let p=0;p<u.length;p++)d=(d<<5)-d+u.charCodeAt(p),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u){let d,p=null,f,h;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),E=b-(d||b);y.diff=E,y.prev=d,y.curr=b,d=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let w=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(S,x)=>{if(S==="%%")return"%";w++;let I=t.formatters[x];if(typeof I=="function"){let A=g[w];S=I.call(y,A),g.splice(w,1),w--}return S}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(f!==t.namespaces&&(f=t.namespaces,h=t.enabled(u)),h),set:g=>{p=g}}),typeof t.init=="function"&&t.init(m),m}function n(u,d){let p=t(this.namespace+(typeof d>"u"?":":d)+u);return p.log=this.log,p}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let p of d)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function o(u,d){let p=0,f=0,h=-1,m=0;for(;p<u.length;)if(f<d.length&&(d[f]===u[p]||d[f]==="*"))d[f]==="*"?(h=f,m=p,f++):(p++,f++);else if(h!==-1)f=h+1,m++,p=m;else return!1;for(;f<d.length&&d[f]==="*";)f++;return f===d.length}function i(){let u=[...t.names,...t.skips.map(d=>"-"+d)].join(",");return t.enable(""),u}function a(u){for(let d of t.skips)if(o(u,d))return!1;for(let d of t.names)if(o(u,d))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}DS.exports=QR});var kS=At((Qt,vd)=>{Qt.formatArgs=ZR;Qt.save=e9;Qt.load=t9;Qt.useColors=JR;Qt.storage=r9();Qt.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Qt.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function JR(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function ZR(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+vd.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}Qt.log=console.debug||console.log||(()=>{});function e9(r){try{r?Qt.storage.setItem("debug",r):Qt.storage.removeItem("debug")}catch{}}function t9(){let r;try{r=Qt.storage.getItem("debug")||Qt.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function r9(){try{return localStorage}catch{}}vd.exports=$g()(Qt);var{formatters:n9}=vd.exports;n9.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var MS={};z(MS,{createSupportsColor:()=>qg,default:()=>pl});function Er(r,e=globalThis.Deno?globalThis.Deno.args:Sd.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}function s9(){if(!("FORCE_COLOR"in Ke))return;if(Ke.FORCE_COLOR==="true")return 1;if(Ke.FORCE_COLOR==="false")return 0;if(Ke.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(Ke.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function o9(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function i9(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let n=s9();n!==void 0&&(Ed=n);let s=t?Ed:n;if(s===0)return 0;if(t){if(Er("color=16m")||Er("color=full")||Er("color=truecolor"))return 3;if(Er("color=256"))return 2}if("TF_BUILD"in Ke&&"AGENT_NAME"in Ke)return 1;if(r&&!e&&s===void 0)return 0;let o=s||0;if(Ke.TERM==="dumb")return o;if(Sd.default.platform==="win32"){let i=LS.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in Ke)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in Ke)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in Ke)||Ke.CI_NAME==="codeship"?1:o;if("TEAMCITY_VERSION"in Ke)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ke.TEAMCITY_VERSION)?1:0;if(Ke.COLORTERM==="truecolor"||Ke.TERM==="xterm-kitty"||Ke.TERM==="xterm-ghostty"||Ke.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Ke){let i=Number.parseInt((Ke.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ke.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ke.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ke.TERM)||"COLORTERM"in Ke?1:o}function qg(r,e={}){let t=i9(r,{streamIsTTY:r&&r.isTTY,...e});return o9(t)}var Sd,LS,Hg,Ke,Ed,a9,pl,Vg=C(()=>{Sd=ae(te("node:process"),1),LS=ae(te("node:os"),1),Hg=ae(te("node:tty"),1);({env:Ke}=Sd.default);Er("no-color")||Er("no-colors")||Er("color=false")||Er("color=never")?Ed=0:(Er("color")||Er("colors")||Er("color=true")||Er("color=always"))&&(Ed=1);a9={stdout:qg({isTTY:Hg.default.isatty(1)}),stderr:qg({isTTY:Hg.default.isatty(2)})},pl=a9});var RS=At((ft,Ad)=>{var c9=te("tty"),Id=te("util");ft.init=m9;ft.log=d9;ft.formatArgs=u9;ft.save=f9;ft.load=p9;ft.useColors=l9;ft.destroy=Id.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ft.colors=[6,2,3,4,5,1];try{let r=(Vg(),$5(MS));r&&(r.stderr||r).level>=2&&(ft.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}ft.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,o)=>o.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function l9(){return"colors"in ft.inspectOpts?!!ft.inspectOpts.colors:c9.isatty(process.stderr.fd)}function u9(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),o=` ${s};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
2
+ "use strict";var OptimysticDbP2P=(()=>{var c_=Object.create;var Ou=Object.defineProperty;var l_=Object.getOwnPropertyDescriptor;var u_=Object.getOwnPropertyNames;var h_=Object.getPrototypeOf,d_=Object.prototype.hasOwnProperty;var Z=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var f_=(r,e)=>()=>(r&&(e=r(r=0)),e);var mt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),z=(r,e)=>{for(var t in e)Ou(r,t,{get:e[t],enumerable:!0})},L6=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of u_(e))!d_.call(r,s)&&s!==t&&Ou(r,s,{get:()=>e[s],enumerable:!(n=l_(e,s))||n.enumerable});return r};var ne=(r,e,t)=>(t=r!=null?c_(h_(r)):{},L6(e||!r||!r.__esModule?Ou(t,"default",{value:r,enumerable:!0}):t,r)),M6=r=>L6(Ou({},"__esModule",{value:!0}),r);var rv=mt((gse,tv)=>{var pi=1e3,mi=pi*60,gi=mi*60,$s=gi*24,vM=$s*7,EM=$s*365.25;tv.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return SM(r);if(t==="number"&&isFinite(r))return e.long?AM(r):IM(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function SM(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*EM;case"weeks":case"week":case"w":return t*vM;case"days":case"day":case"d":return t*$s;case"hours":case"hour":case"hrs":case"hr":case"h":return t*gi;case"minutes":case"minute":case"mins":case"min":case"m":return t*mi;case"seconds":case"second":case"secs":case"sec":case"s":return t*pi;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function IM(r){var e=Math.abs(r);return e>=$s?Math.round(r/$s)+"d":e>=gi?Math.round(r/gi)+"h":e>=mi?Math.round(r/mi)+"m":e>=pi?Math.round(r/pi)+"s":r+"ms"}function AM(r){var e=Math.abs(r);return e>=$s?zh(r,e,$s,"day"):e>=gi?zh(r,e,gi,"hour"):e>=mi?zh(r,e,mi,"minute"):e>=pi?zh(r,e,pi,"second"):r+" ms"}function zh(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var M2=mt((yse,nv)=>{function CM(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=s,t.enabled=a,t.humanize=rv(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let p=0;p<u.length;p++)d=(d<<5)-d+u.charCodeAt(p),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u){let d,p=null,f,h;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),E=b-(d||b);y.diff=E,y.prev=d,y.curr=b,d=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(S,w)=>{if(S==="%%")return"%";x++;let I=t.formatters[w];if(typeof I=="function"){let A=g[x];S=I.call(y,A),g.splice(x,1),x--}return S}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(f!==t.namespaces&&(f=t.namespaces,h=t.enabled(u)),h),set:g=>{p=g}}),typeof t.init=="function"&&t.init(m),m}function n(u,d){let p=t(this.namespace+(typeof d>"u"?":":d)+u);return p.log=this.log,p}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let p of d)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function o(u,d){let p=0,f=0,h=-1,m=0;for(;p<u.length;)if(f<d.length&&(d[f]===u[p]||d[f]==="*"))d[f]==="*"?(h=f,m=p,f++):(p++,f++);else if(h!==-1)f=h+1,m++,p=m;else return!1;for(;f<d.length&&d[f]==="*";)f++;return f===d.length}function i(){let u=[...t.names,...t.skips.map(d=>"-"+d)].join(",");return t.enable(""),u}function a(u){for(let d of t.skips)if(o(u,d))return!1;for(let d of t.names)if(o(u,d))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}nv.exports=CM});var sv=mt((Ft,$h)=>{Ft.formatArgs=_M;Ft.save=PM;Ft.load=DM;Ft.useColors=TM;Ft.storage=kM();Ft.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Ft.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function TM(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function _M(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+$h.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}Ft.log=console.debug||console.log||(()=>{});function PM(r){try{r?Ft.storage.setItem("debug",r):Ft.storage.removeItem("debug")}catch{}}function DM(){let r;try{r=Ft.storage.getItem("debug")||Ft.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function kM(){try{return localStorage}catch{}}$h.exports=M2()(Ft);var{formatters:LM}=$h.exports;LM.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var iv={};z(iv,{createSupportsColor:()=>R2,default:()=>zc});function lr(r,e=globalThis.Deno?globalThis.Deno.args:qh.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}function MM(){if(!("FORCE_COLOR"in ke))return;if(ke.FORCE_COLOR==="true")return 1;if(ke.FORCE_COLOR==="false")return 0;if(ke.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(ke.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function OM(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function RM(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let n=MM();n!==void 0&&(Hh=n);let s=t?Hh:n;if(s===0)return 0;if(t){if(lr("color=16m")||lr("color=full")||lr("color=truecolor"))return 3;if(lr("color=256"))return 2}if("TF_BUILD"in ke&&"AGENT_NAME"in ke)return 1;if(r&&!e&&s===void 0)return 0;let o=s||0;if(ke.TERM==="dumb")return o;if(qh.default.platform==="win32"){let i=ov.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in ke)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in ke)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in ke)||ke.CI_NAME==="codeship"?1:o;if("TEAMCITY_VERSION"in ke)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ke.TEAMCITY_VERSION)?1:0;if(ke.COLORTERM==="truecolor"||ke.TERM==="xterm-kitty"||ke.TERM==="xterm-ghostty"||ke.TERM==="wezterm")return 3;if("TERM_PROGRAM"in ke){let i=Number.parseInt((ke.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ke.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ke.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ke.TERM)||"COLORTERM"in ke?1:o}function R2(r,e={}){let t=RM(r,{streamIsTTY:r&&r.isTTY,...e});return OM(t)}var qh,ov,O2,ke,Hh,NM,zc,N2=f_(()=>{qh=ne(Z("node:process"),1),ov=ne(Z("node:os"),1),O2=ne(Z("node:tty"),1);({env:ke}=qh.default);lr("no-color")||lr("no-colors")||lr("color=false")||lr("color=never")?Hh=0:(lr("color")||lr("colors")||lr("color=true")||lr("color=always"))&&(Hh=1);NM={stdout:R2({isTTY:O2.default.isatty(1)}),stderr:R2({isTTY:O2.default.isatty(2)})},zc=NM});var cv=mt((st,Gh)=>{var BM=Z("tty"),Vh=Z("util");st.init=qM;st.log=zM;st.formatArgs=KM;st.save=$M;st.load=HM;st.useColors=UM;st.destroy=Vh.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");st.colors=[6,2,3,4,5,1];try{let r=(N2(),M6(iv));r&&(r.stderr||r).level>=2&&(st.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}st.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,o)=>o.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function UM(){return"colors"in st.inspectOpts?!!st.inspectOpts.colors:BM.isatty(process.stderr.fd)}function KM(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),o=` ${s};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
3
3
  `).join(`
4
- `+o),r.push(s+"m+"+Ad.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=h9()+e+" "+r[0]}function h9(){return ft.inspectOpts.hideDate?"":new Date().toISOString()+" "}function d9(...r){return process.stderr.write(Id.formatWithOptions(ft.inspectOpts,...r)+`
5
- `)}function f9(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function p9(){return process.env.DEBUG}function m9(r){r.inspectOpts={};let e=Object.keys(ft.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=ft.inspectOpts[e[t]]}Ad.exports=$g()(ft);var{formatters:OS}=Ad.exports;OS.o=function(r){return this.inspectOpts.colors=this.useColors,Id.inspect(r,this.inspectOpts).split(`
6
- `).map(e=>e.trim()).join(" ")};OS.O=function(r){return this.inspectOpts.colors=this.useColors,Id.inspect(r,this.inspectOpts)}});var Wg=At((qie,Gg)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Gg.exports=kS():Gg.exports=RS()});var c8=At(nu=>{(function(){var r,e,t,n,s,o,i,a;a=function(c){var l,u,d,p;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,d=(c&65280)>>>8,p=c&255,[l,u,d,p].join(".")},i=function(c){var l,u,d,p,f,h;for(l=[],d=p=0;p<=3&&c.length!==0;d=++p){if(d>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}h=e(c),f=h[0],u=h[1],c=c.substring(u),l.push(f)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),s=t("A"),e=function(c){var l,u,d,p,f;for(p=0,l=10,u="9",d=0,c.length>1&&c[d]==="0"&&(c[d+1]==="x"||c[d+1]==="X"?(d+=2,l=16):"0"<=c[d+1]&&c[d+1]<="9"&&(d++,l=8,u="7")),f=d;d<c.length;){if("0"<=c[d]&&c[d]<=u)p=p*l+(t(c[d])-n)>>>0;else if(l===16)if("a"<=c[d]&&c[d]<="f")p=p*l+(10+t(c[d])-o)>>>0;else if("A"<=c[d]&&c[d]<="F")p=p*l+(10+t(c[d])-s)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");d++}if(d===f)throw new Error("empty octet");return[p,d]},r=(function(){function c(l,u){var d,p,f,h;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(h=l.split("/",2),l=h[0],u=h[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw d=m,new Error("Invalid mask: "+u)}for(p=f=32;f>=0;p=--f)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw d=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,d,p;for(p=i(this.first),d=i(this.last),u=0;p<=d;)l(a(p),p,u),u++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),nu.ip2long=i,nu.long2ip=a,nu.Netmask=r}).call(nu)});var TT=At((Q5e,CT)=>{CT.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Gw=At(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.TAG_LENGTH=pn.DATA_CHUNK_LENGTH=pn.NONCE_LENGTH=pn.KEY_LENGTH=void 0;pn.KEY_LENGTH=32;pn.NONCE_LENGTH=12;pn.DATA_CHUNK_LENGTH=65536;pn.TAG_LENGTH=16});var zT=At(y1=>{"use strict";Object.defineProperty(y1,"__esModule",{value:!0});y1.ChaCha20Poly1305=void 0;var je=Gw(),Ww=class{constructor(e){this.ctx=e;let t=e.cpKey.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,je.KEY_LENGTH);let n=e.cpNonce.value;this.wasmNonceArr=new Uint8Array(e.memory.buffer,n,je.NONCE_LENGTH);let s=e.cpAssociatedData.value;this.wasmAdArr=new Uint8Array(e.memory.buffer,s,je.KEY_LENGTH);let o=e.cpInput.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,o,je.DATA_CHUNK_LENGTH);let i=e.chacha20Output.value;this.wasmChacha20OutputArr=new Uint8Array(e.memory.buffer,i,je.DATA_CHUNK_LENGTH);let a=e.poly1305Output.value;this.wasmPoly1305OutputArr=new Uint8Array(e.memory.buffer,a,je.TAG_LENGTH);let c=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,c,64)}seal(e,t,n,s,o){this.init(e,t,s);let i=n.length+je.TAG_LENGTH,a;if(o){if(o.length!==i)throw new Error("ChaCha20Poly1305: incorrect destination length");a=o}else a=new Uint8Array(i);let c=s?.length??0;return this.sealUpdate(n,c,a),a.set(this.wasmPoly1305OutputArr,n.length),a}open(e,t,n,s,o){this.init(e,t,s);let i=n.subarray(0,n.length-je.TAG_LENGTH),a;if(o){if(o.length!==i.length)throw new Error("ChaCha20Poly1305: incorrect destination length");a=o}else a=new Uint8Array(i.length);let c=s?.length??0;this.openUpdate(i,c,a);let l=n.subarray(n.length-je.TAG_LENGTH,n.length);return this.isSameTag(l)?a:null}init(e,t,n=new Uint8Array(0)){if(e.length!=je.KEY_LENGTH)throw Error(`Invalid chacha20poly1305 key length ${e.length}, expect ${je.KEY_LENGTH}`);if(n.length>je.KEY_LENGTH)throw Error(`Invalid ad length ${n.length}, expect <= ${je.KEY_LENGTH}`);if(t.length!==je.NONCE_LENGTH)throw Error(`Invalid nonce length ${t.length}, expect ${je.NONCE_LENGTH}`);this.wasmKeyArr.set(e),this.wasmNonceArr.set(t),this.wasmAdArr.set(n)}openUpdate(e,t,n){this.commonUpdate(e,this.ctx.openUpdate,t,n)}sealUpdate(e,t,n){this.commonUpdate(e,this.ctx.sealUpdate,t,n)}commonUpdate(e,t,n,s){let o=e.length;if(e.length<=je.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),t(!0,!0,o,o,n),s.set(o===je.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,o));return}for(let i=0;i<o;i+=je.DATA_CHUNK_LENGTH){let a=Math.min(o,i+je.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(i,a));let c=i===0,l=i+je.DATA_CHUNK_LENGTH>=o;t(c,l,a-i,o,n),s.set(a-i===je.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,a-i),i)}}isSameTag(e){let t=!0;for(let n=0;n<je.TAG_LENGTH;n++)if(this.wasmPoly1305OutputArr[n]!==e[n]){t=!1;break}return t}};y1.ChaCha20Poly1305=Ww});var $T=At(b1=>{"use strict";Object.defineProperty(b1,"__esModule",{value:!0});b1.Poly1305=void 0;var Wn=Gw(),jw=class{constructor(e){this.ctx=e;let t=e.poly1305Key.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,Wn.KEY_LENGTH);let n=e.poly1305Input.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,n,Wn.DATA_CHUNK_LENGTH);let s=e.poly1305Output.value;this.wasmOutputArr=new Uint8Array(e.memory.buffer,s,Wn.TAG_LENGTH);let o=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,o,64)}init(e){if(e.length!=Wn.KEY_LENGTH)throw Error(`Invalid poly1305 key length ${e.length}, expect ${Wn.KEY_LENGTH}`);this.wasmKeyArr.set(e),this.ctx.poly1305Init()}update(e){if(e.length<=Wn.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),this.ctx.poly1305Update(e.length);return}for(let t=0;t<e.length;t+=Wn.DATA_CHUNK_LENGTH){let n=Math.min(e.length,t+Wn.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(t,n)),this.ctx.poly1305Update(n-t)}}digest(){this.ctx.poly1305Digest();let e=new Uint8Array(Wn.TAG_LENGTH);return e.set(this.wasmOutputArr),e}};b1.Poly1305=jw});var HT=At(w1=>{"use strict";Object.defineProperty(w1,"__esModule",{value:!0});w1.wasmCode=void 0;w1.wasmCode=Uint8Array.from([0,97,115,109,1,0,0,0,1,58,10,96,0,0,96,2,127,127,0,96,1,127,0,96,3,127,127,127,0,96,1,127,1,127,96,4,127,127,127,127,0,96,5,127,127,127,127,127,0,96,0,1,127,96,2,127,127,1,127,96,5,127,127,127,127,127,1,127,2,13,1,3,101,110,118,5,97,98,111,114,116,0,5,3,34,33,2,8,1,4,0,4,7,0,0,3,3,2,1,9,4,2,0,3,1,2,2,1,0,0,0,5,1,1,1,6,1,6,0,5,3,1,0,1,6,238,1,47,127,0,65,32,11,127,0,65,16,11,127,0,65,128,128,4,11,127,0,65,16,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,7,226,2,23,6,109,101,109,111,114,121,2,0,21,67,72,65,67,72,65,50,48,95,73,78,80,85,84,95,76,69,78,71,84,72,3,2,23,67,72,65,67,72,65,50,48,95,67,79,85,78,84,69,82,95,76,69,78,71,84,72,3,3,13,99,104,97,99,104,97,50,48,73,110,112,117,116,3,6,11,99,104,97,99,104,97,50,48,75,101,121,3,8,15,99,104,97,99,104,97,50,48,67,111,117,110,116,101,114,3,10,14,99,104,97,99,104,97,50,48,79,117,116,112,117,116,3,12,23,99,104,97,99,104,97,50,48,83,116,114,101,97,109,88,79,82,85,112,100,97,116,101,0,15,10,75,69,89,95,76,69,78,71,84,72,3,0,10,84,65,71,95,76,69,78,71,84,72,3,1,12,112,111,108,121,49,51,48,53,73,110,105,116,0,17,14,112,111,108,121,49,51,48,53,85,112,100,97,116,101,0,20,14,112,111,108,121,49,51,48,53,68,105,103,101,115,116,0,24,13,112,111,108,121,49,51,48,53,73,110,112,117,116,3,19,11,112,111,108,121,49,51,48,53,75,101,121,3,18,14,112,111,108,121,49,51,48,53,79,117,116,112,117,116,3,20,10,111,112,101,110,85,112,100,97,116,101,0,30,10,115,101,97,108,85,112,100,97,116,101,0,32,5,99,112,75,101,121,3,37,7,99,112,78,111,110,99,101,3,39,7,99,112,73,110,112,117,116,3,43,16,99,112,65,115,115,111,99,105,97,116,101,100,68,97,116,97,3,41,5,100,101,98,117,103,3,46,8,1,33,10,195,47,33,70,1,2,127,32,0,63,0,34,2,65,16,116,34,1,75,4,64,32,2,32,0,32,1,107,65,255,255,3,106,65,128,128,124,113,65,16,118,34,1,32,2,32,1,74,27,64,0,65,0,72,4,64,32,1,64,0,65,0,72,4,64,0,11,11,11,32,0,36,5,11,82,1,3,127,32,0,65,240,255,255,255,3,75,4,64,0,11,35,5,65,16,106,34,3,32,0,65,15,106,65,112,113,34,2,65,16,32,2,65,16,75,27,34,4,106,16,1,32,3,65,16,107,34,2,32,4,54,2,0,32,2,65,1,54,2,4,32,2,32,1,54,2,8,32,2,32,0,54,2,12,32,3,11,37,1,1,127,3,64,32,1,4,64,32,0,34,2,65,1,106,33,0,32,2,65,0,58,0,0,32,1,65,1,107,33,1,12,1,11,11,11,42,1,1,127,32,0,65,240,255,255,255,3,75,4,64,65,32,65,208,0,65,54,65,42,16,0,0,11,32,0,65,0,16,2,34,1,32,0,16,3,32,1,11,67,0,65,128,3,36,4,65,128,3,36,5,65,128,128,4,16,4,36,6,35,6,36,7,65,32,16,4,36,8,35,8,36,9,65,16,16,4,36,10,35,10,36,11,65,128,128,4,16,4,36,12,35,12,36,13,65,192,0,16,4,36,14,35,14,36,15,11,83,1,1,127,65,128,2,65,0,16,2,34,1,65,128,2,16,3,32,0,69,4,64,65,12,65,2,16,2,33,0,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,40,2,0,26,32,0,32,1,54,2,0,32,0,32,1,54,2,4,32,0,65,128,2,54,2,8,32,0,11,10,0,65,12,65,3,16,2,16,6,11,95,0,16,7,36,16,35,16,40,2,0,36,17,65,32,16,4,36,18,65,128,128,4,16,4,36,19,65,16,16,4,36,20,35,18,36,21,35,19,36,22,35,20,36,23,65,16,16,4,36,24,35,24,36,25,65,20,16,4,36,26,35,26,36,27,65,20,16,4,36,28,35,28,36,29,65,16,16,4,36,30,35,30,36,31,65,20,16,4,36,35,35,35,36,36,11,55,0,65,32,16,4,36,37,35,37,36,38,65,12,16,4,36,39,35,39,36,40,65,32,16,4,36,41,35,41,36,42,65,128,128,4,16,4,36,43,35,43,36,44,16,7,36,45,35,45,40,2,0,36,46,11,22,0,32,1,32,2,65,255,1,113,65,4,110,65,2,116,106,32,0,54,2,0,11,188,6,1,31,127,65,229,240,193,139,6,33,5,65,238,200,129,153,3,33,6,65,178,218,136,203,7,33,14,65,244,202,129,217,6,33,7,32,2,40,2,0,34,19,33,4,32,2,65,4,106,40,2,0,34,20,33,8,32,2,65,8,106,40,2,0,34,21,33,3,32,2,65,12,106,40,2,0,34,22,33,13,32,2,65,16,106,40,2,0,34,23,33,15,32,2,65,20,106,40,2,0,34,24,33,9,32,2,65,24,106,40,2,0,34,25,33,10,32,2,65,28,106,40,2,0,34,26,33,2,32,1,40,2,0,34,27,33,11,32,1,65,4,106,40,2,0,34,28,33,16,32,1,65,8,106,40,2,0,34,29,33,12,32,1,65,12,106,40,2,0,34,30,33,1,3,64,32,18,65,20,72,4,64,32,3,32,10,32,12,32,3,32,14,106,34,3,115,65,16,119,34,14,106,34,10,115,65,12,119,34,12,32,10,32,14,32,3,32,12,106,34,3,115,65,8,119,34,14,106,34,10,115,33,12,32,13,32,2,32,1,32,7,32,13,106,34,1,115,65,16,119,34,2,106,34,13,115,65,12,119,34,7,32,13,32,2,32,1,32,7,106,34,13,115,65,8,119,34,1,106,34,2,115,33,7,32,4,32,15,32,11,32,4,32,5,106,34,4,115,65,16,119,34,5,106,34,15,115,65,12,119,34,11,32,15,32,5,32,4,32,11,106,34,4,115,65,8,119,34,5,106,34,15,115,33,11,32,10,32,1,32,8,32,9,32,16,32,6,32,8,106,34,1,115,65,16,119,34,8,106,34,6,115,65,12,119,34,9,32,6,32,8,32,1,32,9,106,34,1,115,65,8,119,34,6,106,34,9,115,65,7,119,34,10,32,4,106,34,17,115,65,16,119,34,31,106,33,8,32,2,32,5,32,12,65,7,119,34,5,32,1,106,34,32,115,65,16,119,34,33,106,33,1,32,9,32,14,32,13,32,11,65,7,119,34,9,106,34,11,115,65,16,119,34,12,106,33,4,32,15,32,6,32,3,32,7,65,7,119,34,3,106,34,6,115,65,16,119,34,7,106,34,2,32,6,32,2,32,3,115,65,12,119,34,3,106,34,14,32,7,115,65,8,119,34,16,106,34,15,32,3,115,65,7,119,33,13,32,11,32,4,32,9,115,65,12,119,34,2,106,34,7,32,12,115,65,8,119,34,12,32,4,106,34,9,32,2,115,65,7,119,33,4,32,32,32,1,32,5,115,65,12,119,34,3,106,34,6,32,33,115,65,8,119,34,11,32,1,106,34,2,32,3,115,65,7,119,33,3,32,17,32,8,32,10,115,65,12,119,34,17,106,34,5,32,31,115,65,8,119,34,1,32,8,106,34,10,32,17,115,65,7,119,33,8,32,18,65,2,106,33,18,12,1,11,11,32,5,65,229,240,193,139,6,106,32,0,65,0,16,10,32,6,65,238,200,129,153,3,106,32,0,65,4,16,10,32,14,65,178,218,136,203,7,106,32,0,65,8,16,10,32,7,65,244,202,129,217,6,106,32,0,65,12,16,10,32,4,32,19,106,32,0,65,16,16,10,32,8,32,20,106,32,0,65,20,16,10,32,3,32,21,106,32,0,65,24,16,10,32,13,32,22,106,32,0,65,28,16,10,32,15,32,23,106,32,0,65,32,16,10,32,9,32,24,106,32,0,65,36,16,10,32,10,32,25,106,32,0,65,40,16,10,32,2,32,26,106,32,0,65,44,16,10,32,11,32,27,106,32,0,65,48,16,10,32,16,32,28,106,32,0,65,52,16,10,32,12,32,29,106,32,0,65,56,16,10,32,1,32,30,106,32,0,65,60,16,10,11,97,1,4,127,65,4,33,3,65,1,33,1,3,64,32,3,34,2,65,1,107,33,3,32,2,65,255,1,113,4,64,32,1,32,0,32,4,65,255,1,113,106,34,2,45,0,0,106,33,1,32,2,32,1,58,0,0,32,1,65,8,118,33,1,32,4,65,1,106,33,4,12,1,11,11,32,1,65,0,74,4,64,65,144,1,65,208,1,65,135,2,65,4,16,0,0,11,11,8,0,32,0,32,1,16,3,11,108,1,2,127,3,64,32,6,32,1,73,4,64,35,15,32,3,32,2,16,11,32,6,33,5,3,64,32,5,32,1,73,65,0,32,5,32,6,65,64,107,73,27,4,64,32,4,32,5,106,32,0,32,5,106,45,0,0,35,15,32,5,32,6,107,106,45,0,0,115,58,0,0,32,5,65,1,106,33,5,12,1,11,11,32,3,16,12,32,6,65,64,107,33,6,12,1,11,11,35,15,65,192,0,16,13,32,1,11,14,0,35,7,32,0,35,9,35,11,35,13,16,14,11,204,4,1,1,127,35,27,32,0,45,0,0,32,0,65,1,106,45,0,0,65,8,116,114,34,1,65,255,63,113,59,1,0,35,27,65,2,106,32,1,65,13,118,32,0,65,2,106,45,0,0,32,0,65,3,106,45,0,0,65,8,116,114,34,1,65,3,116,114,65,255,63,113,59,1,0,35,27,65,4,106,32,1,65,10,118,32,0,65,4,106,45,0,0,32,0,65,5,106,45,0,0,65,8,116,114,34,1,65,6,116,114,65,131,62,113,59,1,0,35,27,65,6,106,32,1,65,7,118,32,0,65,6,106,45,0,0,32,0,65,7,106,45,0,0,65,8,116,114,34,1,65,9,116,114,65,255,63,113,59,1,0,35,27,65,8,106,32,1,65,4,118,32,0,65,8,106,45,0,0,32,0,65,9,106,45,0,0,65,8,116,114,34,1,65,12,116,114,65,255,1,113,59,1,0,35,27,65,10,106,32,1,65,1,118,65,254,63,113,59,1,0,35,27,65,12,106,32,1,65,14,118,32,0,65,10,106,45,0,0,32,0,65,11,106,45,0,0,65,8,116,114,34,1,65,2,116,114,65,255,63,113,59,1,0,35,27,65,14,106,32,1,65,11,118,32,0,65,12,106,45,0,0,32,0,65,13,106,45,0,0,65,8,116,114,34,1,65,5,116,114,65,129,63,113,59,1,0,35,27,65,16,106,32,1,65,8,118,32,0,65,14,106,45,0,0,32,0,65,15,106,45,0,0,65,8,116,114,34,1,65,8,116,114,65,255,63,113,59,1,0,35,27,65,18,106,32,1,65,5,118,65,255,0,113,59,1,0,35,31,32,0,65,16,106,45,0,0,32,0,65,17,106,45,0,0,65,8,116,114,59,1,0,35,31,65,2,106,32,0,65,18,106,45,0,0,32,0,65,19,106,45,0,0,65,8,116,114,59,1,0,35,31,65,4,106,32,0,65,20,106,45,0,0,32,0,65,21,106,45,0,0,65,8,116,114,59,1,0,35,31,65,6,106,32,0,65,22,106,45,0,0,32,0,65,23,106,45,0,0,65,8,116,114,59,1,0,35,31,65,8,106,32,0,65,24,106,45,0,0,32,0,65,25,106,45,0,0,65,8,116,114,59,1,0,35,31,65,10,106,32,0,65,26,106,45,0,0,32,0,65,27,106,45,0,0,65,8,116,114,59,1,0,35,31,65,12,106,32,0,65,28,106,45,0,0,32,0,65,29,106,45,0,0,65,8,116,114,59,1,0,35,31,65,14,106,32,0,65,30,106,45,0,0,32,0,65,31,106,45,0,0,65,8,116,114,59,1,0,11,6,0,35,21,16,16,11,166,13,1,32,127,65,0,65,128,16,35,33,27,33,34,35,29,47,1,0,33,3,35,29,65,2,106,47,1,0,33,4,35,29,65,4,106,47,1,0,33,8,35,29,65,6,106,47,1,0,33,9,35,29,65,8,106,47,1,0,33,10,35,29,65,10,106,47,1,0,33,11,35,29,65,12,106,47,1,0,33,12,35,29,65,14,106,47,1,0,33,13,35,29,65,16,106,47,1,0,33,14,35,29,65,18,106,47,1,0,33,6,35,27,47,1,0,33,17,35,27,65,2,106,47,1,0,33,18,35,27,65,4,106,47,1,0,33,20,35,27,65,6,106,47,1,0,33,22,35,27,65,8,106,47,1,0,33,24,35,27,65,10,106,47,1,0,33,26,35,27,65,12,106,47,1,0,33,29,35,27,65,14,106,47,1,0,33,30,35,27,65,16,106,47,1,0,33,31,35,27,65,18,106,47,1,0,33,33,3,64,32,2,65,16,79,4,64,32,3,32,0,32,1,106,45,0,0,32,0,32,1,65,1,106,106,45,0,0,65,8,116,114,34,15,65,255,63,113,106,34,3,32,17,108,32,4,32,0,32,1,65,2,106,106,45,0,0,32,0,32,1,65,3,106,106,45,0,0,65,8,116,114,34,16,65,3,116,32,15,65,255,255,3,113,65,13,118,114,65,255,63,113,106,34,4,32,33,65,5,108,34,15,108,106,32,8,32,0,32,1,65,4,106,106,45,0,0,32,0,32,1,65,5,106,106,45,0,0,65,8,116,114,34,19,65,6,116,32,16,65,255,255,3,113,65,10,118,114,65,255,63,113,106,34,8,32,31,65,5,108,34,16,108,106,32,9,32,0,32,1,65,6,106,106,45,0,0,32,0,32,1,65,7,106,106,45,0,0,65,8,116,114,34,21,65,9,116,32,19,65,255,255,3,113,65,7,118,114,65,255,63,113,106,34,9,32,30,65,5,108,34,19,108,106,32,10,32,0,32,1,65,8,106,106,45,0,0,32,0,32,1,65,9,106,106,45,0,0,65,8,116,114,34,23,65,12,116,32,21,65,255,255,3,113,65,4,118,114,65,255,63,113,106,34,10,32,29,65,5,108,34,21,108,106,34,32,65,255,63,113,32,11,32,23,65,255,255,3,113,65,1,118,65,255,63,113,106,34,11,32,26,65,5,108,34,27,108,106,32,12,32,0,32,1,65,10,106,106,45,0,0,32,0,32,1,65,11,106,106,45,0,0,65,8,116,114,34,28,65,2,116,32,23,65,255,255,3,113,65,14,118,114,65,255,63,113,106,34,12,32,24,65,5,108,34,23,108,106,32,13,32,0,32,1,65,12,106,106,45,0,0,32,0,32,1,65,13,106,106,45,0,0,65,8,116,114,34,25,65,5,116,32,28,65,255,255,3,113,65,11,118,114,65,255,63,113,106,34,13,32,22,65,5,108,34,28,108,106,32,14,32,25,65,255,255,3,113,65,8,118,32,0,32,1,65,14,106,106,45,0,0,32,0,32,1,65,15,106,106,45,0,0,65,8,116,114,34,25,65,8,116,114,65,255,63,113,106,34,14,32,20,65,5,108,34,7,108,106,33,5,32,11,32,21,108,32,32,65,13,118,32,5,32,6,32,34,32,25,65,255,255,3,113,65,5,118,114,65,255,255,3,113,106,34,6,32,18,65,5,108,108,106,34,32,65,13,118,106,32,3,32,18,108,106,32,4,32,17,108,106,32,8,32,15,108,106,32,9,32,16,108,106,32,10,32,19,108,106,34,25,65,255,63,113,106,32,12,32,27,108,106,32,13,32,23,108,106,32,14,32,28,108,106,33,5,32,11,32,19,108,32,25,65,13,118,32,5,32,6,32,7,108,106,34,25,65,13,118,106,32,3,32,20,108,106,32,4,32,18,108,106,32,8,32,17,108,106,32,9,32,15,108,106,32,10,32,16,108,106,34,7,65,255,63,113,106,32,12,32,21,108,106,32,13,32,27,108,106,32,14,32,23,108,106,33,5,32,11,32,16,108,32,7,65,13,118,32,5,32,6,32,28,108,106,34,28,65,13,118,106,32,3,32,22,108,106,32,4,32,20,108,106,32,8,32,18,108,106,32,9,32,17,108,106,32,10,32,15,108,106,34,7,65,255,63,113,106,32,12,32,19,108,106,32,13,32,21,108,106,32,14,32,27,108,106,33,5,32,11,32,15,108,32,7,65,13,118,32,5,32,6,32,23,108,106,34,23,65,13,118,106,32,3,32,24,108,106,32,4,32,22,108,106,32,8,32,20,108,106,32,9,32,18,108,106,32,10,32,17,108,106,34,7,65,255,63,113,106,32,12,32,16,108,106,32,13,32,19,108,106,32,14,32,21,108,106,33,5,32,11,32,17,108,32,7,65,13,118,32,5,32,6,32,27,108,106,34,27,65,13,118,106,32,3,32,26,108,106,32,4,32,24,108,106,32,8,32,22,108,106,32,9,32,20,108,106,32,10,32,18,108,106,34,7,65,255,63,113,106,32,12,32,15,108,106,32,13,32,16,108,106,32,14,32,19,108,106,33,5,32,11,32,18,108,32,7,65,13,118,32,5,32,6,32,21,108,106,34,21,65,13,118,106,32,3,32,29,108,106,32,4,32,26,108,106,32,8,32,24,108,106,32,9,32,22,108,106,32,10,32,20,108,106,34,7,65,255,63,113,106,32,12,32,17,108,106,32,13,32,15,108,106,32,14,32,16,108,106,33,5,32,11,32,20,108,32,7,65,13,118,32,5,32,6,32,19,108,106,34,19,65,13,118,106,32,3,32,30,108,106,32,4,32,29,108,106,32,8,32,26,108,106,32,9,32,24,108,106,32,10,32,22,108,106,34,7,65,255,63,113,106,32,12,32,18,108,106,32,13,32,17,108,106,32,14,32,15,108,106,33,5,32,11,32,22,108,32,7,65,13,118,32,5,32,6,32,16,108,106,34,16,65,13,118,106,32,3,32,31,108,106,32,4,32,30,108,106,32,8,32,29,108,106,32,9,32,26,108,106,32,10,32,24,108,106,34,7,65,255,63,113,106,32,12,32,20,108,106,32,13,32,18,108,106,32,14,32,17,108,106,33,5,32,11,32,24,108,32,7,65,13,118,32,5,32,6,32,15,108,106,34,15,65,13,118,106,32,3,32,33,108,106,32,4,32,31,108,106,32,8,32,30,108,106,32,9,32,29,108,106,32,10,32,26,108,106,34,3,65,255,63,113,106,32,12,32,22,108,106,32,13,32,20,108,106,32,14,32,18,108,106,33,4,32,3,65,13,118,32,4,32,6,32,17,108,106,34,6,65,13,118,106,34,3,32,3,65,2,116,106,32,32,65,255,63,113,106,34,3,65,13,118,33,4,32,3,65,255,63,113,33,3,32,25,65,255,63,113,32,4,106,33,4,32,28,65,255,63,113,33,8,32,23,65,255,63,113,33,9,32,27,65,255,63,113,33,10,32,21,65,255,63,113,33,11,32,19,65,255,63,113,33,12,32,16,65,255,63,113,33,13,32,15,65,255,63,113,33,14,32,6,65,255,63,113,33,6,32,1,65,16,106,33,1,32,2,65,16,107,33,2,12,1,11,11,35,29,32,3,59,1,0,35,29,65,2,106,32,4,59,1,0,35,29,65,4,106,32,8,59,1,0,35,29,65,6,106,32,9,59,1,0,35,29,65,8,106,32,10,59,1,0,35,29,65,10,106,32,11,59,1,0,35,29,65,12,106,32,12,59,1,0,35,29,65,14,106,32,13,59,1,0,35,29,65,16,106,32,14,59,1,0,35,29,65,18,106,32,6,59,1,0,11,203,1,1,3,127,35,32,4,64,65,16,35,32,107,34,3,32,1,75,4,64,32,1,33,3,11,3,64,32,2,32,3,73,4,64,35,25,32,2,35,32,106,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,32,3,107,33,1,32,3,33,4,32,3,35,32,106,36,32,35,32,65,16,73,4,64,15,11,35,25,65,0,65,16,16,18,65,0,36,32,11,2,127,32,1,65,16,79,4,64,32,0,32,4,32,1,32,1,65,15,113,107,34,3,16,18,32,3,32,4,106,33,4,32,1,32,3,107,33,1,11,32,1,11,4,64,65,0,33,2,3,64,32,2,32,1,73,4,64,35,25,32,2,35,32,106,106,32,0,32,2,32,4,106,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,35,32,106,36,32,11,11,8,0,35,22,32,0,16,19,11,149,9,1,3,127,35,32,4,64,35,32,34,1,35,25,106,65,1,58,0,0,32,1,65,1,106,33,1,3,64,32,1,65,16,73,4,64,32,1,35,25,106,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,65,1,36,33,35,25,65,0,65,16,16,18,11,35,29,65,2,106,47,1,0,65,13,118,33,2,35,29,65,2,106,35,29,65,2,106,47,1,0,65,255,63,113,59,1,0,65,2,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,29,106,32,2,32,3,35,29,106,47,1,0,106,59,1,0,32,3,35,29,106,47,1,0,65,13,118,33,2,32,3,35,29,106,32,3,35,29,106,47,1,0,65,255,63,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,29,47,1,0,32,2,65,5,108,106,59,1,0,35,29,47,1,0,33,1,35,29,35,29,47,1,0,65,255,63,113,59,1,0,35,29,65,2,106,35,29,65,2,106,47,1,0,32,1,65,255,255,3,113,65,13,118,106,59,1,0,35,29,65,2,106,47,1,0,33,1,35,29,65,2,106,35,29,65,2,106,47,1,0,65,255,63,113,59,1,0,35,29,65,4,106,35,29,65,4,106,47,1,0,32,1,65,255,255,3,113,65,13,118,106,59,1,0,35,36,35,29,47,1,0,65,5,106,59,1,0,35,36,47,1,0,65,13,118,33,2,35,36,35,36,47,1,0,65,255,63,113,59,1,0,65,1,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,36,106,32,2,32,3,35,29,106,47,1,0,106,59,1,0,32,3,35,36,106,47,1,0,65,13,118,33,2,32,3,35,36,106,32,3,35,36,106,47,1,0,65,255,63,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,36,65,18,106,35,36,65,18,106,47,1,0,65,128,64,106,59,1,0,32,2,65,1,115,65,1,107,33,2,65,0,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,36,106,32,2,32,3,35,36,106,47,1,0,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,32,2,65,127,115,33,3,65,0,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,2,35,29,106,32,2,35,36,106,47,1,0,32,3,32,2,35,29,106,47,1,0,113,114,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,29,47,1,0,35,29,65,2,106,47,1,0,65,13,116,114,59,1,0,35,29,65,2,106,35,29,65,4,106,47,1,0,65,10,116,35,29,65,2,106,47,1,0,65,3,118,114,59,1,0,35,29,65,4,106,35,29,65,6,106,47,1,0,65,7,116,35,29,65,4,106,47,1,0,65,6,118,114,59,1,0,35,29,65,6,106,35,29,65,8,106,47,1,0,65,4,116,35,29,65,6,106,47,1,0,65,9,118,114,59,1,0,35,29,65,8,106,35,29,65,10,106,47,1,0,65,1,116,35,29,65,8,106,47,1,0,65,12,118,114,35,29,65,12,106,47,1,0,65,14,116,114,59,1,0,35,29,65,10,106,35,29,65,14,106,47,1,0,65,11,116,35,29,65,12,106,47,1,0,65,2,118,114,59,1,0,35,29,65,12,106,35,29,65,16,106,47,1,0,65,8,116,35,29,65,14,106,47,1,0,65,5,118,114,59,1,0,35,29,65,14,106,35,29,65,18,106,47,1,0,65,5,116,35,29,65,16,106,47,1,0,65,8,118,114,59,1,0,35,29,35,29,47,1,0,35,31,47,1,0,106,34,2,59,1,0,65,1,33,1,3,64,32,1,65,8,73,4,64,32,1,65,1,116,34,3,35,29,106,47,1,0,32,3,35,31,106,47,1,0,106,32,2,65,16,118,106,33,2,35,29,32,3,106,32,2,59,1,0,32,1,65,1,106,33,1,12,1,11,11,32,0,35,29,47,1,0,58,0,0,32,0,65,1,106,35,29,47,1,0,65,8,118,58,0,0,32,0,65,2,106,35,29,65,2,106,47,1,0,58,0,0,32,0,65,3,106,35,29,65,2,106,47,1,0,65,8,118,58,0,0,32,0,65,4,106,35,29,65,4,106,47,1,0,58,0,0,32,0,65,5,106,35,29,65,4,106,47,1,0,65,8,118,58,0,0,32,0,65,6,106,35,29,65,6,106,47,1,0,58,0,0,32,0,65,7,106,35,29,65,6,106,47,1,0,65,8,118,58,0,0,32,0,65,8,106,35,29,65,8,106,47,1,0,58,0,0,32,0,65,9,106,35,29,65,8,106,47,1,0,65,8,118,58,0,0,32,0,65,10,106,35,29,65,10,106,47,1,0,58,0,0,32,0,65,11,106,35,29,65,10,106,47,1,0,65,8,118,58,0,0,32,0,65,12,106,35,29,65,12,106,47,1,0,58,0,0,32,0,65,13,106,35,29,65,12,106,47,1,0,65,8,118,58,0,0,32,0,65,14,106,35,29,65,14,106,47,1,0,58,0,0,32,0,65,15,106,35,29,65,14,106,47,1,0,65,8,118,58,0,0,65,1,36,34,11,11,0,32,0,32,1,65,1,116,16,3,11,38,0,35,25,65,16,16,13,35,27,65,10,16,22,35,29,65,10,16,22,35,31,65,8,16,22,65,0,36,32,65,0,36,33,65,0,36,34,11,33,1,1,127,35,23,33,0,35,34,4,64,65,144,2,65,208,2,65,226,3,65,4,16,0,0,11,32,0,16,21,16,23,11,39,1,1,127,3,64,32,0,65,32,73,4,64,32,0,35,7,106,65,0,58,0,0,32,0,65,1,106,33,0,12,1,11,11,65,32,16,15,26,11,152,2,1,1,127,3,64,32,4,65,32,72,4,64,32,4,35,9,106,32,0,32,4,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,65,0,33,4,3,64,32,4,65,4,72,4,64,32,4,35,11,106,65,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,65,4,33,4,3,64,32,4,65,16,72,4,64,32,4,35,11,106,32,1,32,4,65,4,107,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,16,25,65,0,33,4,3,64,32,4,65,32,72,4,64,32,4,35,21,106,32,4,35,13,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,35,21,16,16,32,3,65,0,75,4,64,65,0,33,4,3,64,32,4,32,3,73,4,64,32,4,35,22,106,32,2,32,4,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,32,3,16,20,32,3,65,15,113,65,0,75,4,64,65,16,32,3,65,15,113,107,34,1,65,0,74,4,64,65,0,33,0,3,64,32,0,32,1,72,4,64,32,0,35,22,106,65,0,58,0,0,32,0,65,1,106,33,0,12,1,11,11,32,1,16,20,11,11,11,11,65,1,1,127,3,64,32,2,32,1,73,4,64,35,22,32,2,106,32,0,32,2,106,45,0,0,58,0,0,35,7,32,2,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,20,32,1,16,15,26,11,27,0,32,0,32,1,65,0,16,10,32,0,173,66,128,128,128,128,16,127,167,32,1,65,4,16,10,11,87,1,2,127,32,0,65,15,113,65,0,75,4,64,65,16,32,0,65,15,113,107,34,3,65,0,74,4,64,3,64,32,2,32,3,72,4,64,32,2,35,22,106,65,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,3,16,20,11,11,32,1,35,22,16,28,65,8,16,20,32,0,35,22,16,28,65,8,16,20,16,24,11,34,0,32,0,4,64,35,38,35,40,35,42,32,4,16,26,11,35,44,32,2,16,27,32,1,4,64,32,3,32,4,16,29,11,11,89,1,1,127,3,64,32,2,32,1,73,4,64,35,7,32,2,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,15,26,65,0,33,2,3,64,32,2,32,1,73,4,64,35,22,32,2,106,32,2,35,13,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,20,11,34,0,32,0,4,64,35,38,35,40,35,42,32,4,16,26,11,35,44,32,2,16,31,32,1,4,64,32,3,32,4,16,29,11,11,8,0,16,5,16,8,16,9,11,11,234,2,6,0,65,16,11,43,28,0,0,0,1,0,0,0,1,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,192,0,11,53,38,0,0,0,1,0,0,0,1,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,128,1,11,63,48,0,0,0,1,0,0,0,1,0,0,0,48,0,0,0,67,0,104,0,97,0,67,0,104,0,97,0,58,0,32,0,99,0,111,0,117,0,110,0,116,0,101,0,114,0,32,0,111,0,118,0,101,0,114,0,102,0,108,0,111,0,119,0,65,192,1,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,99,0,104,0,97,0,99,0,104,0,97,0,50,0,48,0,46,0,116,0,115,0,65,128,2,11,57,42,0,0,0,1,0,0,0,1,0,0,0,42,0,0,0,80,0,111,0,108,0,121,0,49,0,51,0,48,0,53,0,32,0,119,0,97,0,115,0,32,0,102,0,105,0,110,0,105,0,115,0,104,0,101,0,100,0,65,192,2,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,112,0,111,0,108,0,121,0,49,0,51,0,48,0,53,0,46,0,116,0,115])});var Yw=At(x1=>{"use strict";Object.defineProperty(x1,"__esModule",{value:!0});x1.newInstance=void 0;var GH=HT(),WH=new WebAssembly.Module(GH.wasmCode),jH={env:{abort:function(r,e,t,n){throw Error(`abort: ${r}:${e}:${t}:${n}`)}}};function YH(){return new WebAssembly.Instance(WH,jH).exports}x1.newInstance=YH});var GT=At(v1=>{"use strict";Object.defineProperty(v1,"__esModule",{value:!0});v1.chacha20StreamXOR=void 0;var XH=Yw(),mn=XH.newInstance(),QH=mn.chacha20Input.value,JH=mn.chacha20Output.value,ZH=mn.chacha20Key.value,eq=mn.chacha20Counter.value,{CHACHA20_INPUT_LENGTH:Ma,KEY_LENGTH:Xw,CHACHA20_COUNTER_LENGTH:VT}=mn,tq=new Uint8Array(mn.memory.buffer,QH,Ma),qT=new Uint8Array(mn.memory.buffer,JH,Ma),rq=new Uint8Array(mn.memory.buffer,ZH,Xw),nq=new Uint8Array(mn.memory.buffer,eq,VT);function sq(r,e,t){if(r.length!=Xw)throw new Error("ChaCha: key size must be 32 bytes, expected "+Xw+" got "+r.length);if(e.length!=VT)throw new Error("ChaCha nonce with counter must be 16 bytes");rq.set(r),nq.set(e);let n=new Uint8Array(t.length),s=Math.floor(t.length/Ma);for(let o=0;o<=s;o++){let i=o*Ma,a=Math.min((o+1)*Ma,t.length);tq.set(s===0?t:t.subarray(i,a));let c=a-i,l=mn.chacha20StreamXORUpdate(c);n.set(l===Ma?qT:qT.subarray(0,l),i)}return n}v1.chacha20StreamXOR=sq});var WT=At(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.newInstance=gn.chacha20StreamXOR=gn.Poly1305=gn.ChaCha20Poly1305=void 0;var oq=zT();Object.defineProperty(gn,"ChaCha20Poly1305",{enumerable:!0,get:function(){return oq.ChaCha20Poly1305}});var iq=$T();Object.defineProperty(gn,"Poly1305",{enumerable:!0,get:function(){return iq.Poly1305}});var aq=GT();Object.defineProperty(gn,"chacha20StreamXOR",{enumerable:!0,get:function(){return aq.chacha20StreamXOR}});var cq=Yw();Object.defineProperty(gn,"newInstance",{enumerable:!0,get:function(){return cq.newInstance}})});var e_=At((CEe,ZT)=>{function wq(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}ZT.exports=wq});var JP=At((I_e,QP)=>{"use strict";function ze(r,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(r)?this._fromArray(r):(this._capacityMask=3,this._list=new Array(4))}ze.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}};ze.prototype.get=function(e){return this.peekAt(e)};ze.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};ze.prototype.peekFront=function(){return this.peek()};ze.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(ze.prototype,"length",{get:function(){return this.size()}});ze.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ze.prototype.unshift=function(e){if(arguments.length===0)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ze.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};ze.prototype.push=function(e){if(arguments.length===0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ze.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var n=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),n}};ze.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var n=this.size(),s=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o=this._list[t],i;if(e<n/2){for(i=e;i>0;i--)this._list[t]=this._list[t=t-1+s&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+s&this._capacityMask}else{for(i=n-1-e;i>0;i--)this._list[t]=this._list[t=t+1+s&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+s&this._capacityMask}return o}}};ze.prototype.remove=function(e,t){var n=e,s,o=t;if(n===(n|0)&&this._head!==this._tail){var i=this.size(),a=this._list.length;if(!(n>=i||n<-i||t<1)){if(n<0&&(n+=i),t===1||!t)return s=new Array(1),s[0]=this.removeOne(n),s;if(n===0&&n+t>=i)return s=this.toArray(),this.clear(),s;n+t>i&&(t=i-n);var c;for(s=new Array(t),c=0;c<t;c++)s[c]=this._list[this._head+n+c&this._capacityMask];if(n=this._head+n&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return s}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return s}if(n<i/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[n=n-1+a&this._capacityMask]);for(n=this._head-1+a&this._capacityMask;o>0;)this._list[n=n-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+a&this._capacityMask,c=i-(t+e);c>0;c--)this.push(this._list[n++]);for(n=this._tail;o>0;)this._list[n=n+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),s}}};ze.prototype.splice=function(e,t){var n=e;if(n===(n|0)){var s=this.size();if(n<0&&(n+=s),!(n>s))if(arguments.length>2){var o,i,a,c=arguments.length,l=this._list.length,u=2;if(!s||n<s/2){for(i=new Array(n),o=0;o<n;o++)i[o]=this._list[this._head+o&this._capacityMask];for(t===0?(a=[],n>0&&(this._head=this._head+n+l&this._capacityMask)):(a=this.remove(n,t),this._head=this._head+n+l&this._capacityMask);c>u;)this.unshift(arguments[--c]);for(o=n;o>0;o--)this.unshift(i[o-1])}else{i=new Array(s-(n+t));var d=i.length;for(o=0;o<d;o++)i[o]=this._list[this._head+n+t+o&this._capacityMask];for(t===0?(a=[],n!=s&&(this._tail=this._head+n+l&this._capacityMask)):(a=this.remove(n,t),this._tail=this._tail-d+l&this._capacityMask);u<c;)this.push(arguments[u++]);for(o=0;o<d;o++)this.push(i[o])}return a}else return this.remove(n,t)}};ze.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};ze.prototype.isEmpty=function(){return this._head===this._tail};ze.prototype.toArray=function(){return this._copyArray(!1)};ze.prototype._fromArray=function(e){var t=e.length,n=this._nextPowerOf2(t);this._list=new Array(n),this._capacityMask=n-1,this._tail=t;for(var s=0;s<t;s++)this._list[s]=e[s]};ze.prototype._copyArray=function(e,t){var n=this._list,s=n.length,o=this.length;if(t=t|o,t==o&&this._head<this._tail)return this._list.slice(this._head,this._tail);var i=new Array(t),a=0,c;if(e||this._head>this._tail){for(c=this._head;c<s;c++)i[a++]=n[c];for(c=0;c<this._tail;c++)i[a++]=n[c]}else for(c=this._head;c<this._tail;c++)i[a++]=n[c];return i};ze.prototype._growArray=function(){if(this._head!=0){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1};ze.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};ze.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),n=1<<t+1;return Math.max(n,4)};QP.exports=ze});var $j={};z($j,{ArachnodeFretAdapter:()=>$l,BlockStorage:()=>Bi,ClusterClient:()=>ro,ClusterCoordinator:()=>ml,ClusterMember:()=>Cd,ClusterService:()=>Td,CoordinatorRepo:()=>_d,Libp2pKeyPeerNetwork:()=>Xl,MemoryRawStorage:()=>gl,NetworkManagerService:()=>xm,ProtocolClient:()=>Cn,RepoClient:()=>Xg,RepoService:()=>Dd,RestorationCoordinator:()=>Kl,RingSelector:()=>Fl,SYNC_PROTOCOL_PREFIX:()=>dA,SYNC_PROTOCOL_VERSION:()=>fA,StorageMonitor:()=>zl,StorageRepo:()=>yl,SyncClient:()=>ho,SyncService:()=>cf,asyncIteratorToArray:()=>uc,buildKnownPeers:()=>Kj,buildSyncProtocol:()=>Ul,clusterMember:()=>jg,clusterService:()=>Yg,computeResponsibility:()=>Uj,coordinatorRepo:()=>Qg,createLibp2pNode:()=>Bj,first:()=>Lm,getNetworkManager:()=>zj,lessThanLex:()=>MD,networkManagerService:()=>B5,reduce:()=>tk,repoService:()=>Jg,sortPeersByDistance:()=>OD,syncService:()=>l3,xorDistanceBytes:()=>LD});function ut(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ch=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},jo=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ch(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new ch(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Em=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ot(r={}){return FD(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function FD(r,e){e=e??{};let t=e.onEnd,n=new jo,s,o,i,a=ut(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{o=b=>{o=null,n.push(b);try{g(r(n))}catch(E){y(E)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ut()})}},l=g=>o!=null?o(g):(n.push(g),s),u=g=>(n=new jo,o!=null?o({error:g}):(n.push({error:g}),s)),d=g=>{if(i)return s;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},p=g=>i?s:(i=!0,g!=null?u(g):l({done:!0})),f=()=>(n=new jo,p(),{done:!0}),h=g=>(p(g),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:f,throw:h,push:d,end:p,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,E;y!=null&&(b=new Promise((w,v)=>{E=()=>{v(new Em)},y.addEventListener("abort",E)}));try{await Promise.race([a.promise,b])}finally{E!=null&&y!=null&&y?.removeEventListener("abort",E)}}},t==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(g){return m.end(g),t!=null&&(t(g),t=void 0),s},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},s}var lh=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function uh(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new lh(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new lh(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Sm=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ut(),this.haveNext=ut()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ut(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ut(),await uh(this.readNext.promise,t?.signal,t)}};function H5(){return new Sm}function zD(r){return r[Symbol.asyncIterator]!=null}async function $D(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*HD(r){let e=new AbortController,t=H5();$D(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*qD(r){for(let e of r)yield*e}function VD(...r){let e=[];for(let t of r)zD(t)||e.push(t);return e.length===r.length?qD(e):HD(r)}var Ks=VD;function ht(r,...e){if(r==null)throw new Error("Empty pipeline");if(Im(r)){let n=r;r=()=>n.source}else if(V5(r)||q5(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Im(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Im(t[n])&&(t[n]=WD(t[n]));return GD(...t)}var GD=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},q5=r=>r?.[Symbol.asyncIterator]!=null,V5=r=>r?.[Symbol.iterator]!=null,Im=r=>r==null?!1:r.sink!=null&&r.source!=null,WD=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Ot({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(q5(o))s=async function*(){yield*o,n.end()};else if(V5(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ks(n,s())}return r.source};gr();Be();rt();var dh=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Yo=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},fh=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},lc=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ph(r){return r[Symbol.asyncIterator]!=null}function Y5(r,e){if(r.byteLength>e)throw new Yo("Message length too long")}var gh=r=>{let e=Ae(r),t=tt(e);return Vr(r,t),gh.bytes=e,t};gh.bytes=0;function yr(r,e){e=e??{};let t=e.lengthEncoder??gh,n=e?.maxDataLength??4194304;function*s(o){Y5(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return ph(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}yr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??gh,n=e?.maxDataLength??4194304;return Y5(r,n),new U(t(r.byteLength),r)};gr();Be();var Fs;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Fs||(Fs={}));var km=r=>{let e=jt(r);return km.bytes=Ae(e),e};km.bytes=0;function Pr(r,e){let t=new U,n=Fs.LENGTH,s=-1,o=e?.lengthDecoder??km,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Fs.LENGTH)try{if(s=o(t),s<0)throw new dh("Invalid message length");if(s>a)throw new Yo("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Fs.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new fh("Message length length too long");break}throw l}if(n===Fs.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Fs.LENGTH}}}return ph(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new lc("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new lc("Unexpected end of input")})()}Pr.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Pr(n,{...e??{},onLength:o=>{t=o}})};async function Lm(r,e=()=>{throw new Error("No items found")},t){let n=new AbortController,s=typeof t=="number"?setTimeout(()=>n.abort(),t):void 0;try{for await(let o of r(n.signal))return o;return e()}finally{s!==void 0&&clearTimeout(s),n.abort()}}async function uc(r){let e=[];for await(let t of r)e.push(t);return e}function tk(r,e,t){let n=t,s=0;for(let o of r)n=e(n,o,s),++s;return n}var Cn=class{peerId;peerNetwork;constructor(e,t){this.peerId=e,this.peerNetwork=t}async processMessage(e,t,n){let s=await this.peerNetwork.connect(this.peerId,t,{signal:n?.signal});try{let o=ht([new TextEncoder().encode(JSON.stringify(e))],yr);for await(let a of o)s.send(a);let i=ht(s,Pr,async function*(a){for await(let c of a){let l=new TextDecoder().decode(c.subarray());yield JSON.parse(l)}});return await Lm(()=>i,()=>{throw new Error("No response received")})}finally{await s.close()}}};ke();var ro=class r extends Cn{protocolPrefix;constructor(e,t,n){super(e,t),this.protocolPrefix=n}static create(e,t,n){return new r(e,t,n)}async update(e,t=0){let n={operation:"update",record:e},s=(this.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",o;try{o=await this.processMessage(n,s)}catch(i){if(s!=="/db-p2p/cluster/1.0.0")o=await this.processMessage(n,"/db-p2p/cluster/1.0.0");else throw i}if(o?.redirect?.peers?.length){if(t>=2)throw new Error("Redirect loop detected in ClusterClient (max hops reached)");let i=this.peerId.toString(),a=o.redirect.peers.find(u=>u.id!==i)??o.redirect.peers[0],c=de(a.id);if(a.id===i)throw new Error("Redirect loop detected in ClusterClient (same peer)");return this.recordCoordinatorForRecordIfSupported(e,c),await r.create(c,this.peerNetwork,this.protocolPrefix).update(e,t+1)}return o}recordCoordinatorForRecordIfSupported(e,t){let n=e?.message,s;if(n?.commit?.tailId)s=n.commit.tailId;else if(n?.pend?.transforms){let o=Object.keys(n.pend.transforms);o.length>0&&(s=o[0])}if(s){let o=new TextEncoder().encode(s),i=this.peerNetwork;typeof i?.recordCoordinator=="function"&&i.recordCoordinator(o,t)}}};var G2=new Map;function tn(r,e){if(G2.has(r))throw new Error(`Block type ${r} (${e}) already registered (${G2.get(r)})`);return G2.set(r,e),r}function pd(r,[e,t,n,s]){Array.isArray(s)?r[e].splice(t,n,...structuredClone(s)):r[e]=structuredClone(s)}function SM(r,e){for(let t of e)pd(r,t)}function gs(r){if(!r)return[];let e=Object.keys(r.inserts??{}),t=Object.keys(r.updates??{}),n=r.deletes??[];return[...new Set([...e,...t,...n])]}function W2(){return{inserts:{},updates:{},deletes:[]}}function md(r,e){return{...r.inserts&&e in r.inserts?{insert:r.inserts[e]}:{},...r.updates&&e in r.updates?{updates:structuredClone(r.updates[e])}:{},...r.deletes?.includes(e)?{delete:!0}:{}}}function j2(r,e){return{inserts:r.insert?{[e]:r.insert}:{},updates:r.updates?{[e]:r.updates}:{},deletes:r.delete?[e]:[]}}function cl(r,e){if(e.insert&&(r=e.insert),r&&e.updates&&SM(r,e.updates),!e.delete)return r}function Y2(r,e,t){return{inserts:{...r.inserts,...t.insert?{[e]:t.insert}:{}},updates:{...r.updates,...t.updates?{[e]:t.updates}:{}},deletes:[...r.deletes??[],...t.delete?[e]:[]]}}function Xt(r,e){return e??r}var IM=tn("TL","TreeLeaf"),AM=tn("TB","TreeBranch"),CM=Xt("entries"),TM=Xt("partitions"),_M=Xt("nodes");var kM=Xt("entries"),LM=Xt("priorId"),MM=Xt("nextId"),OM=tn("CHD","ChainDataBlock"),RM=Xt("headId"),NM=Xt("tailId"),BM=tn("CHH","ChainHeaderBlock");var eg={};z(eg,{base10:()=>VM});var Ere=new Uint8Array(0);function zE(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function vr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function $E(r){return new TextEncoder().encode(r)}function HE(r){return new TextDecoder().decode(r)}function KM(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var FM=KM,zM=FM,VE=zM;var X2=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Q2=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 GE(this,e)}},J2=class{decoders;constructor(e){this.decoders=e}or(e){return GE(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function GE(r,e){return new J2({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Z2=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new X2(e,t,n),this.decoder=new Q2(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ti({name:r,prefix:e,encode:t,decode:n}){return new Z2(r,e,t,n)}function ys({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=VE(t,r);return Ti({prefix:e,name:r,encode:n,decode:o=>vr(s(o))})}function $M(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function HM(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function qM(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function He({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=qM(n);return Ti({prefix:e,name:r,encode(o){return HM(o,n,t)},decode(o){return $M(o,s,t,r)}})}var VM=ys({prefix:"9",name:"base10",alphabet:"0123456789"});var tg={};z(tg,{base16:()=>GM,base16upper:()=>WM});var GM=He({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),WM=He({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var rg={};z(rg,{base2:()=>jM});var jM=He({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ng={};z(ng,{base256emoji:()=>ZM});var WE=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}"),YM=WE.reduce((r,e,t)=>(r[t]=e,r),[]),XM=WE.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function QM(r){return r.reduce((e,t)=>(e+=YM[t],e),"")}function JM(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=XM[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var ZM=Ti({prefix:"\u{1F680}",name:"base256emoji",encode:QM,decode:JM});var sg={};z(sg,{base32:()=>_i,base32hex:()=>nO,base32hexpad:()=>oO,base32hexpadupper:()=>iO,base32hexupper:()=>sO,base32pad:()=>tO,base32padupper:()=>rO,base32upper:()=>eO,base32z:()=>aO});var _i=He({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),eO=He({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tO=He({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rO=He({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),nO=He({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),sO=He({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),oO=He({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),iO=He({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aO=He({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var og={};z(og,{base36:()=>ll,base36upper:()=>cO});var ll=ys({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cO=ys({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ig={};z(ig,{base58btc:()=>rn,base58flickr:()=>lO});var rn=ys({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),lO=ys({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ag={};z(ag,{base64:()=>uO,base64pad:()=>hO,base64url:()=>dO,base64urlpad:()=>fO});var uO=He({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),hO=He({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),dO=He({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),fO=He({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var cg={};z(cg,{base8:()=>pO});var pO=He({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var lg={};z(lg,{identity:()=>mO});var mO=Ti({prefix:"\0",name:"identity",encode:r=>HE(r),decode:r=>$E(r)});var Ure=new TextEncoder,Kre=new TextDecoder;var hg={};z(hg,{identity:()=>UO});var bO=XE,jE=128,wO=127,xO=~wO,vO=Math.pow(2,31);function XE(r,e,t){e=e||[],t=t||0;for(var n=t;r>=vO;)e[t++]=r&255|jE,r/=128;for(;r&xO;)e[t++]=r&255|jE,r>>>=7;return e[t]=r|0,XE.bytes=t-n+1,e}var EO=ug,SO=128,YE=127;function ug(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw ug.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&YE)<<s:(i&YE)*Math.pow(2,s),s+=7}while(i>=SO);return ug.bytes=o-n,t}var IO=Math.pow(2,7),AO=Math.pow(2,14),CO=Math.pow(2,21),TO=Math.pow(2,28),_O=Math.pow(2,35),PO=Math.pow(2,42),DO=Math.pow(2,49),kO=Math.pow(2,56),LO=Math.pow(2,63),MO=function(r){return r<IO?1:r<AO?2:r<CO?3:r<TO?4:r<_O?5:r<PO?6:r<DO?7:r<kO?8:r<LO?9:10},OO={encode:bO,decode:EO,encodingLength:MO},RO=OO,ul=RO;function hl(r,e=0){return[ul.decode(r,e),ul.decode.bytes]}function Pi(r,e,t=0){return ul.encode(r,e,t),e}function Di(r){return ul.encodingLength(r)}function Li(r,e){let t=e.byteLength,n=Di(r),s=n+Di(t),o=new Uint8Array(s+t);return Pi(r,o,0),Pi(t,o,n),o.set(e,s),new ki(r,t,e,o)}function QE(r){let e=vr(r),[t,n]=hl(e),[s,o]=hl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ki(t,s,i,e)}function JE(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&zE(r.bytes,t.bytes)}}var ki=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var ZE=0,NO="identity",eS=vr;function BO(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Li(ZE,eS(r))}var UO={code:ZE,name:NO,encode:eS,digest:BO};var mg={};z(mg,{sha256:()=>FO,sha512:()=>zO});var pg=ae(te("crypto"),1);var KO=20;function fg({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new dg(r,e,t,n,s)}var dg=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??KO,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?tS(n,this.code,t?.truncate):n.then(s=>tS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function tS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Li(e,r)}var FO=fg({name:"sha2-256",code:18,encode:r=>vr(pg.default.createHash("sha256").update(r).digest())}),zO=fg({name:"sha2-512",code:19,encode:r=>vr(pg.default.createHash("sha512").update(r).digest())});function nS(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return HO(t,gg(r),e??rn.encoder);default:return qO(t,gg(r),e??_i.encoder)}}var sS=new WeakMap;function gg(r){let e=sS.get(r);if(e==null){let t=new Map;return sS.set(r,t),t}return e}var yd=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==fl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==VO)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Li(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&JE(e.multihash,n.multihash)}toString(e){return nS(this,e)}toJSON(){return{"/":nS(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??oS(n,s,o.bytes))}else if(t[GO]===!0){let{version:n,multihash:s,code:o}=t,i=QE(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==fl)throw new Error(`Version 0 CID must use dag-pb (code: ${fl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=oS(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,fl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=vr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ki(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=hl(e.subarray(t));return t+=p,d},s=n(),o=fl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=$O(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gg(o).set(n,e),o}};function $O(r,e){switch(r[0]){case"Q":{let t=e??rn;return[rn.prefix,t.decode(`${rn.prefix}${r}`)]}case rn.prefix:{let t=e??rn;return[rn.prefix,t.decode(r)]}case _i.prefix:{let t=e??_i;return[_i.prefix,t.decode(r)]}case ll.prefix:{let t=e??ll;return[ll.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function HO(r,e,t){let{prefix:n}=t;if(n!==rn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function qO(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var fl=112,VO=18;function oS(r,e,t){let n=Di(r),s=n+Di(e),o=new Uint8Array(s+t.byteLength);return Pi(r,o,0),Pi(e,o,n),o.set(t,s),o}var GO=Symbol.for("@ipld/js-cid/CID");var yg={...lg,...rg,...cg,...eg,...tg,...sg,...og,...ig,...ag,...ng},cne={...mg,...hg};var aS=te("node:buffer");function iS(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function cS(r=0){return iS(aS.Buffer.allocUnsafe(r))}function uS(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var lS=uS("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),bg=uS("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=cS(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),mne={utf8:lS,"utf-8":lS,hex:yg.base16,latin1:bg,ascii:bg,binary:bg,...yg};var no=class{static lockQueues=new Map;static async acquire(e){let t=this.lockQueues.get(e)??Promise.resolve(),n,s=new Promise(i=>{n=i});return this.lockQueues.set(e,s),await t,()=>{n(),this.lockQueues.get(e)===s&&this.lockQueues.delete(e)}}};var XO=tn("DIH","DiaryHeaderBlock");var QO=tn("TRE","TreeHeaderBlock"),JO=Xt("rootId");var Cg=ae(te("crypto"),1);var ose=new Uint8Array(0);function bd(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var ZO=pS,dS=128,eR=127,tR=~eR,rR=Math.pow(2,31);function pS(r,e,t){e=e||[],t=t||0;for(var n=t;r>=rR;)e[t++]=r&255|dS,r/=128;for(;r&tR;)e[t++]=r&255|dS,r>>>=7;return e[t]=r|0,pS.bytes=t-n+1,e}var nR=wg,sR=128,fS=127;function wg(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw wg.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&fS)<<s:(i&fS)*Math.pow(2,s),s+=7}while(i>=sR);return wg.bytes=o-n,t}var oR=Math.pow(2,7),iR=Math.pow(2,14),aR=Math.pow(2,21),cR=Math.pow(2,28),lR=Math.pow(2,35),uR=Math.pow(2,42),hR=Math.pow(2,49),dR=Math.pow(2,56),fR=Math.pow(2,63),pR=function(r){return r<oR?1:r<iR?2:r<aR?3:r<cR?4:r<lR?5:r<uR?6:r<hR?7:r<dR?8:r<fR?9:10},mR={encode:ZO,decode:nR,encodingLength:pR},gR=mR,xg=gR;function vg(r,e,t=0){return xg.encode(r,e,t),e}function Eg(r){return xg.encodingLength(r)}function mS(r,e){let t=e.byteLength,n=Eg(r),s=n+Eg(t),o=new Uint8Array(s+t);return vg(r,o,0),vg(t,o,n),o.set(e,s),new Sg(r,t,e,o)}var Sg=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var wR=20;function Ag({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Ig(r,e,t,n,s)}var Ig=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??wR,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?gS(n,this.code,t?.truncate):n.then(s=>gS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function gS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return mS(e,r)}var yS=Ag({name:"sha2-256",code:18,encode:r=>bd(Cg.default.createHash("sha256").update(r).digest())}),mse=Ag({name:"sha2-512",code:19,encode:r=>bd(Cg.default.createHash("sha512").update(r).digest())});var Ise=Xt("priorHash");Tg();Tg();var so=class{promise;response;error;t1=Date.now();duration;get isResponse(){return this.response!==void 0}get isError(){return this.error!==void 0}get isComplete(){return this.isResponse||this.isError}async result(){if(this.isResponse)return this.response;if(this.isError)throw this.error;return await this.promise}constructor(e){this.promise=e,e.then(t=>(this.duration=Date.now()-this.t1,this.response=t,t),t=>{this.duration=Date.now()-this.t1,this.error=t})}};function _g(r,e){return r.reduce((t,n)=>{let s=e(n);return(t[s]??=[]).push(n),t},{})}ke();var Ng=ae(te("crypto"),1);var Sie=new Uint8Array(0);function Mi(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var vR=SS,vS=128,ER=127,SR=~ER,IR=Math.pow(2,31);function SS(r,e,t){e=e||[],t=t||0;for(var n=t;r>=IR;)e[t++]=r&255|vS,r/=128;for(;r&SR;)e[t++]=r&255|vS,r>>>=7;return e[t]=r|0,SS.bytes=t-n+1,e}var AR=Pg,CR=128,ES=127;function Pg(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Pg.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&ES)<<s:(i&ES)*Math.pow(2,s),s+=7}while(i>=CR);return Pg.bytes=o-n,t}var TR=Math.pow(2,7),_R=Math.pow(2,14),PR=Math.pow(2,21),DR=Math.pow(2,28),kR=Math.pow(2,35),LR=Math.pow(2,42),MR=Math.pow(2,49),OR=Math.pow(2,56),RR=Math.pow(2,63),NR=function(r){return r<TR?1:r<_R?2:r<PR?3:r<DR?4:r<kR?5:r<LR?6:r<MR?7:r<OR?8:r<RR?9:10},BR={encode:vR,decode:AR,encodingLength:NR},UR=BR,Dg=UR;function kg(r,e,t=0){return Dg.encode(r,e,t),e}function Lg(r){return Dg.encodingLength(r)}function IS(r,e){let t=e.byteLength,n=Lg(r),s=n+Lg(t),o=new Uint8Array(s+t);return kg(r,o,0),kg(t,o,n),o.set(e,s),new Mg(r,t,e,o)}var Mg=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var zR=20;function Rg({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Og(r,e,t,n,s)}var Og=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??zR,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?AS(n,this.code,t?.truncate):n.then(s=>AS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function AS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return IS(e,r)}var nn=Rg({name:"sha2-256",code:18,encode:r=>Mi(Ng.default.createHash("sha256").update(r).digest())}),Mie=Rg({name:"sha2-512",code:19,encode:r=>Mi(Ng.default.createHash("sha512").update(r).digest())});function $R(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var HR=$R,qR=HR,CS=qR;var Bg=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ug=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 TS(this,e)}},Kg=class{decoders;constructor(e){this.decoders=e}or(e){return TS(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function TS(r,e){return new Kg({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Fg=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Bg(e,t,n),this.decoder=new Ug(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function VR({name:r,prefix:e,encode:t,decode:n}){return new Fg(r,e,t,n)}function zg({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=CS(t,r);return VR({prefix:e,name:r,encode:n,decode:o=>Mi(s(o))})}var wd=zg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Fie=zg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});ie();var NS=ae(Wg(),1),g9="optimystic:db-p2p";function Sr(r){return(0,NS.default)(`${g9}:${r}`)}var ye=Sr("cluster-member"),xt;(function(r){r[r.Promising=0]="Promising",r[r.OurPromiseNeeded=1]="OurPromiseNeeded",r[r.OurCommitNeeded=2]="OurCommitNeeded",r[r.Consensus=3]="Consensus",r[r.Rejected=4]="Rejected",r[r.Propagating=5]="Propagating"})(xt||(xt={}));function jg(r){return new Cd(r.storageRepo,r.peerNetwork,r.peerId,r.protocolPrefix,r.partitionDetector,r.fretService,r.validator)}var y9=600*1e3,Cd=class{storageRepo;peerNetwork;peerId;protocolPrefix;partitionDetector;fretService;validator;activeTransactions=new Map;executedTransactions=new Map;cleanupQueue=[];pendingUpdates=new Map;constructor(e,t,n,s,o,i,a){this.storageRepo=e,this.peerNetwork=t,this.peerId=n,this.protocolPrefix=s,this.partitionDetector=o,this.fretService=i,this.validator=a,setInterval(()=>this.queueExpiredTransactions(),6e4),setInterval(()=>this.processCleanupQueue(),1e3)}wasTransactionExecuted(e){return this.executedTransactions.has(e)}async update(e){let t=this.pendingUpdates.get(e.messageHash);t&&(ye("cluster-member:concurrent-update-wait",{messageHash:e.messageHash}),await t);let n=this.processUpdate(e);this.pendingUpdates.set(e.messageHash,n);try{return await n}finally{setTimeout(()=>{this.pendingUpdates.delete(e.messageHash)},100)}}async processUpdate(e){let t=this.peerId.toString(),n=e.commits[t]?"commit":e.promises[t]?"promise":"initial";if(ye("cluster-member:incoming",{messageHash:e.messageHash,phase:n,peerCount:Object.keys(e.peers).length,promiseCount:Object.keys(e.promises).length,commitCount:Object.keys(e.commits).length,existingTransaction:this.activeTransactions.has(e.messageHash)}),this.fretService&&e.networkSizeHint&&e.networkSizeConfidence)try{this.fretService.reportNetworkSize(e.networkSizeHint,e.networkSizeConfidence,"cluster")}catch{}await this.validateRecord(e);let s=this.activeTransactions.get(e.messageHash),o=s?.record||e;s&&ye("cluster-member:merge-start",{messageHash:e.messageHash,existingPromises:Object.keys(s.record.promises??{}),existingCommits:Object.keys(s.record.commits??{}),incomingPromises:Object.keys(e.promises??{}),incomingCommits:Object.keys(e.commits??{})}),s&&(o=await this.mergeRecords(s.record,e),ye("cluster-member:merge-complete",{messageHash:e.messageHash,mergedPromises:Object.keys(o.promises??{}),mergedCommits:Object.keys(o.commits??{})}));let i=await this.getTransactionPhase(o);ye("cluster-member:phase",{messageHash:e.messageHash,phase:i,promises:Object.keys(o.promises??{}),commits:Object.keys(o.commits??{})});let a=!0;switch(i){case xt.OurPromiseNeeded:ye("cluster-member:action-promise",{messageHash:e.messageHash}),o=await this.handlePromiseNeeded(o),ye("cluster-member:action-promise-complete",{messageHash:e.messageHash,promises:Object.keys(o.promises??{})});break;case xt.OurCommitNeeded:ye("cluster-member:action-commit",{messageHash:e.messageHash}),o=await this.handleCommitNeeded(o),ye("cluster-member:action-commit-complete",{messageHash:e.messageHash,commits:Object.keys(o.commits??{})}),await this.getTransactionPhase(o)===xt.Consensus&&(ye("cluster-member:action-consensus-after-commit",{messageHash:e.messageHash}),await this.handleConsensus(o)),a=!1;break;case xt.Consensus:ye("cluster-member:action-consensus",{messageHash:e.messageHash}),n!=="commit"?await this.handleConsensus(o):ye("cluster-member:consensus-skip-already-committed",{messageHash:e.messageHash}),a=!1;break;case xt.Rejected:ye("cluster-member:action-rejected",{messageHash:e.messageHash}),await this.handleRejection(o),a=!1;break;case xt.Propagating:ye("cluster-member:phase-propagating",{messageHash:e.messageHash}),a=!1;break;case xt.Promising:ye("cluster-member:phase-promising-blocked",{messageHash:e.messageHash});break}if(a){let c=this.setupTimeouts(o);this.activeTransactions.set(e.messageHash,{record:o,lastUpdate:Date.now(),promiseTimeout:c.promiseTimeout,resolutionTimeout:c.resolutionTimeout}),ye("cluster-member:state-persist",{messageHash:e.messageHash,storedPromises:Object.keys(o.promises??{}),storedCommits:Object.keys(o.commits??{})})}else ye("cluster-member:state-clear",{messageHash:e.messageHash}),this.clearTransaction(e.messageHash);return ye("cluster-member:update-complete",{messageHash:e.messageHash,promiseCount:Object.keys(o.promises).length,commitCount:Object.keys(o.commits).length}),o}async mergeRecords(e,t){if(ye("cluster-member:merge-records",{messageHash:e.messageHash,existingPromises:Object.keys(e.promises??{}),existingCommits:Object.keys(e.commits??{}),incomingPromises:Object.keys(t.promises??{}),incomingCommits:Object.keys(t.commits??{})}),e.messageHash!==t.messageHash)throw new Error("Message hash mismatch");if(JSON.stringify(e.message)!==JSON.stringify(t.message))throw new Error("Message content mismatch");if(JSON.stringify(e.peers)!==JSON.stringify(t.peers))throw new Error("Peers mismatch");return{...e,promises:{...e.promises,...t.promises},commits:{...e.commits,...t.commits}}}async validateRecord(e){let t=await this.computeMessageHash(e.message);if(t!==e.messageHash)throw new Error(`Message hash mismatch: expected=${t}, received=${e.messageHash}`);if(await this.validateSignatures(e),e.message.expiration&&e.message.expiration<Date.now())throw new Error("Transaction expired")}async computeMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),n=await nn.digest(t);return wd.encode(n.digest)}async validateSignatures(e){let t=await this.computePromiseHash(e);for(let[s,o]of Object.entries(e.promises))if(!await this.verifySignature(s,t,o))throw new Error(`Invalid promise signature from ${s}`);let n=await this.computeCommitHash(e);for(let[s,o]of Object.entries(e.commits))if(!await this.verifySignature(s,n,o))throw new Error(`Invalid commit signature from ${s}`)}async computePromiseHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)),n=await nn.digest(t);return T(n.digest,"base64url")}async computeCommitHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)+JSON.stringify(e.promises)),n=await nn.digest(t);return T(n.digest,"base64url")}async verifySignature(e,t,n){return!0}async getTransactionPhase(e){let t=Object.keys(e.peers).length,n=Object.keys(e.promises).length,s=Object.keys(e.commits).length,o=this.peerId.toString(),i=Object.values(e.promises).filter(l=>l.type==="reject"),a=Object.values(e.commits).filter(l=>l.type==="reject");if(i.length>0||this.hasMajority(a.length,t))return xt.Rejected;if(!e.promises[o]&&!this.hasConflict(e))return xt.OurPromiseNeeded;if(n<t)return xt.Promising;if(n===t&&!e.commits[o])return xt.OurCommitNeeded;let c=Object.values(e.commits).filter(l=>l.type==="approve");return this.hasMajority(c.length,t)?xt.Consensus:xt.Propagating}hasMajority(e,t){return e>t/2}async handlePromiseNeeded(e){let t=await this.validatePendOperations(e),n=t.valid?{type:"approve",signature:"approved"}:{type:"reject",signature:"rejected",rejectReason:t.reason};return t.valid||ye("cluster-member:validation-rejected",{messageHash:e.messageHash,reason:t.reason}),{...e,promises:{...e.promises,[this.peerId.toString()]:n}}}async validatePendOperations(e){for(let t of e.message.operations)if("pend"in t){let n=t.pend;if(n.rev!==void 0){let s=gs(n.transforms),o=await this.storageRepo.get({blockIds:s});for(let i of s){let c=o[i]?.state?.latest?.rev;if(c!==void 0&&c>=n.rev)return ye("cluster-member:validation-stale-revision",{messageHash:e.messageHash,blockId:i,requestedRev:n.rev,latestRev:c}),{valid:!1,reason:`stale revision: block ${i} at rev ${c}, requested rev ${n.rev}`}}}if(this.validator&&n.transaction&&n.operationsHash){let s=await this.validator.validate(n.transaction,n.operationsHash);if(!s.valid)return{valid:!1,reason:s.reason}}}return{valid:!0}}async handleCommitNeeded(e){if(this.hasLocalCommit(e))return e;let t={type:"approve",signature:"committed"};return{...e,commits:{...e.commits,[this.peerId.toString()]:t}}}async handleConsensus(e){if(this.executedTransactions.has(e.messageHash)){ye("cluster-member:consensus-already-executed",{messageHash:e.messageHash});return}this.executedTransactions.set(e.messageHash,Date.now());try{for(let t of e.message.operations)if("get"in t)await this.storageRepo.get(t.get);else if("pend"in t){let n=await this.storageRepo.pend(t.pend);if(!n.success)throw ye("cluster-member:consensus-pend-failed",{messageHash:e.messageHash,actionId:t.pend.actionId,reason:n.reason,hasMissing:!!n.missing?.length,hasPending:!!n.pending?.length}),new Error(`Consensus pend failed for action ${t.pend.actionId}: ${n.reason??"stale revision"}`)}else if("commit"in t){let n=await this.storageRepo.commit(t.commit);if(!n.success)throw ye("cluster-member:consensus-commit-failed",{messageHash:e.messageHash,actionId:t.commit.actionId,reason:n.reason,hasMissing:!!n.missing?.length}),new Error(`Consensus commit failed for action ${t.commit.actionId}: ${n.reason??"stale revision"}`)}else"cancel"in t&&await this.storageRepo.cancel(t.cancel.actionRef)}catch(t){throw this.executedTransactions.delete(e.messageHash),t}}async handleRejection(e){}setupTimeouts(e){return e.message.expiration?{promiseTimeout:setTimeout(()=>this.handleExpiration(e.messageHash),e.message.expiration-Date.now()),resolutionTimeout:setTimeout(()=>this.resolveWithPeers(e.messageHash),e.message.expiration+5e3-Date.now())}:{}}hasConflict(e){let t=Date.now(),n=2e3,s=this.getAffectedBlockIds(e.message.operations);ye("cluster-member:hasConflict-check",{messageHash:e.messageHash,activeCount:this.activeTransactions.size,incomingBlockIds:s});for(let[o,i]of Array.from(this.activeTransactions.entries())){if(o===e.messageHash)continue;let a=this.getAffectedBlockIds(i.record.message.operations);if(ye("cluster-member:hasConflict-compare",{existing:o,incoming:e.messageHash,existingBlockIds:a,incomingBlockIds:s}),t-i.lastUpdate>n){ye("cluster-member:stale-cleanup",{messageHash:o,age:t-i.lastUpdate}),this.clearTransaction(o);continue}if(this.operationsConflict(i.record.message.operations,e.message.operations)){if(this.resolveRace(i.record,e)==="keep-existing")return ye("cluster-member:race-keep-existing",{existing:o,incoming:e.messageHash}),!0;ye("cluster-member:race-accept-incoming",{existing:o,incoming:e.messageHash}),this.clearTransaction(o);continue}}return!1}resolveRace(e,t){let n=Object.keys(e.promises).length,s=Object.keys(t.promises).length;return n>s?"keep-existing":s>n?"accept-incoming":e.messageHash>t.messageHash?"keep-existing":"accept-incoming"}operationsConflict(e,t){let n=this.getActionId(e),s=this.getActionId(t);if(n&&s&&n===s)return!1;let o=new Set(this.getAffectedBlockIds(e)),i=new Set(this.getAffectedBlockIds(t));for(let a of Array.from(o))if(i.has(a))return ye("cluster-member:conflict-detected",{blocks1:Array.from(o),blocks2:Array.from(i),conflictingBlock:a}),!0;return!1}getActionId(e){for(let t of e){if("pend"in t)return t.pend.actionId;if("commit"in t)return t.commit.actionId;if("cancel"in t)return t.cancel.actionRef.actionId}}getAffectedBlockIds(e){let t=new Set;for(let n of e)"get"in n?n.get.blockIds.forEach(s=>t.add(s)):"pend"in n?gs(n.pend.transforms).forEach(s=>t.add(s)):"commit"in n?n.commit.blockIds.forEach(s=>t.add(s)):"cancel"in n&&n.cancel.actionRef.blockIds.forEach(s=>t.add(s));return Array.from(t)}async propagateIfNeeded(e){let t=[];for(let[n,s]of Object.entries(e.peers))if(n!==this.peerId.toString())try{let o=ro.create(de(n),this.peerNetwork,this.protocolPrefix);t.push(o.update(e))}catch(o){console.error(`Failed to propagate to peer ${n}:`,o)}await Promise.allSettled(t)}async handleExpiration(e){let t=this.activeTransactions.get(e);if(t&&!t.record.promises[this.peerId.toString()]){let n={type:"reject",signature:"rejected",rejectReason:"Transaction expired"},s={...t.record,promises:{...t.record.promises,[this.peerId.toString()]:n}};this.activeTransactions.set(e,{...t,record:s}),await this.propagateIfNeeded(s)}}async resolveWithPeers(e){ye("cluster-member:resolve-skipped",{messageHash:e,reason:"coordinator-handles-retry"})}queueExpiredTransactions(){let e=Date.now();for(let[n,s]of Array.from(this.activeTransactions.entries()))s.record.message.expiration&&s.record.message.expiration<e&&this.cleanupQueue.push(n);let t=e-y9;for(let[n,s]of Array.from(this.executedTransactions.entries()))s<t&&this.executedTransactions.delete(n)}async processCleanupQueue(){for(;this.cleanupQueue.length>0;){let e=this.cleanupQueue.shift();if(!e)continue;let t=this.activeTransactions.get(e);if(!t)continue;let n=await this.getTransactionPhase(t.record);n!==xt.Consensus&&n!==xt.Rejected&&this.activeTransactions.delete(e)}}hasLocalCommit(e){let t=this.peerId.toString();return!!e.commits[t]}clearTransaction(e){let t=this.activeTransactions.get(e);if(!t){ye("cluster-member:clear-miss",{messageHash:e});return}t.promiseTimeout&&clearTimeout(t.promiseTimeout),t.resolutionTimeout&&clearTimeout(t.resolutionTimeout),this.activeTransactions.delete(e),ye("cluster-member:clear-done",{messageHash:e,remaining:Array.from(this.activeTransactions.keys())})}};function Yg(r={}){return e=>new Td(e,r)}var Td=class{protocol;maxInboundStreams;maxOutboundStreams;log;cluster;components;running;k;configuredClusterSize;allowDownsize;sizeTolerance;responsibilityK;constructor(e,t={}){this.components=e,this.protocol=t.protocol??(t.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.log=e.logger.forComponent(t.logPrefix??"db-p2p:cluster"),this.cluster=e.cluster,this.running=!1,this.k=t.kBucketSize??10,this.configuredClusterSize=t.configuredClusterSize??10,this.allowDownsize=t.allowClusterDownsize??!0,this.sizeTolerance=t.clusterSizeTolerance??.5,this.responsibilityK=t.responsibilityK??1}[Symbol.toStringTag]="@libp2p/cluster";async start(){this.running||(await this.components.registrar.handle(this.protocol,this.handleIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.running=!0)}async stop(){this.running&&(await this.components.registrar.unhandle(this.protocol),this.running=!1)}handleIncomingStream(e,t){let n=t.remotePeer,s=async function*(o){for await(let i of o){let a=new TextDecoder().decode(i.subarray()),c=JSON.parse(a),l;if(c.operation==="update"){let d=c.record?.message?.commit?.tailId??c.record?.message?.pend?Object.keys(c.record.message.pend.transforms)[0]:void 0;l=await this.cluster.update(c.record)}else throw new Error(`Unknown operation: ${c.operation}`);if(c.operation==="update"){let d=l;this.log("cluster-service:pre-serialize",{messageHash:d?.messageHash,responseType:typeof l,hasPromises:"promises"in(d??{}),hasCommits:"commits"in(d??{}),promiseKeys:Object.keys(d?.promises??{}),commitKeys:Object.keys(d?.commits??{}),promiseValues:d?.promises,commitValues:d?.commits})}let u=JSON.stringify(l);if(c.operation==="update"){let d=JSON.parse(u);this.log("cluster-service:post-serialize",{messageHash:d?.messageHash,promiseKeys:Object.keys(d?.promises??{}),commitKeys:Object.keys(d?.commits??{})})}yield new TextEncoder().encode(u)}};(async()=>{try{let o=ht(e,i=>Pr(i),s.bind(this),i=>yr(i));for await(let i of o)e.send(i);await e.close()}catch(o){this.log.error("error handling cluster protocol message from %p - %e",n,o),e.abort(o instanceof Error?o:new Error(String(o)))}})()}};ke();var Xg=class r extends Cn{protocolPrefix;constructor(e,t,n){super(e,t),this.protocolPrefix=n}static create(e,t,n){return new r(e,t,n)}async get(e,t){return this.processRepoMessage([{get:e}],t)}async pend(e,t){return this.processRepoMessage([{pend:e}],t)}async cancel(e,t){return this.processRepoMessage([{cancel:{actionRef:e}}],t)}async commit(e,t){return this.processRepoMessage([{commit:e}],t)}async processRepoMessage(e,t,n=0){let s={operations:e,expiration:t.expiration},o=t.expiration??Date.now()+3e4,i=Math.max(1,o-Date.now()),a=async u=>await Promise.race([u(),new Promise((d,p)=>setTimeout(()=>p(new Error("RepoClient timeout")),i))]),c,l=(this.protocolPrefix??"/db-p2p")+"/repo/1.0.0";if(c=await a(()=>super.processMessage(s,l,{signal:t?.signal})),c?.redirect?.peers?.length){if(n>=2)throw new Error("Redirect loop detected in RepoClient (max hops reached)");let u=this.peerId.toString(),d=c.redirect.peers.find(h=>h.id!==u)??c.redirect.peers[0],p=de(d.id);if(d.id===u)throw new Error("Redirect loop detected in RepoClient (same peer)");return this.recordCoordinatorForOpsIfSupported(e,p),await r.create(p,this.peerNetwork,this.protocolPrefix).processRepoMessage(e,t,n+1)}return c}extractKeyFromOperations(e){let t=e[0];if("get"in t){let n=t.get.blockIds[0];return n?new TextEncoder().encode(n):void 0}if("pend"in t){let n=Object.keys(t.pend.transforms)[0];return n?new TextEncoder().encode(n):void 0}if("commit"in t)return new TextEncoder().encode(t.commit.tailId)}recordCoordinatorForOpsIfSupported(e,t){let n=this.extractKeyFromOperations(e),s=this.peerNetwork;n!=null&&typeof s?.recordCoordinator=="function"&&s.recordCoordinator(n,t)}};ke();var ne=Sr("cluster"),ml=class{keyNetwork;createClusterClient;cfg;localCluster;fretService;transactions=new Map;retryInitialIntervalMs=2e3;retryBackoffFactor=2;retryMaxIntervalMs=3e4;retryMaxAttempts=5;constructor(e,t,n,s,o){this.keyNetwork=e,this.createClusterClient=t,this.cfg=n,this.localCluster=s,this.fretService=o}async createMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),n=await nn.digest(t);return wd.encode(n.digest)}async getClusterForBlock(e){let t=new TextEncoder().encode(e);try{let n=await this.keyNetwork.findCluster(t),s=Object.keys(n??{});return ne("cluster-tx:cluster-members",{blockId:e,peerIds:s}),n}catch(n){return ne("WARN findCluster failed for %s: %o",e,n),{}}}makeRecord(e,t,n){let s=Object.keys(e??{}).length,o={messageHash:t,peers:e,message:n,coordinatingBlockIds:n.coordinatingBlockIds,promises:{},commits:{},suggestedClusterSize:s||void 0,minRequiredSize:this.cfg.allowClusterDownsize?void 0:this.cfg.clusterSize};if(this.fretService)try{let i=this.fretService.getNetworkSizeEstimate();i.size_estimate>0&&(o.networkSizeHint=i.size_estimate,o.networkSizeConfidence=i.confidence)}catch{}return o}async executeClusterTransaction(e,t,n){let s=await this.getClusterForBlock(e),o=await this.createMessageHash(t),i=this.makeRecord(s,o,t);ne("cluster-tx:start",{messageHash:o,blockId:e,peerCount:Object.keys(s??{}).length,allowDownsize:this.cfg.allowClusterDownsize,configuredSize:this.cfg.clusterSize,suggestedSize:i.suggestedClusterSize,minRequiredSize:i.minRequiredSize});let a=this.executeTransaction(s,i),c=new so(a),l={messageHash:o,record:i,pending:c,lastUpdate:Date.now()};this.transactions.set(o,l),ne("cluster-tx:transaction-store",{messageHash:o,transactionKeys:Array.from(this.transactions.keys())});try{let u=await c.result(),d=this.localCluster?.wasTransactionExecuted?.(o)??!1;return{record:u,localExecuted:d}}finally{let u=this.transactions.get(o),d=u?.retry?{attempt:u.retry.attempt,pending:Array.from(u.retry.pendingPeers??[])}:void 0;ne("cluster-tx:complete",{messageHash:o,finalPromises:u?Object.keys(u.record.promises??{}):void 0,finalCommits:u?Object.keys(u.record.commits??{}):void 0,retry:d}),u?.retry||setTimeout(()=>{this.transactions.delete(o),ne("cluster-tx:transaction-remove",{messageHash:o,remaining:Array.from(this.transactions.keys())})},100)}}async executeTransaction(e,t){let n=Object.keys(e).length;if(n<this.cfg.minAbsoluteClusterSize){if(!await this.validateSmallCluster(n,e))throw ne("cluster-tx:reject-too-small",{peerCount:n,minRequired:this.cfg.minAbsoluteClusterSize}),new Error(`Cluster size ${n} below minimum ${this.cfg.minAbsoluteClusterSize} and not validated`);ne("cluster-tx:small-cluster-validated",{peerCount:n})}if(!this.cfg.allowClusterDownsize&&n<this.cfg.clusterSize)throw ne("cluster-tx:reject-downsize",{peerCount:n,required:this.cfg.clusterSize}),new Error(`Cluster size ${n} below configured minimum ${this.cfg.clusterSize}`);let s=await this.collectPromises(e,t),o=Math.ceil(n*this.cfg.superMajorityThreshold),i=s.record.promises,a=Object.values(i).filter(u=>u.type==="approve").length,c=Object.values(i).filter(u=>u.type==="reject").length,l=n-o;if(c>l){let u=Object.entries(i).filter(([d,p])=>p.type==="reject").map(([d,p])=>`${d}: ${p.rejectReason??"unknown"}`).join("; ");throw ne("cluster-tx:rejected-by-validators",{messageHash:t.messageHash,peerCount:n,rejections:c,maxAllowed:l,reasons:u}),this.updateTransactionRecord(s.record,"rejected-by-validators"),new Error(`Transaction rejected by validators (${c}/${n} rejected): ${u}`)}if(n>1&&a<o)throw ne("cluster-tx:supermajority-failed",{messageHash:t.messageHash,peerCount:n,approvals:a,rejections:c,superMajority:o,threshold:this.cfg.superMajorityThreshold}),this.updateTransactionRecord(s.record,"supermajority-failed"),new Error(`Failed to get super-majority: ${a}/${n} approvals (needed ${o}, ${c} rejections)`);return await this.commitTransaction(s.record)}async getClusterSize(e){let t=await this.getClusterForBlock(e);return Object.keys(t??{}).length}async validateSmallCluster(e,t){if(this.fretService)try{let n=this.fretService.getNetworkSizeEstimate();if(n.confidence>.5){let s=Math.floor(Math.log10(n.size_estimate+1)),o=Math.floor(Math.log10(e+1));if(Math.abs(s-o)<=1)return ne("cluster-tx:small-cluster-validated-by-fret",{localSize:e,fretEstimate:n.size_estimate,confidence:n.confidence,sources:n.sources}),!0}}catch{}return ne("cluster-tx:small-cluster-accepted-without-validation",{localSize:e,reason:"no-confident-network-size-estimate"}),!0}async collectPromises(e,t){let n=Object.keys(e),s=[],o=n.map(l=>{let u=this.localCluster&&l===this.localCluster.peerId.toString();ne("cluster-tx:promise-request",{messageHash:t.messageHash,peerId:l,isLocal:u});let d=u?this.localCluster.update(t):this.createClusterClient(de(l)).update(t);return new so(d)}),i=await Promise.all(o.map((l,u)=>l.result().then(d=>{let p=n[u];return ne("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:p,success:!0,returnedPromises:Object.keys(d.promises??{}),returnedCommits:Object.keys(d.commits??{})}),s.push({peerId:p,success:!0}),d}).catch(d=>{let p=n[u];return ne("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:p,success:!1,error:d}),s.push({peerId:p,success:!1,error:d instanceof Error?d.message:String(d)}),null}))),a=s.filter(l=>l.success).map(l=>l.peerId),c=s.filter(l=>!l.success);ne("cluster-tx:promise-summary",{messageHash:t.messageHash,successes:a,failures:c}),ne("cluster-tx:promise-merge-begin",{messageHash:t.messageHash,initialPromises:Object.keys(t.promises??{}),transactionsKeys:Array.from(this.transactions.keys()),hasTransaction:this.transactions.has(t.messageHash)});for(let l of i.filter(Boolean)){ne("cluster-tx:promise-merge-input",{messageHash:t.messageHash,resultFrom:Object.keys(l.promises??{}),recordBefore:Object.keys(t.promises??{})});let u=Object.keys(l.promises??{});if(ne("cluster-tx:promise-merge-result",{messageHash:t.messageHash,peerPromises:u}),typeof t.suggestedClusterSize=="number"&&typeof l.suggestedClusterSize=="number"){let d=l.suggestedClusterSize,p=Object.keys(e).length,f=Math.ceil(Math.max(1,d*this.cfg.clusterSizeTolerance));Math.abs(p-d)>f&&ne("cluster-tx:size-variance",{expected:d,actual:p,tolerance:this.cfg.clusterSizeTolerance})}t.promises={...t.promises,...l.promises},ne("cluster-tx:promise-merge-after",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})})}return ne("cluster-tx:promise-merge",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})}),ne("cluster-tx:promise-merge-end",{messageHash:t.messageHash,finalPromises:Object.keys(t.promises??{}),transactionsEntry:this.transactions.get(t.messageHash)}),this.updateTransactionRecord(t,"after-promises"),{record:t}}async commitTransaction(e){let t=Object.keys(e.peers),n=[],s={...e},o=t.map(f=>{let h=this.localCluster&&f===this.localCluster.peerId.toString();ne("cluster-tx:commit-request",{messageHash:e.messageHash,peerId:f,isLocal:h});let m=h?this.localCluster.update(s):this.createClusterClient(de(f)).update(s);return new so(m)}),i=await Promise.all(o.map((f,h)=>f.result().then(m=>{let g=t[h];return ne("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!0}),n.push({peerId:g,success:!0}),m}).catch(m=>{let g=t[h];return ne("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!1,error:m}),n.push({peerId:g,success:!1,error:m instanceof Error?m.message:String(m)}),null}))),a=n.filter(f=>f.success).map(f=>f.peerId),c=n.filter(f=>!f.success);ne("cluster-tx:commit-summary",{messageHash:e.messageHash,successes:a,failures:c}),ne("cluster-tx:commit-merge-begin",{messageHash:e.messageHash,initialCommits:Object.keys(e.commits??{}),transactionsEntry:this.transactions.get(e.messageHash)});for(let f of i.filter(Boolean))ne("cluster-tx:commit-merge-input",{messageHash:e.messageHash,resultFrom:Object.keys(f.commits??{}),recordBefore:Object.keys(e.commits??{})}),ne("cluster-tx:commit-merge-result",{messageHash:e.messageHash,peerCommits:Object.keys(f.commits??{})}),e.commits={...e.commits,...f.commits},ne("cluster-tx:commit-merge-after",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})});ne("cluster-tx:commit-merge",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})}),ne("cluster-tx:commit-merge-end",{messageHash:e.messageHash,finalCommits:Object.keys(e.commits??{}),transactionsEntry:this.transactions.get(e.messageHash)}),this.updateTransactionRecord(e,"after-commit");let l=Object.keys(e.peers).length,u=Math.floor(l*this.cfg.simpleMajorityThreshold)+1,d=Object.keys(e.commits).length;if(d>=u&&(ne("cluster-tx:commit-majority-reached",{messageHash:e.messageHash,commitCount:d,simpleMajority:u,peerCount:l,threshold:this.cfg.simpleMajorityThreshold}),this.localCluster))try{await this.localCluster.update(e)}catch(f){ne("cluster-tx:local-execution-error",{messageHash:e.messageHash,error:f instanceof Error?f.message:String(f)})}let p=c.map(f=>f.peerId);return p.length>0?this.scheduleCommitRetry(e.messageHash,e,p):this.clearRetry(e.messageHash),e}updateTransactionRecord(e,t){let n=this.transactions.get(e.messageHash);if(!n){ne("cluster-tx:transaction-update-miss",{messageHash:e.messageHash,stage:t});return}n.record={...e},n.lastUpdate=Date.now(),ne("cluster-tx:transaction-update",{messageHash:e.messageHash,stage:t,promises:Object.keys(e.promises??{}),commits:Object.keys(e.commits??{})})}scheduleCommitRetry(e,t,n){let s=this.transactions.get(e);if(!s)return;let o=s.retry,i=(o?.attempt??0)+1;if(i>this.retryMaxAttempts){ne("cluster-tx:retry-abort",{messageHash:e,missingPeers:n});return}if(n.length===0){this.clearRetry(e);return}let a=new Set(n),c=o?Math.min(o.intervalMs*this.retryBackoffFactor,this.retryMaxIntervalMs):this.retryInitialIntervalMs;o?.timer&&clearTimeout(o.timer);let l=setTimeout(()=>{this.retryCommits(e)},c);s.retry={pendingPeers:a,attempt:i,intervalMs:c,timer:l},ne("cluster-tx:retry-scheduled",{messageHash:e,attempt:i,missingPeers:n,delayMs:c})}async retryCommits(e){let t=this.transactions.get(e);if(!t?.retry)return;let{pendingPeers:n,attempt:s}=t.retry;if(n.size===0){this.clearRetry(e);return}let o=Array.from(n),i=t.record;ne("cluster-tx:retry-start",{messageHash:e,attempt:s,peerIds:o});let a=await Promise.all(o.map(async u=>{let d=this.localCluster&&u===this.localCluster.peerId.toString(),p={...i,commits:i.commits};try{let f=d?await this.localCluster.update(p):await this.createClusterClient(de(u)).update(p);return t.record.commits={...t.record.commits,...f.commits},{peerId:u,success:!0}}catch(f){return{peerId:u,success:!1,error:f instanceof Error?f.message:String(f)}}})),c=a.filter(u=>u.success).map(u=>u.peerId),l=a.filter(u=>!u.success);for(let u of c)n.delete(u);if(ne("cluster-tx:retry-complete",{messageHash:e,attempt:s,successes:c,failures:l}),n.size===0){ne("cluster-tx:retry-finished",{messageHash:e}),this.clearRetry(e);return}this.transactions.has(e)&&this.scheduleCommitRetry(e,t.record,Array.from(n))}clearRetry(e){let t=this.transactions.get(e);t?.retry&&(t.retry.timer&&clearTimeout(t.retry.timer),t.retry=void 0,setTimeout(()=>{this.transactions.delete(e),ne("cluster-tx:transaction-remove",{messageHash:e,remaining:Array.from(this.transactions.keys())})},100))}};ke();var io=Sr("coordinator-repo");function Qg(r,e,t,n){return s=>new _d(r,e,s.storageRepo,t,s.localCluster,s.localPeerId,n,s.clusterLatestCallback)}var _d=class{keyNetwork;createClusterClient;storageRepo;clusterLatestCallback;coordinator;DEFAULT_TIMEOUT=3e4;constructor(e,t,n,s,o,i,a,c){this.keyNetwork=e,this.createClusterClient=t,this.storageRepo=n,this.clusterLatestCallback=c;let l={clusterSize:s?.clusterSize??10,superMajorityThreshold:s?.superMajorityThreshold??.75,simpleMajorityThreshold:s?.simpleMajorityThreshold??.51,minAbsoluteClusterSize:s?.minAbsoluteClusterSize??3,allowClusterDownsize:s?.allowClusterDownsize??!0,clusterSizeTolerance:s?.clusterSizeTolerance??.5,partitionDetectionWindow:s?.partitionDetectionWindow??6e4},u=o&&i?{update:o.update.bind(o),peerId:i,wasTransactionExecuted:o.wasTransactionExecuted?.bind(o)}:void 0;this.coordinator=new ml(e,t,l,u,a)}async get(e,t){let n=await this.storageRepo.get(e,t),s=t?.skipClusterFetch;if(this.clusterLatestCallback&&!s){for(let o of e.blockIds)if(!n[o]?.state?.latest)try{await this.fetchBlockFromCluster(o);let a=await this.storageRepo.get({blockIds:[o],context:e.context},t);a[o]&&(n[o]=a[o])}catch(a){io("cluster-fetch:error",{blockId:o,error:a.message})}}return n}async fetchBlockFromCluster(e){if(!this.clusterLatestCallback)return;let t=await this.queryClusterForLatest(e);t&&(await this.storageRepo.get({blockIds:[e],context:{committed:[t],rev:t.rev}}),io("cluster-fetch:synced",{blockId:e,rev:t.rev}))}async queryClusterForLatest(e){let t=new TextEncoder().encode(e),n=await this.keyNetwork.findCluster(t);if(!n||Object.keys(n).length===0)return;let s=Object.keys(n),o,i=(c,l)=>Promise.race([c,new Promise(u=>setTimeout(()=>u(void 0),l))]),a=await Promise.allSettled(s.map(c=>{let l=de(c);return i(this.clusterLatestCallback(l,e),3e3)}));for(let c of a)if(c.status==="fulfilled"&&c.value){let l=c.value;(!o||l.rev>o.rev)&&(o=l)}return o}async pend(e,t){let n=Object.keys(e.transforms),s=t?.coordinatingBlockIds??n;if(await this.coordinator.getClusterSize(s[0])<=1)return await this.storageRepo.pend(e,t);let i={operations:[{pend:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT,coordinatingBlockIds:s};try{let{localExecuted:a}=await this.coordinator.executeClusterTransaction(s[0],i,t);if(io("coordinator-repo:pend-cluster-complete",{actionId:e.actionId,localExecuted:a}),!a){let c=await this.storageRepo.pend(e,t);return io("coordinator-repo:pend-fallback-result",{actionId:e.actionId,success:c.success,hasMissing:!!c.missing?.length,hasPending:!!c.pending?.length}),c}return{success:!0,pending:[],blockIds:Object.keys(e.transforms)}}catch(a){throw io("coordinator-repo:pend-error",{actionId:e.actionId,error:a.message}),a}}async cancel(e,t){let n=e.blockIds,s={operations:[{cancel:{actionRef:e}}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let o=n.map(c=>this.coordinator.executeClusterTransaction(c,s,t));(await Promise.all(o)).some(c=>c.localExecuted)||await this.storageRepo.cancel(e,t)}catch(o){throw io("coordinator-repo:cancel-error",{actionId:e.actionId,error:o.message}),o}}async commit(e,t){let n=e.blockIds;if(await this.coordinator.getClusterSize(n[0])<=1)return await this.storageRepo.commit(e,t);let o={operations:[{commit:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let{localExecuted:i}=await this.coordinator.executeClusterTransaction(n[0],o,t);return i?{success:!0}:await this.storageRepo.commit(e,t)}catch(i){throw io("coordinator-repo:commit-error",{actionId:e.actionId,error:i.message}),i}}};function BS(r){try{if(r==null)return null;if(typeof r?.toString=="function")return r.toString();let e=r.id;return e&&typeof e.toString=="function"?e.toString():typeof e=="string"?e:typeof r=="string"?r:null}catch{return null}}function ao(r,e){let t=BS(r),n=BS(e);return t!=null&&n!=null&&t===n}function Pd(r){return{redirect:{peers:r,reason:"not_in_cluster"}}}function Jg(r={}){return e=>new Dd(e,r)}var Dd=class{protocol;maxInboundStreams;maxOutboundStreams;log;repo;components;running;k;responsibilityK;constructor(e,t={}){this.components=e;let n=t.protocol??(t.protocolPrefix??"/db-p2p")+"/repo/1.0.0";this.protocol=n,this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.log=e.logger.forComponent(t.logPrefix??"db-p2p:repo-service"),this.repo=e.repo,this.running=!1,this.k=t.kBucketSize??10,this.responsibilityK=t.responsibilityK??1}[Symbol.toStringTag]="@libp2p/repo-service";async start(){this.running||(await this.components.registrar.handle(this.protocol,this.handleIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.running=!0)}async stop(){this.running&&(await this.components.registrar.unhandle(this.protocol),this.running=!1)}handleIncomingStream(e,t){let n=t.remotePeer,s=async function*(o){for await(let i of o){let a=new TextDecoder().decode(i.subarray()),c=JSON.parse(a),l=c.operations[0],u;if("get"in l){let p=(await nn.digest(new TextEncoder().encode(l.get.blockIds[0]))).digest,f=this.components.libp2p?.services?.networkManager;if(f?.getCluster){let h=await f.getCluster(p);c.cluster=h.map(b=>b.toString?.()??String(b));let m=this.components.libp2p.peerId,g=h.some(b=>ao(b,m));if(!(h.length<this.responsibilityK)&&!g){let b=h.filter(E=>!ao(E,m));console.debug("repo-service:redirect",{peerId:m.toString(),reason:"not-cluster-member",operation:"get",blockId:l.get.blockIds[0],cluster:h.map(E=>E.toString?.()??String(E))}),u=Pd(b.map(E=>({id:E.toString(),addrs:[]})))}else u=await this.repo.get(l.get,{expiration:c.expiration,skipClusterFetch:!0})}else u=await this.repo.get(l.get,{expiration:c.expiration,skipClusterFetch:!0})}else if("pend"in l){let d=Object.keys(l.pend.transforms)[0],f=(await nn.digest(new TextEncoder().encode(d))).digest,h=this.components.libp2p?.services?.networkManager;if(h?.getCluster){let m=await h.getCluster(f);c.cluster=m.map(E=>E.toString?.()??String(E));let g=this.components.libp2p.peerId,y=m.some(E=>ao(E,g));if(!(m.length<this.responsibilityK)&&!y){let E=m.filter(w=>!ao(w,g));console.debug("repo-service:redirect",{peerId:g.toString(),reason:"not-cluster-member",operation:"pend",blockId:d,cluster:m.map(w=>w.toString?.()??String(w))}),u=Pd(E.map(w=>({id:w.toString(),addrs:[]})))}else u=await this.repo.pend(l.pend,{expiration:c.expiration})}else u=await this.repo.pend(l.pend,{expiration:c.expiration})}else if("cancel"in l)u=await this.repo.cancel(l.cancel.actionRef,{expiration:c.expiration});else if("commit"in l){let p=(await nn.digest(new TextEncoder().encode(l.commit.tailId))).digest,f=this.components.libp2p?.services?.networkManager;if(f?.getCluster){let h=await f.getCluster(p);c.cluster=h.map(b=>b.toString?.()??String(b));let m=this.components.libp2p.peerId,g=h.some(b=>ao(b,m));if(!(h.length<this.responsibilityK)&&!g){let b=h.filter(E=>!ao(E,m));console.debug("repo-service:redirect",{peerId:m.toString(),reason:"not-cluster-member",operation:"commit",tailId:l.commit.tailId,cluster:h.map(E=>E.toString?.()??String(E))}),u=Pd(b.map(E=>({id:E.toString(),addrs:[]})))}else u=await this.repo.commit(l.commit,{expiration:c.expiration})}else u=await this.repo.commit(l.commit,{expiration:c.expiration})}yield new TextEncoder().encode(JSON.stringify(u))}};(async()=>{try{let o=ht(e,i=>Pr(i),s.bind(this),i=>yr(i));for await(let i of o)e.send(i);await e.close()}catch(o){this.log.error("error handling repo protocol message from %p - %e",n,o),e.abort(o instanceof Error?o:new Error(String(o)))}})()}};function US(r){if(r.length<=1)return r;r.sort((t,n)=>t[0]-n[0]);let e=[r[0]];for(let t of r.slice(1)){let n=e[e.length-1];n[1]!==void 0&&(t[0]<=n[1]?t[1]===void 0?n[1]=void 0:n[1]=Math.max(n[1],t[1]):e.push(t))}return e}var Bi=class{blockId;storage;restoreCallback;constructor(e,t,n){this.blockId=e,this.storage=t,this.restoreCallback=n}async getLatest(){return(await this.storage.getMetadata(this.blockId))?.latest}async getBlock(e){let t=await this.storage.getMetadata(this.blockId);if(!t)return;let n=e??t.latest?.rev;if(n===void 0)throw new Error(`No revision specified and no latest revision exists for block ${this.blockId}`);return await this.ensureRevision(t,n),await this.materializeBlock(t,n)}async getTransaction(e){return await this.storage.getTransaction(this.blockId,e)}async getPendingTransaction(e){return await this.storage.getPendingTransaction(this.blockId,e)}async*listPendingTransactions(){yield*this.storage.listPendingTransactions(this.blockId)}async savePendingTransaction(e,t){let n=await this.storage.getMetadata(this.blockId);n||(n={latest:void 0,ranges:[[0]]},await this.storage.saveMetadata(this.blockId,n)),await this.storage.savePendingTransaction(this.blockId,e,t)}async deletePendingTransaction(e){await this.storage.deletePendingTransaction(this.blockId,e)}async*listRevisions(e,t){yield*this.storage.listRevisions(this.blockId,e,t)}async saveMaterializedBlock(e,t){await this.storage.saveMaterializedBlock(this.blockId,e,t)}async saveRevision(e,t){await this.storage.saveRevision(this.blockId,e,t)}async promotePendingTransaction(e){await this.storage.promotePendingTransaction(this.blockId,e)}async setLatest(e){let t=await this.storage.getMetadata(this.blockId);if(!t)throw new Error(`Block ${this.blockId} not found`);t.latest=e,await this.storage.saveMetadata(this.blockId,t)}async ensureRevision(e,t){if(this.inRanges(t,e.ranges))return;let n=`BlockStorage.ensureRevision:${this.blockId}`,s=await no.acquire(n);try{let o=await this.storage.getMetadata(this.blockId);if(!o)throw new Error(`Block ${this.blockId} metadata disappeared unexpectedly.`);if(this.inRanges(t,o.ranges))return;let i=await this.restoreBlock(t);if(!i)throw new Error(`Block ${this.blockId} revision ${t} not found during restore attempt.`);await this.saveRestored(i),o.ranges.unshift(i.range),o.ranges=US(o.ranges),await this.storage.saveMetadata(this.blockId,o)}finally{s()}}async materializeBlock(e,t){let n,s,o=[];for await(let i of this.storage.listRevisions(this.blockId,t,1)){let a=await this.storage.getMaterializedBlock(this.blockId,i.actionId);if(a){n=a,s=i;break}else o.push(i)}if(!n||!s)throw new Error(`Failed to find materialized block ${this.blockId} for revision ${t}`);for(let i=o.length-1;i>=0;--i){let{actionId:a}=o[i],c=await this.storage.getTransaction(this.blockId,a);if(!c)throw new Error(`Missing action ${a} for block ${this.blockId}`);n=cl(n,c)}if(!n)throw new Error(`Block ${this.blockId} has been deleted`);return o.length?(await this.storage.saveMaterializedBlock(this.blockId,o[0].actionId,n),{block:n,actionRev:o[0]}):{block:n,actionRev:s}}async restoreBlock(e){if(this.restoreCallback)return await this.restoreCallback(this.blockId,e)}async saveRestored(e){let t=Object.entries(e.revisions).map(([n,s])=>({rev:Number(n),data:s}));for(let{rev:n,data:{action:s,block:o}}of t)await Promise.all([this.storage.saveRevision(this.blockId,n,s.actionId),this.storage.saveTransaction(this.blockId,s.actionId,s.transform),o?this.storage.saveMaterializedBlock(this.blockId,s.actionId,o):Promise.resolve()])}inRanges(e,t){return t.some(n=>e>=n[0]&&(n[1]===void 0||e<n[1]))}};var gl=class{metadata=new Map;revisions=new Map;pendingActions=new Map;actions=new Map;materializedBlocks=new Map;getRevisionKey(e,t){return`${e}:${t}`}getActionKey(e,t){return`${e}:${t}`}async getMetadata(e){return this.metadata.get(e)}async saveMetadata(e,t){this.metadata.set(e,t)}async getRevision(e,t){return this.revisions.get(this.getRevisionKey(e,t))}async saveRevision(e,t,n){this.revisions.set(this.getRevisionKey(e,t),n)}async*listRevisions(e,t,n){let s=t<=n,o=s?t:n,i=s?n:t,a=[];for(let c=o;c<=i;c++){let l=this.revisions.get(this.getRevisionKey(e,c));l&&a.push({rev:c,actionId:l})}s||a.reverse();for(let c of a)yield c}async getPendingTransaction(e,t){return this.pendingActions.get(this.getActionKey(e,t))}async savePendingTransaction(e,t,n){this.pendingActions.set(this.getActionKey(e,t),structuredClone(n))}async deletePendingTransaction(e,t){this.pendingActions.delete(this.getActionKey(e,t))}async*listPendingTransactions(e){let t=`${e}:`;for(let[n]of Array.from(this.pendingActions.entries()))n.startsWith(t)&&(yield n.substring(t.length))}async getTransaction(e,t){return this.actions.get(this.getActionKey(e,t))}async saveTransaction(e,t,n){this.actions.set(this.getActionKey(e,t),n)}async getMaterializedBlock(e,t){let n=this.materializedBlocks.get(this.getActionKey(e,t));return n?structuredClone(n):void 0}async saveMaterializedBlock(e,t,n){let s=this.getActionKey(e,t);n?this.materializedBlocks.set(s,structuredClone(n)):this.materializedBlocks.delete(s)}async promotePendingTransaction(e,t){let n=this.getActionKey(e,t),s=this.pendingActions.get(n);s&&(this.actions.set(n,s),this.pendingActions.delete(n))}};var yl=class{createBlockStorage;validatePend;constructor(e,t){this.createBlockStorage=e,this.validatePend=t?.validatePend}async get({blockIds:e,context:t},n){let s=Array.from(new Set(e)),o=await Promise.all(s.map(async i=>{let a=this.createBlockStorage(i);if(t){let u=await a.getLatest(),d=u?t.committed.filter(p=>p.rev>u.rev):t.committed;for(let{actionId:p,rev:f}of d.sort((h,m)=>h.rev-m.rev))await a.getPendingTransaction(p)&&await this.internalCommit(i,p,f,a)}let c=await a.getBlock(t?.rev);if(!c)return[i,{state:{}}];if(t?.actionId!==void 0){let u=await a.getPendingTransaction(t.actionId);if(!u)throw new Error(`Pending action ${t.actionId} not found`);let d=cl(c.block,u);return[i,{block:d,state:{latest:await a.getLatest(),pendings:[t.actionId]}}]}let l=await uc(a.listPendingTransactions());return[i,{block:c.block,state:{latest:await a.getLatest(),pendings:l}}]}));return Object.fromEntries(o)}async pend(e,t){if(this.validatePend&&e.transaction&&e.operationsHash){let i=await this.validatePend(e.transaction,e.operationsHash);if(!i.valid)return{success:!1,reason:i.reason??"Transaction validation failed"}}let n=gs(e.transforms),s=[],o=[];for(let i of n){let a=this.createBlockStorage(i),c=md(e.transforms,i),l=await uc(a.listPendingTransactions());if(s.push(...l.map(u=>({blockId:i,actionId:u}))),e.rev!==void 0||c.insert){let u=await a.getLatest();if(u&&u.rev>=(e.rev??0)){let d=await uc(a.listRevisions(e.rev??0,u.rev));for(let p of d){let f=await a.getTransaction(p.actionId);if(!f)throw new Error(`Missing action ${p.actionId} for block ${i}`);o.push({actionId:p.actionId,rev:p.rev,transforms:j2(f,i)})}}}}if(o.length)return{success:!1,missing:o};if(s.length>0){if(e.policy==="f")return{success:!1,pending:s};if(e.policy==="r")return{success:!1,pending:await Promise.all(s.map(async i=>{let a=this.createBlockStorage(i.blockId);return{blockId:i.blockId,actionId:i.actionId,transform:await a.getPendingTransaction(i.actionId)??await a.getTransaction(i.actionId)}}))}}return await Promise.all(n.map(i=>{let a=this.createBlockStorage(i),c=md(e.transforms,i);return a.savePendingTransaction(e.actionId,c)})),{success:!0,pending:s,blockIds:n}}async cancel(e,t){await Promise.all(e.blockIds.map(n=>this.createBlockStorage(n).deletePendingTransaction(e.actionId)))}async commit(e,t){let n=Array.from(new Set(e.blockIds)).sort(),s=[];try{for(let c of n){let l=`StorageRepo.commit:${c}`,u=await no.acquire(l);s.push(u)}let o=e.blockIds.map(c=>({blockId:c,storage:this.createBlockStorage(c)})),i=[];for(let{blockId:c,storage:l}of o){let u=await l.getLatest();if(u&&u.rev>=e.rev){let d=[];for await(let p of l.listRevisions(e.rev,u.rev)){let f=await l.getTransaction(p.actionId);if(!f)throw new Error(`Missing action ${p.actionId} for block ${c}`);d.push({actionId:p.actionId,rev:p.rev,transform:f})}i.push({blockId:c,transforms:d})}}if(i.length)return{success:!1,missing:b9(i)};let a=[];for(let{blockId:c,storage:l}of o)await l.getPendingTransaction(e.actionId)||a.push({blockId:c,actionId:e.actionId});if(a.length)throw new Error(`Pending action ${e.actionId} not found for block(s): ${a.map(c=>c.blockId).join(", ")}`);for(let{blockId:c,storage:l}of o)try{await this.internalCommit(c,e.actionId,e.rev,l)}catch(u){return{success:!1,reason:u instanceof Error?u.message:"Unknown error during commit"}}}finally{s.reverse().forEach(o=>o())}return{success:!0}}async internalCommit(e,t,n,s){let o=await s.getPendingTransaction(t);if(!o)throw new Error(`Consistency Error: Pending action ${t} disappeared for block ${e} within critical section.`);let i=await s.getLatest(),a=i?(await s.getBlock(i.rev))?.block:void 0,c=cl(a,o);c&&await s.saveMaterializedBlock(t,c),await s.saveRevision(n,t),await s.promotePendingTransaction(t),await s.setLatest({actionId:t,rev:n})}};function b9(r){let e=r.flatMap(({blockId:n,transforms:s})=>s.map(o=>({blockId:n,transform:o}))),t=_g(e,({transform:n})=>n.actionId);return Object.entries(t).map(([n,s])=>s.reduce((o,{blockId:i,transform:a})=>(Y2(o.transforms,i,a.transform),o),{actionId:n,rev:s[0].transform.rev,transforms:W2()}))}var sn=class{entries;constructor(e){this.entries=e}},bl=class{partitions;nodes;constructor(e,t){this.partitions=e,this.nodes=t}};var Rn=class r{node;index;constructor(e,t){this.node=e,this.index=t}clone(){return new r(this.node,this.index)}},Ui=class r{branches;leafNode;leafIndex;on;version;constructor(e,t,n,s,o){this.branches=e,this.leafNode=t,this.leafIndex=n,this.on=s,this.version=o}isEqual(e){return this.leafNode===e.leafNode&&this.leafIndex===e.leafIndex&&this.on===e.on&&this.version===e.version}clone(){return new r(this.branches.map(e=>e.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var Ir=64,kd=class{keyFromEntry;compare;_root;_version=0;constructor(e=n=>n,t=(n,s)=>n<s?-1:n>s?1:0){this.keyFromEntry=e,this.compare=t,this._root=new sn([])}first(){return this.getFirst(this._root)}last(){return this.getLast(this._root)}find(e){return this.getPath(this._root,e)}get(e){return this.at(this.find(e))}at(e){return this.validatePath(e),e.on?e.leafNode.entries[e.leafIndex]:void 0}*range(e){let t=e.first?this.findFirst(e):e.isAscending?this.first():this.last(),n=e.last?this.findLast(e):e.isAscending?this.last():this.first(),s=this.keyFromEntry(n.leafNode.entries[n.leafIndex]),o=e.isAscending?this.internalAscending(t):this.internalDescending(t),i=e.isAscending?1:-1;for(let a of o){if(!a.on||!n.on||this.compareKeys(this.keyFromEntry(a.leafNode.entries[a.leafIndex]),s)*i>0)break;yield a}}isValid(e){return e.version===this._version}insert(e){Object.freeze(e);let t=this.internalInsert(e);return t.on&&(t.version=++this._version),t}updateAt(e,t){this.validatePath(e),e.on&&Object.freeze(t);let n=this.internalUpdate(e,t);return n[0].on&&(n[0].version=++this._version),n}upsert(e){let t=this.find(this.keyFromEntry(e));return Object.freeze(e),t.on?t.leafNode.entries[t.leafIndex]=e:this.internalInsertAt(t,e),t.version=++this._version,t}merge(e,t){let n=this.keyFromEntry(e),s=this.find(n);if(s.on){let o=this.updateAt(s,t(s.leafNode.entries[s.leafIndex]));return o[0].on&&(o[0].version=++this._version),o}else return this.internalInsertAt(s,Object.freeze(e)),s.on=!0,s.version=++this._version,[s,!1]}deleteAt(e){this.validatePath(e);let t=this.internalDelete(e);return t&&++this._version,t}ascending(e){return this.validatePath(e),this.internalAscending(e.clone())}descending(e){return this.validatePath(e),this.internalDescending(e.clone())}getCount(e){let t=0,n=e?e.path.clone():this.first();if(e?.ascending??!0)for(;n.on;)t+=n.leafNode.entries.length-n.leafIndex,n.leafIndex=n.leafNode.entries.length-1,this.internalNext(n);else for(;n.on;)t+=n.leafIndex+1,n.leafIndex=0,this.internalPrior(n);return t}next(e){let t=e.clone();return this.moveNext(t),t}moveNext(e){this.validatePath(e),this.internalNext(e)}prior(e){let t=e.clone();return this.movePrior(t),t}movePrior(e){this.validatePath(e),this.internalPrior(e)}compareKeys(e,t){let n=this.compare(e,t);if(n!==0&&n===this.compare(t,e))throw new Error("Inconsistent comparison function for given values");return n}*internalAscending(e){for(this.validatePath(e);e.on;)yield e,this.moveNext(e)}*internalDescending(e){for(this.validatePath(e);e.on;)yield e,this.movePrior(e)}findFirst(e){let t=this.find(e.first.key);return(!t.on||e.first&&!e.first.inclusive)&&(e.isAscending?this.internalNext(t):this.internalPrior(t)),t}findLast(e){let t=this.find(e.last.key);return(!t.on||e.last&&!e.last.inclusive)&&(e.isAscending?this.internalPrior(t):this.internalNext(t)),t}getPath(e,t){if(e instanceof sn){let n=e,[s,o]=this.indexOfEntry(n.entries,t);return new Ui([],n,o,s,this._version)}else{let n=e,s=this.indexOfKey(n.partitions,t),o=this.getPath(n.nodes[s],t);return o.branches.unshift(new Rn(n,s)),o}}indexOfEntry(e,t){let n=0,s=e.length-1,o=0,i=-1;for(;n<=s;){if(o=n+s>>>1,i=this.compareKeys(t,this.keyFromEntry(e[o])),i===0)return[!0,o];i<0?s=o-1:n=o+1}return[!1,n]}indexOfKey(e,t){let n=0,s=e.length-1,o=0,i=-1;for(;n<=s;){if(o=n+s>>>1,i=this.compareKeys(t,e[o]),i===0)return o+1;i<0?s=o-1:n=o+1}return n}internalNext(e){if(e.on)if(e.leafIndex>=e.leafNode.entries.length-1){let t=0,n=!1,s=e.branches.length-1;for(;t<=s&&!n;){let o=e.branches[s-t];o.index===o.node.partitions.length?++t:n=!0}if(!n)e.leafIndex=e.leafNode.entries.length,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);++o.index,this.moveToFirst(o.node.nodes[o.index],e)}}else++e.leafIndex,e.on=!0;else if(e.on=e.branches.every(t=>t.index>=0&&t.index<t.node.nodes.length)&&e.leafIndex>=0&&e.leafIndex<e.leafNode.entries.length,e.on)return}internalPrior(e){if(this.validatePath(e),e.leafIndex<=0){let t=0,n=!1,s=e.branches.length-1;for(;t<=s&&!n;)e.branches[s-t].index===0?++t:n=!0;if(!n)e.leafIndex=0,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);--o.index,this.moveToLast(o.node.nodes[o.index],e)}}else--e.leafIndex,e.on=!0}internalUpdate(e,t){if(e.on){let n=this.keyFromEntry(e.leafNode.entries[e.leafIndex]),s=this.keyFromEntry(t);if(this.compareKeys(n,s)!==0){let o=this.internalInsert(t);return o.on&&(this.internalDelete(this.find(n)),o=this.find(s)),[o,!1]}else e.leafNode.entries[e.leafIndex]=t}return[e,!0]}internalDelete(e){if(e.on){if(e.leafNode.entries.splice(e.leafIndex,1),e.branches.length>0){if(e.leafIndex===0){let n=e.branches.at(-1);this.updatePartition(n.index,e,e.branches.length-1,this.keyFromEntry(e.leafNode.entries[e.leafIndex]))}let t=this.rebalanceLeaf(e);t&&(this._root=t)}return e.on=!1,!0}else return!1}internalInsert(e){let t=this.find(this.keyFromEntry(e));return t.on?(t.on=!1,t):(this.internalInsertAt(t,e),t.on=!0,t)}internalInsertAt(e,t){let n=this.leafInsert(e,t),s=e.branches.length-1;for(;n&&s>=0;)n=this.branchInsert(e,s,n),--s;if(n){let o=new bl([n.key],[this._root,n.right]);this._root=o,e.branches.unshift(new Rn(o,n.indexDelta))}}moveToFirst(e,t){if(e instanceof sn){let n=e;t.leafNode=n,t.leafIndex=0,t.on=n.entries.length>0}else t.branches.push(new Rn(e,0)),this.moveToFirst(e.nodes[0],t)}moveToLast(e,t){if(e instanceof sn){let n=e,s=n.entries.length;t.leafNode=n,t.on=s>0,t.leafIndex=s>0?s-1:0}else{let n=e,s=new Rn(n,n.partitions.length);t.branches.push(s),this.moveToLast(n.nodes[s.index],t)}}getFirst(e){if(e instanceof sn){let t=e;return new Ui([],t,0,t.entries.length>0,this._version)}else{let t=e,n=this.getFirst(t.nodes[0]);return n.branches.unshift(new Rn(t,0)),n}}getLast(e){if(e instanceof sn){let t=e,n=t.entries.length;return new Ui([],t,n>0?n-1:0,n>0,this._version)}else{let t=e,n=t.nodes.length-1,s=this.getLast(t.nodes[n]);return s.branches.unshift(new Rn(t,n)),s}}leafInsert(e,t){let{leafNode:n,leafIndex:s}=e;if(n.entries.length<Ir){n.entries.splice(s,0,t);return}let o=n.entries.length+1>>>1,i=n.entries.splice(o),a=new sn(i),c=s<o?0:1;return c?(e.leafNode=a,e.leafIndex-=n.entries.length,a.entries.splice(e.leafIndex,0,t)):n.entries.splice(s,0,t),new Ld(this.keyFromEntry(i[0]),a,c)}branchInsert(e,t,n){let s=e.branches[t],{index:o,node:i}=s;if(s.index+=n.indexDelta,i.partitions.splice(o,0,n.key),i.nodes.splice(o+1,0,n.right),i.nodes.length<=Ir)return;let a=i.nodes.length>>>1,c=i.partitions.splice(a),l=i.partitions.pop(),u=i.nodes.splice(a),d=new bl(c,u),p=s.index<a?0:1;return p&&(s.index-=a,s.node=d),new Ld(l,d,p)}rebalanceLeaf(e){if(e.leafNode.entries.length>=Ir>>>1)return;let t=e.leafNode,n=e.branches.at(-1),s=e.branches.length-1,o=n.index,i=n.node,a=i.nodes[o+1];if(a&&a.entries.length>Ir>>>1){let l=a.entries.shift();t.entries.push(l),this.updatePartition(o+1,e,s,this.keyFromEntry(a.entries[0]));return}let c=i.nodes[o-1];if(c&&c.entries.length>Ir>>>1){let l=c.entries.pop();t.entries.unshift(l),this.updatePartition(o,e,s,this.keyFromEntry(l)),e.leafIndex+=1;return}if(a&&a.entries.length+t.entries.length<=Ir)return t.entries.push(...a.entries),i.partitions.splice(o,1),i.nodes.splice(o+1,1),o===0&&this.updatePartition(o,e,s,this.keyFromEntry(t.entries[0])),this.rebalanceBranch(e,s);if(c&&c.entries.length+t.entries.length<=Ir)return e.leafNode=c,e.leafIndex+=c.entries.length,c.entries.push(...t.entries),i.partitions.splice(o-1,1),i.nodes.splice(o,1),this.rebalanceBranch(e,s)}rebalanceBranch(e,t){let n=e.branches[t],s=n.node;if(t===0&&s.partitions.length===0)return e.branches[t+1]?.node??e.leafNode;if(t===0||s.nodes.length>=Ir<<1)return;let o=e.branches.at(t-1),i=o.index,a=o.node,c=a.nodes[i+1];if(c&&c.nodes.length>Ir>>>1){s.partitions.push(a.partitions[i]);let u=c.nodes.shift();s.nodes.push(u);let d=c.partitions.shift();this.updatePartition(i+1,e,t-1,d);return}let l=a.nodes[i-1];if(l&&l.nodes.length>Ir>>>1){s.partitions.unshift(a.partitions[i-1]);let u=l.nodes.pop();s.nodes.unshift(u);let d=l.partitions.pop();n.index+=1,this.updatePartition(i,e,t-1,d);return}if(c&&c.nodes.length+s.nodes.length<=Ir){let u=a.partitions.splice(i,1)[0];return s.partitions.push(u),s.partitions.push(...c.partitions),s.nodes.push(...c.nodes),a.nodes.splice(i+1,1),i===0&&a.partitions.length>0&&this.updatePartition(i,e,t-1,a.partitions[0]),this.rebalanceBranch(e,t-1)}if(l&&l.nodes.length+s.nodes.length<=Ir){n.node=l,n.index+=l.nodes.length;let u=a.partitions.splice(i-1,1)[0];return l.partitions.push(u),l.partitions.push(...s.partitions),l.nodes.push(...s.nodes),a.nodes.splice(i,1),this.rebalanceBranch(e,t-1)}}updatePartition(e,t,n,s){let o=t.branches[n];e>0?o.node.partitions[e-1]=s:n!==0&&this.updatePartition(t.branches[n-1].index,t,n-1,s)}validatePath(e){if(!this.isValid(e))throw new Error("Path is invalid due to mutation of the tree")}},Ld=class{key;right;indexDelta;constructor(e,t,n){this.key=e,this.right=t,this.indexDelta=n}};function wl(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function Md(r){return`${wl(r.coord)}|${r.id}`}var Od=class{byKey;byId;constructor(){this.byKey=new kd(e=>Md(e)),this.byId=new Map}insert(e){let t=Md(e);this.byKey.insert(e),this.byId.set(e.id,t)}upsert(e,t){let n=Date.now(),s=this.byId.get(e);if(s){let i=this.byKey.find(s);i.on&&this.byKey.deleteAt(i),this.byId.delete(e)}let o={id:e,coord:t,relevance:0,lastAccess:n,state:"disconnected",accessCount:0,successCount:0,failureCount:0,avgLatencyMs:0};return this.insert(o),o}update(e,t){let n=this.byId.get(e);if(!n)return;let s=this.byKey.find(n),o=this.byKey.at(s);if(!o)return;let i={...o,...t};this.byKey.updateAt(s,i),Md(o)!==Md(i)&&(this.byKey.deleteAt(s),this.insert(i))}getById(e){let t=this.byId.get(e);if(!t)return;let n=this.byKey.find(t);return n.on?this.byKey.at(n):void 0}remove(e){let t=this.byId.get(e);if(!t)return;let n=this.byKey.find(t);n.on&&this.byKey.deleteAt(n),this.byId.delete(e)}list(){let e=[];for(let t of this.byKey.ascending(this.byKey.first()))e.push(this.byKey.at(t));return e}size(){return this.byId.size}setState(e,t){this.update(e,{state:t})}protectedIdsAround(e,t){let n=new Set;for(let s of this.neighborsRight(e,t))n.add(s);for(let s of this.neighborsLeft(e,t))n.add(s);return n}ceilPath(e){let t=`${e}|\0`,n=this.byKey.find(t);return n.on||(n=this.byKey.next(n)),n}floorPath(e){let t=`${e}|\uFFFF`,n=this.byKey.find(t);return n.on||(n=this.byKey.prior(n)),n}successorOfCoord(e){let t=wl(e),n=this.ceilPath(t);if(n.on)return this.byKey.at(n);let s=this.byKey.first();return s.on?this.byKey.at(s):void 0}predecessorOfCoord(e){let t=wl(e),n=this.floorPath(t);if(n.on)return this.byKey.at(n);let s=this.byKey.last();return s.on?this.byKey.at(s):void 0}neighborsRight(e,t){let n=[],s=wl(e),o=this.ceilPath(s);o=o.on?o:this.byKey.first();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.first(),!o.on));)n.push(this.byKey.at(o).id),o=this.byKey.next(o),i++;return Array.from(new Set(n))}neighborsLeft(e,t){let n=[],s=wl(e),o=this.floorPath(s);o=o.on?o:this.byKey.last();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.last(),!o.on));)n.push(this.byKey.at(o).id),o=this.byKey.prior(o),i++;return Array.from(new Set(n))}};var ny={};z(ny,{sha256:()=>qi,sha512:()=>U9});var ry=ae(te("crypto"),1);var qae=new Uint8Array(0);function KS(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Ar(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function FS(r){return new TextEncoder().encode(r)}function zS(r){return new TextDecoder().decode(r)}var w9=VS,HS=128,x9=127,v9=~x9,E9=Math.pow(2,31);function VS(r,e,t){e=e||[],t=t||0;for(var n=t;r>=E9;)e[t++]=r&255|HS,r/=128;for(;r&v9;)e[t++]=r&255|HS,r>>>=7;return e[t]=r|0,VS.bytes=t-n+1,e}var S9=Zg,I9=128,qS=127;function Zg(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Zg.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&qS)<<s:(i&qS)*Math.pow(2,s),s+=7}while(i>=I9);return Zg.bytes=o-n,t}var A9=Math.pow(2,7),C9=Math.pow(2,14),T9=Math.pow(2,21),_9=Math.pow(2,28),P9=Math.pow(2,35),D9=Math.pow(2,42),k9=Math.pow(2,49),L9=Math.pow(2,56),M9=Math.pow(2,63),O9=function(r){return r<A9?1:r<C9?2:r<T9?3:r<_9?4:r<P9?5:r<D9?6:r<k9?7:r<L9?8:r<M9?9:10},R9={encode:w9,decode:S9,encodingLength:O9},N9=R9,xl=N9;function vl(r,e=0){return[xl.decode(r,e),xl.decode.bytes]}function Ki(r,e,t=0){return xl.encode(r,e,t),e}function Fi(r){return xl.encodingLength(r)}function $i(r,e){let t=e.byteLength,n=Fi(r),s=n+Fi(t),o=new Uint8Array(s+t);return Ki(r,o,0),Ki(t,o,n),o.set(e,s),new zi(r,t,e,o)}function El(r){let e=Ar(r),[t,n]=vl(e),[s,o]=vl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new zi(t,s,i,e)}function GS(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&KS(r.bytes,t.bytes)}}var zi=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var B9=20;function ty({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new ey(r,e,t,n,s)}var ey=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??B9,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?WS(n,this.code,t?.truncate):n.then(s=>WS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function WS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return $i(e,r)}var qi=ty({name:"sha2-256",code:18,encode:r=>Ar(ry.default.createHash("sha256").update(r).digest())}),U9=ty({name:"sha2-512",code:19,encode:r=>Ar(ry.default.createHash("sha512").update(r).digest())});ie();re();async function qe(r){let e=r.toMultihash().bytes;return await qi.encode(e)}async function ir(r){return await qi.encode(r)}function YS(r){return T(r,"base64url")}function XS(r="default"){let e=`/optimystic/${r}/fret/1.0.0`;return{PROTOCOL_NEIGHBORS:`${e}/neighbors`,PROTOCOL_NEIGHBORS_ANNOUNCE:`${e}/neighbors/announce`,PROTOCOL_MAYBE_ACT:`${e}/maybeAct`,PROTOCOL_LEAVE:`${e}/leave`,PROTOCOL_PING:`${e}/ping`}}var sy="/optimystic/default/fret/1.0.0/neighbors",oy="/optimystic/default/fret/1.0.0/neighbors/announce",iy="/optimystic/default/fret/1.0.0/maybeAct",ay="/optimystic/default/fret/1.0.0/leave",cy="/optimystic/default/fret/1.0.0/ping";async function Cr(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)}async function on(r){if(r.byteLength===0)throw new Error("empty response");let e=0,t=r.byteLength;for(;e<t&&(r[e]===0||r[e]===9||r[e]===10||r[e]===13||r[e]===32);)e++;for(;t>e&&(r[t-1]===0||r[t-1]===9||r[t-1]===10||r[t-1]===13||r[t-1]===32);)t--;if(t<=e)throw new Error("whitespace response");let n=new TextDecoder().decode(r.subarray(e,t));return JSON.parse(n)}var bs=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Nd=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Bd=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var fy={};z(fy,{base58btc:()=>Ge,base58flickr:()=>V9});function K9(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var F9=K9,z9=F9,QS=z9;var ly=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},uy=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 JS(this,e)}},hy=class{decoders;constructor(e){this.decoders=e}or(e){return JS(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function JS(r,e){return new hy({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var dy=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new ly(e,t,n),this.decoder=new uy(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Vi({name:r,prefix:e,encode:t,decode:n}){return new dy(r,e,t,n)}function ws({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=QS(t,r);return Vi({prefix:e,name:r,encode:n,decode:o=>Ar(s(o))})}function $9(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function H9(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function q9(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ve({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=q9(n);return Vi({prefix:e,name:r,encode(o){return H9(o,n,t)},decode(o){return $9(o,s,t,r)}})}var Ge=ws({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),V9=ws({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var py={};z(py,{base32:()=>xs,base32hex:()=>Y9,base32hexpad:()=>Q9,base32hexpadupper:()=>J9,base32hexupper:()=>X9,base32pad:()=>W9,base32padupper:()=>j9,base32upper:()=>G9,base32z:()=>Z9});var xs=Ve({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),G9=Ve({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),W9=Ve({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),j9=Ve({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Y9=Ve({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),X9=Ve({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Q9=Ve({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),J9=Ve({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Z9=Ve({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var my={};z(my,{base36:()=>Sl,base36upper:()=>eN});var Sl=ws({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),eN=ws({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});function ZS(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return rN(t,gy(r),e??Ge.encoder);default:return nN(t,gy(r),e??xs.encoder)}}var eI=new WeakMap;function gy(r){let e=eI.get(r);if(e==null){let t=new Map;return eI.set(r,t),t}return e}var ot=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Il)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==sN)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=$i(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&GS(e.multihash,n.multihash)}toString(e){return ZS(this,e)}toJSON(){return{"/":ZS(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??tI(n,s,o.bytes))}else if(t[oN]===!0){let{version:n,multihash:s,code:o}=t,i=El(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Il)throw new Error(`Version 0 CID must use dag-pb (code: ${Il}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=tI(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Il,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Ar(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new zi(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=vl(e.subarray(t));return t+=p,d},s=n(),o=Il;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=tN(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gy(o).set(n,e),o}};function tN(r,e){switch(r[0]){case"Q":{let t=e??Ge;return[Ge.prefix,t.decode(`${Ge.prefix}${r}`)]}case Ge.prefix:{let t=e??Ge;return[Ge.prefix,t.decode(r)]}case xs.prefix:{let t=e??xs;return[xs.prefix,t.decode(r)]}case Sl.prefix:{let t=e??Sl;return[Sl.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function rN(r,e,t){let{prefix:n}=t;if(n!==Ge.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function nN(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Il=112,sN=18;function tI(r,e,t){let n=Fi(r),s=n+Fi(e),o=new Uint8Array(s+t.byteLength);return Ki(r,o,0),Ki(e,o,n),o.set(t,s),o}var oN=Symbol.for("@ipld/js-cid/CID");var yy={};z(yy,{identity:()=>Ur});var rI=0,iN="identity",nI=Ar;function aN(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return $i(rI,nI(r))}var Ur={code:rI,name:iN,encode:nI,digest:aN};Ne();Be();re();ie();Be();var cN=parseInt("11111",2),by=parseInt("10000000",2),lN=parseInt("01111111",2),sI={0:Al,1:Al,2:uN,3:fN,4:pN,5:dN,6:hN,16:Al,22:Al,48:Al};function wy(r,e={offset:0}){let t=r[e.offset]&cN;if(e.offset++,sI[t]!=null)return sI[t](r,e);throw new Error("No decoder for tag "+t)}function Cl(r,e){let t=0;if((r[e.offset]&by)===by){let n=r[e.offset]&lN,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Al(r,e){Cl(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=wy(r,e);if(n===null)break;t.push(n)}return t}function uN(r,e){let t=Cl(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function hN(r,e){let t=Cl(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function dN(r,e){return e.offset++,null}function fN(r,e){let t=Cl(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function pN(r,e){let t=Cl(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function mN(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new U;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function xy(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=mN(r.byteLength);return new U(Uint8Array.from([e.byteLength|by]),e)}function oI(r){let e=new U,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new U(Uint8Array.from([2]),xy(e),e)}function iI(r){let e=Uint8Array.from([0]),t=new U(e,r);return new U(Uint8Array.from([3]),xy(t),t)}function Ud(r,e=48){let t=new U;for(let n of r)t.append(n);return new U(Uint8Array.from([e]),xy(t),t)}async function aI(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var gN=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),yN=Uint8Array.from([6,5,43,129,4,0,34]),bN=Uint8Array.from([6,5,43,129,4,0,35]),wN={ext:!0,kty:"EC",crv:"P-256"},xN={ext:!0,kty:"EC",crv:"P-384"},vN={ext:!0,kty:"EC",crv:"P-521"},vy=32,Ey=48,Sy=66;function cI(r){let e=wy(r);return lI(e)}function lI(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===vy*2+1)return n=T(e.subarray(t,t+vy),"base64url"),s=T(e.subarray(t+vy),"base64url"),new Gi({...wN,key_ops:["verify"],x:n,y:s});if(e.byteLength===Ey*2+1)return n=T(e.subarray(t,t+Ey),"base64url"),s=T(e.subarray(t+Ey),"base64url"),new Gi({...xN,key_ops:["verify"],x:n,y:s});if(e.byteLength===Sy*2+1)return n=T(e.subarray(t,t+Sy),"base64url"),s=T(e.subarray(t+Sy),"base64url"),new Gi({...vN,key_ops:["verify"],x:n,y:s});throw new bs(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function uI(r){return Ud([oI(Uint8Array.from([1])),Ud([EN(r.crv)],160),Ud([iI(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function EN(r){if(r==="P-256")return gN;if(r==="P-384")return yN;if(r==="P-521")return bN;throw new bs(`Invalid curve ${r}`)}var Gi=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=uI(this.jwk)),this._raw}toMultihash(){return Ur.digest(Wi(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async verify(e,t,n){return aI(this.jwk,t,e,n)}};var Kd=ae(te("crypto"),1);bt();re();ie();var zce=Kd.default.generateKeyPairSync,Tl=32;var SN=64;function hI(r,e,t){if(r.byteLength!==Tl)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==SN)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=Kd.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:T(r,"base64url"),kty:"OKP"}});return Kd.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}Ne();bt();re();function fI(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Fd=class{type="Ed25519";raw;constructor(e){this.raw=Iy(e,Tl)}toMultihash(){return Ur.digest(Wi(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=hI(this.raw,t,e);return fI(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function pI(r){return r=Iy(r,Tl),new Fd(r)}function Iy(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new bs(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}wr();var ar;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ar||(ar={}));var Ay;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ay||(Ay={}));(function(r){r.codec=()=>sr(Ay)})(ar||(ar={}));var _l;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ar.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ar.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(_l||(_l={}));var Cy;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ar.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ar.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Cy||(Cy={}));var mI=ae(te("node:crypto"),1);eo();var zd=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function gI(r,e,t,n){n?.signal?.throwIfAborted();let s=mI.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return st.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new zd(String(i))}}eo();Ne();var $d=class{type="secp256k1";raw;_key;constructor(e){this._key=bI(e),this.raw=yI(this._key)}toMultihash(){return Ur.digest(Wi(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return gI(this._key,t,e,n)}};function wI(r){return new $d(r)}function yI(r){return st.Point.fromBytes(r).toBytes()}function bI(r){try{return st.Point.fromBytes(r),r}catch(e){throw new Nd(String(e))}}function xI(r){let{Type:e,Data:t}=_l.decode(r.digest),n=t??new Uint8Array;switch(e){case ar.Ed25519:return pI(n);case ar.secp256k1:return wI(n);case ar.ECDSA:return cI(n);default:throw new Bd}}function Wi(r){return _l.encode({Type:ar[r.type],Data:r.raw})}var Ty=Symbol.for("@libp2p/peer-id");var Hd=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var qd=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Vd=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};ie();Ne();re();ie();var vI=Symbol.for("nodejs.util.inspect.custom"),CN=114,Pl=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ty]=!0;toString(){return this.string==null&&(this.string=Ge.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ot.createV1(CN,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[vI](){return`PeerId(${this.toString()})`}},Gd=class extends Pl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Wd=class extends Pl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},jd=class extends Pl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},TN=2336,Dl=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ur.digest(D(this.url))}[vI](){return`PeerId(${this.url})`}[Ty]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ot.createV1(TN,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=T(e)),e.toString()===this.toString())}};var _N=114,EI=2336;function Oe(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=El(Ge.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return PN(ot.parse(r));if(e==null)throw new Hd('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=El(e.decode(r))}return SI(t)}function SI(r){if(kN(r))return new Gd({multihash:r});if(DN(r))try{let e=xI(r);if(e.type==="Ed25519")return new Wd({multihash:r,publicKey:e});if(e.type==="secp256k1")return new jd({multihash:r,publicKey:e})}catch{let t=T(r.digest);return new Dl(new URL(t))}throw new Vd("Supplied PeerID Multihash is invalid")}function PN(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==_N&&r.code!==EI)throw new qd("Supplied PeerID CID is invalid");if(r.code===EI){let e=T(r.multihash.digest);return new Dl(new URL(e))}return SI(r.multihash)}function DN(r){return r.code===Ur.code}function kN(r){return r.code===qi.code}var II=ae(Wg(),1),LN="optimystic:fret";function vs(r){return(0,II.default)(`${LN}:${r}`)}var _y=vs("rpc:neighbors");function AI(r,e,t,n={PROTOCOL_NEIGHBORS:sy,PROTOCOL_NEIGHBORS_ANNOUNCE:oy}){r.handle(n.PROTOCOL_NEIGHBORS,async({stream:s})=>{try{let o=await e();await s.sink((async function*(){yield await Cr(o)})());try{s.close?.()}catch{}}catch(o){console.error("neighbors handler error:",o)}}),t&&r.handle(n.PROTOCOL_NEIGHBORS_ANNOUNCE,async({stream:s})=>{try{let o=await TI(s),i=await on(o);t(i.from,i),await s.sink((async function*(){yield await Cr({ok:!0})})());try{s.close?.()}catch{}}catch(o){console.error("neighbors announce handler error:",o)}})}async function CI(r,e,t=sy){let n=Oe(e),s=r.getConnections?.(n)??[];if(!Array.isArray(s)||s.length===0||typeof s[0]?.newStream!="function")return{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""};let o;try{o=await s[0].newStream([t]);let i=await TI(o);return await on(i)}catch(i){return _y("fetchNeighbors decode failed for %s - %o",e,i),{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""}}finally{if(o)try{await o.close()}catch{}}}async function Py(r,e,t,n=oy){let s=Oe(e),o=r.getConnections?.(s)??[];if(!Array.isArray(o)||o.length===0||typeof o[0]?.newStream!="function")return;let i;try{i=await o[0].newStream([n]),await i.sink((async function*(){yield await Cr(t)})())}catch(a){_y("announceNeighbors failed to %s - %o",e,a)}finally{if(i)try{await i.close()}catch{}}}function MN(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")try{return e.subarray(0)}catch(t){_y("toBytes subarray failed - %o",t)}if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unsupported chunk type in neighbors read")}async function TI(r){let e=[];for await(let o of r.source)e.push(MN(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}function _I(r,e,t=iy){r.handle(t,async({stream:n})=>{try{let s=await DI(n),o=await on(s),i=await e(o);await n.sink((async function*(){yield await Cr(i)})())}catch(s){console.error("maybeAct handler error:",s)}})}async function PI(r,e,t,n=iy){let s=Oe(e),o=r.getConnections?.(s)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([n]):i=await r.dialProtocol(s,[n]),await i.sink((async function*(){yield await Cr(t)})());let a=await DI(i);return await on(a)}finally{if(i)try{await i.close()}catch{}}}function ON(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")return e.subarray(0);throw new Error("Unsupported chunk type in maybeAct read")}async function DI(r){let e=[];for await(let o of r.source)e.push(ON(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}function kI(r,e,t=ay){r.handle(t,async({stream:n})=>{try{let s=await NN(n),o=await on(s);await e(o),await n.sink((async function*(){yield await Cr({ok:!0})})())}catch(s){console.error("leave handler error:",s)}})}async function LI(r,e,t,n=ay){let s=Oe(e),o=r.getConnections?.(s)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([n]):i=await r.dialProtocol(s,[n]),await i.sink((async function*(){yield await Cr(t)})())}finally{if(i)try{await i.close()}catch{}}}function RN(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")return e.subarray(0);throw new Error("Unsupported chunk type in leave read")}async function NN(r){let e=[];for await(let o of r.source)e.push(RN(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}var Dy=vs("rpc:ping");function MI(r,e=cy,t){r.handle(e,async({stream:n})=>{let s={ok:!0,ts:Date.now()};if(t)try{let o=await t();o.size_estimate!==void 0&&(s.size_estimate=o.size_estimate,s.confidence=o.confidence)}catch(o){Dy("getSizeEstimate failed - %o",o)}await n.sink((async function*(){yield await Cr(s)})())})}async function kl(r,e,t=cy){let n=Date.now(),s=Oe(e),o;try{try{let l=r.getConnections?.(s)??[];if(Array.isArray(l)&&l.length>0&&typeof l[0]?.newStream=="function")o=await l[0].newStream([t]);else{let u=await r.dialProtocol(s,[t]);o=u.stream??u}}catch{let u=await r.dialProtocol(s,[t]);o=u.stream??u}let i=null;for await(let l of o.source)if(l!=null)try{if(l instanceof Uint8Array){i=l;break}if(typeof l.subarray=="function"){let u=l.subarray();if(u instanceof Uint8Array){i=u;break}if(ArrayBuffer.isView(u)){i=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);break}}if(ArrayBuffer.isView(l)){i=new Uint8Array(l.buffer,l.byteOffset,l.byteLength);break}}catch(u){Dy("sendPing chunk handling failed - %o",u)}let a=Math.max(0,Date.now()-n);if(!i||i.length===0)return{ok:!1,rttMs:a};let c=new TextDecoder().decode(i).trim();if(!c||c[0]!=="{"||!c.endsWith("}"))return{ok:!1,rttMs:a};try{let l=await on(i);return{ok:!!l.ok,rttMs:a,size_estimate:l.size_estimate,confidence:l.confidence}}catch(l){return Dy("sendPing decode failed - %o",l),{ok:!1,rttMs:a}}}finally{if(o)try{await o.close()}catch{}}}re();function BN(r){let e=0n;for(let t=0;t<r.length;t++)e=e<<8n|BigInt(r[t]);return e}function UN(r){if(r.length===0)return 0n;let e=[...r].sort((n,s)=>n<s?-1:n>s?1:0),t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2n:e[t]}function Yd(r,e){let t=r.list(),n=t.length;if(n===0)return{n:0,confidence:0};if(n===1)return{n:1,confidence:.2};let s=1n<<256n,o=t.map(g=>BN(g.coord)).sort((g,y)=>g<y?-1:g>y?1:0),i=[];for(let g=1;g<o.length;g++)i.push(o[g]-o[g-1]);i.push(o[0]+s-o[o.length-1]);let a=UN(i),c=a>0n?a:s/BigInt(Math.max(1,n)),l=s/c,u=Math.max(1,Math.min(Number(l),1e9)),d=i[0],p=i[0];for(let g of i)g<d&&(d=g),g>p&&(p=g);let f=Math.min(1,n/Math.max(1,e*2)),h=p===0n?0:Number(d)/Number(p),m=Math.max(.05,Math.min(1,.5*f+.5*h));return{n:u,confidence:m}}var ji=class{capacity;refillPerSec;tokens;last;constructor(e,t){this.capacity=e,this.refillPerSec=t,this.tokens=e,this.last=Date.now()}tryTake(e=1){return this.refill(),this.tokens>=e?(this.tokens-=e,!0):!1}retryAfterMs(e=1){if(this.refill(),this.tokens>=e)return 0;let n=(e-this.tokens)/this.refillPerSec;return Math.ceil(n*1e3)}refill(){let e=Date.now(),t=(e-this.last)/1e3;t>0&&(this.tokens=Math.min(this.capacity,this.tokens+t*this.refillPerSec),this.last=e)}};ie();var vt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Nn=class extends Error{static name="ValidationError";name="ValidationError"},Ll=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Xd=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};Ne();re();ie();gr();bt();re();ie();var fe=te("node:net");var Ly={};z(Ly,{base64:()=>KN,base64pad:()=>FN,base64url:()=>ky,base64urlpad:()=>zN});var KN=Ve({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),FN=Ve({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ky=Ve({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zN=Ve({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var My={};z(My,{base10:()=>$N});var $N=ws({prefix:"9",name:"base10",alphabet:"0123456789"});var Oy={};z(Oy,{base16:()=>HN,base16upper:()=>qN});var HN=Ve({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qN=Ve({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ry={};z(Ry,{base2:()=>VN});var VN=Ve({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ny={};z(Ny,{base256emoji:()=>XN});var OI=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}"),GN=OI.reduce((r,e,t)=>(r[t]=e,r),[]),WN=OI.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function jN(r){return r.reduce((e,t)=>(e+=GN[t],e),"")}function YN(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=WN[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var XN=Vi({prefix:"\u{1F680}",name:"base256emoji",encode:jN,decode:YN});var By={};z(By,{base8:()=>QN});var QN=Ve({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Uy={};z(Uy,{identity:()=>JN});var JN=Vi({prefix:"\0",name:"identity",encode:r=>zS(r),decode:r=>FS(r)});var que=new TextEncoder,Vue=new TextDecoder;var RI={...Uy,...Ry,...By,...My,...Oy,...py,...my,...fy,...Ly,...Ny},jue={...ny,...yy};bt();re();ie();function Fy(r){return e=>T(e,r)}function zy(r){return e=>D(e,r)}function Yi(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function co(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function NI(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=co(n);return Ee([t,s],t.length+s.length)}function BI(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=xs.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 s=co(n);return Ee([t,s],t.length+s.length)}function $y(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=T(e,"base32"),s=Yi(t);return`${n}:${s}`}var Hy=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new vt("Invalid byte value in IP address");e[n]=s}),e},UI=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,fe.isIPv4)(t[n]),i;o&&(i=Hy(t[n]),t[n]=T(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,T(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new vt("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},KI=function(r){if(r.byteLength!==4)throw new vt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},FI=function(r){if(r.byteLength!==16)throw new vt("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new vt(`Invalid IPv6 address "${t}"`)}};function zI(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new vt(`Invalid IPv6 address "${r}"`)}}var Ky=Object.values(RI).map(r=>r.decoder),tB=(function(){let r=Ky[0].or(Ky[1]);return Ky.slice(2).forEach(e=>r=r.or(e)),r})();function $I(r){return tB.decode(r)}function HI(r){return e=>r.encoder.encode(e)}function rB(r){if(parseInt(r).toString()!==r)throw new Nn("Value must be an integer")}function nB(r){if(r<0)throw new Nn("Value must be a positive integer, or zero")}function sB(r){return e=>{if(e>r)throw new Nn(`Value must be smaller than or equal to ${r}`)}}function oB(...r){return e=>{for(let t of r)t(e)}}var Ml=oB(rB,nB,sB(65535));var pt=-1,qy=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Xd(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},cr=new qy,RB=[{code:4,name:"ip4",size:32,valueToBytes:Hy,bytesToValue:KI,validate:r=>{if(!(0,fe.isIPv4)(r))throw new Nn(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:273,name:"udp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:33,name:"dccp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:41,name:"ip6",size:128,valueToBytes:UI,bytesToValue:FI,stringToValue:zI,validate:r=>{if(!(0,fe.isIPv6)(r))throw new Nn(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:pt},{code:43,name:"ipcidr",size:8,bytesToValue:Fy("base10"),valueToBytes:zy("base10")},{code:53,name:"dns",size:pt,resolvable:!0},{code:54,name:"dns4",size:pt,resolvable:!0},{code:55,name:"dns6",size:pt,resolvable:!0},{code:56,name:"dnsaddr",size:pt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:co,bytesToValue:Yi,validate:Ml},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:pt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:pt,bytesToValue:Fy("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?zy("base58btc")(r):ot.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:$y,valueToBytes:NI},{code:445,name:"onion3",size:296,bytesToValue:$y,valueToBytes:BI},{code:446,name:"garlic64",size:pt},{code:447,name:"garlic32",size:pt},{code:448,name:"tls"},{code:449,name:"sni",size:pt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:pt,bytesToValue:HI(ky),valueToBytes:$I},{code:480,name:"http"},{code:481,name:"http-path",size:pt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:pt}];RB.forEach(r=>{cr.addProtocol(r)});function qI(r){let e=[],t=0;for(;t<r.length;){let n=jt(r,t),s=cr.getProtocol(n),o=Ae(n),i=NB(s,r,t+o),a=0;i>0&&s.size===pt&&(a=Ae(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,d=r.subarray(u,u+i);l.value=s.bytesToValue?.(d)??T(d)}e.push(l),t+=c}return e}function VI(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=cr.getProtocol(n.code),o=Ae(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,s.size===pt&&(c=Ae(a)));let l=new Uint8Array(o+c+a),u=0;In(n.code,l,u),u+=o,i!=null&&(s.size===pt&&(In(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ee(t,e)}function GI(r){if(r.charAt(0)!=="/")throw new vt('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=cr.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new vt(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new vt(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new vt("Incomplete multiaddr");return e}function WI(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=cr.getProtocol(e.code);if(t==null)throw new vt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function NB(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:jt(e,t)}var BB=Symbol.for("nodejs.util.inspect.custom"),Jy=Symbol.for("@multiformats/multiaddr"),UB=[53,54,55,56],Qy=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function KB(r){if(r==null&&(r="/"),YI(r))return r.getComponents();if(r instanceof Uint8Array)return qI(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),GI(r);if(Array.isArray(r))return r;throw new vt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var tf=class r{[Jy]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=KB(e),t.validate!==!1&&FB(this)}get bytes(){return this.#r==null&&(this.#r=VI(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=WI(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,n,s,o="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(o=`%${l??""}`),UB.includes(a)&&(t="tcp",s=443,n=`${l??""}${o}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",s=parseInt(l??"")),(a===4||a===41)&&(t="tcp",n=`${l??""}${o}`,e=a===41?6:4);if(e==null||t==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:s}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let n=cr.getProtocol(e);return{code:e,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(t==null)return[e];let n=cr.getProtocol(e),s=[e];return t!=null&&s.push(n.valueToBytes?.(t)??D(t)),s})}stringTuples(){return this.#e.map(({code:e,value:t})=>t==null?[e]:[e,t])}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Ll(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:n,value:s})=>{n===421&&e.push([n,s]),n===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?T(Ge.decode(`z${n}`),"base58btc"):T(ot.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(cr.getProtocol(e.code).path)return e.value??null;return null}equals(e){return W(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=jI.get(t.name);if(n==null)throw new Qy(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>Rl(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(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[BB](){return`Multiaddr(${this.toString()})`}};function FB(r){r.getComponents().forEach(e=>{let t=cr.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}var rf=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let p=Number.parseInt(d,e);if(!Number.isNaN(p))return p});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var XI=45,zB=15,Xi=new rf;function QI(r){if(!(r.length>zB))return Xi.new(r).parseWith(()=>Xi.readIPv4Addr())}function JI(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>XI))return Xi.new(r).parseWith(()=>Xi.readIPv6Addr())}function Nl(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>XI)return;let t=Xi.new(r).parseWith(()=>Xi.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function ZI(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function eA(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function Zy(r){switch(r.length){case lo:return r.join(".");case uo:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function tA(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function rA(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var lo=4,uo=16,Uhe=parseInt("0xFFFF",16),$B=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Bl(r,e){e.length===uo&&r.length===lo&&ZI(e,0,11)&&(e=e.slice(12)),e.length===lo&&r.length===uo&&eA(r,$B,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function nA(r,e){if(typeof e=="string"&&(e=Nl(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function e3(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=lo,s=QI(e);if(s==null&&(n=uo,s=JI(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=t3(o,8*n);return{network:Bl(s,i),mask:i}}function t3(r,e){if(e!==8*lo&&e!==8*uo)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var Bn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=e3(e));else{let n=Nl(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=Nl(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=t3(s,8*n.length);this.network=Bl(n,this.mask)}}contains(e){return nA({network:this.network,mask:this.mask},e)}toString(){let e=tA(this.mask),t=e!==-1?String(e):rA(this.mask);return Zy(this.network)+"/"+t}};function sA(r,e){return new Bn(r).contains(e)}re();ie();var jI=new Map;function YI(r){return!!r?.[Jy]}function Rl(r){return new tf(r)}function nf(r,e){let t=Math.max(r.length,e.length),n=new Uint8Array(t);for(let s=0;s<t;s++){let o=r[r.length-1-s]??0,i=e[e.length-1-s]??0;n[t-1-s]=o^i}return n}function r3(r,e){let t=Math.max(r.length,e.length);for(let n=0;n<t;n++){let s=r[n]??0,o=e[n]??0;if(s<o)return!0;if(s>o)return!1}return!1}function oA(r){for(let e=0;e<r.length;e++)if(r[e]!==0)return e;return Number.POSITIVE_INFINITY}function HB(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function iA(r,e,t,n){return r3(e,n)?!0:r3(n,e)?!1:r<t}function sf(r,e,t,n,s,o=1){let i,a=[];for(let u of t){let d=r.getById(u);if(!d)continue;let p=nf(d.coord,e),f=n(u),h=(f?1:0)+.25*s(u);a.push({id:u,dist:p,connected:f,score:h}),(!i||iA(u,p,i.id,i.dist))&&(i={id:u,dist:p})}if(!i)return;let c=oA(i.dist),l;for(let u of a){if(!u.connected)continue;if(oA(u.dist)<=c+o){if(!l){l={id:u.id,dist:u.dist,score:u.score};continue}iA(u.id,u.dist,l.id,l.dist)?l={id:u.id,dist:u.dist,score:u.score}:HB(u.dist,l.dist)&&(u.score>l.score||u.score===l.score&&u.id<l.id)&&(l={id:u.id,dist:u.dist,score:u.score})}}return l?.id??i.id}function aA(r=12,e=.08,t=.03,n=.6,s=.7,o=1.8,i=1e-6){let a=[];for(let c=0;c<r;c++)a.push((c+.5)/r);return{centers:a,occupancy:new Float64Array(r),alpha:t,sigma:e,beta:n,sMin:s,sMax:o,eps:i}}function of(r,e){let t=nf(r,e),n=0;for(let o=0;o<t.length;o++){let i=t[o]??0;if(i===0){n+=8;continue}let a=7-Math.floor(Math.log2(i));n+=a;break}return 1-Math.min(256,n)/256}function cA(r,e){let t=r/Math.max(1e-9,e);return Math.exp(-.5*t*t)}function n3(r,e){for(let t=0;t<r.centers.length;t++){let n=cA(Math.abs(e-r.centers[t]),r.sigma);r.occupancy[t]=(1-r.alpha)*r.occupancy[t]+r.alpha*n}}function s3(r,e){let t=0,n=0;for(let i=0;i<r.centers.length;i++){let a=cA(Math.abs(e-r.centers[i]),r.sigma);t+=r.occupancy[i]*a,n+=1*a}let s=(n+r.eps)/(t+r.eps),o=Math.pow(s,r.beta);return Math.max(r.sMin,Math.min(r.sMax,o))}function qB(r,e){let t=Math.max(0,e-r.lastAccess),s=Math.log(2)/Math.max(1,6e4);return Math.exp(-s*t)}function VB(r){return Math.log1p(r.accessCount)/5}function GB(r){let e=r.successCount+r.failureCount,t=e>0?r.successCount/e:.5,n=r.avgLatencyMs>0?Math.min(1,r.avgLatencyMs/1e3):.5,s=.5*t+.5*(1-n);return Math.max(0,s)}function o3(r,e){return .4*qB(r,e)+.2*VB(r)+.4*GB(r)}function i3(r,e){return{...r,...e}}function lA(r,e,t,n=Date.now()){n3(t,e);let s=o3(r,n),o=s3(t,e),i=s*o;return i3(r,{lastAccess:n,relevance:i,accessCount:r.accessCount+1})}function uA(r,e,t,n,s=Date.now()){n3(n,t);let o=.2,i=r.avgLatencyMs>0?(1-o)*r.avgLatencyMs+o*e:e,a=o3({...r,avgLatencyMs:i,successCount:r.successCount+1},s),c=s3(n,t),l=a*c;return i3(r,{lastAccess:s,relevance:l,successCount:r.successCount+1,avgLatencyMs:i})}function hA(r,e,t,n=Date.now()){n3(t,e);let s=o3({...r,failureCount:r.failureCount+1},n)*.7,o=s3(t,e),i=s*o;return i3(r,{lastAccess:n,relevance:i,failureCount:r.failureCount+1})}var Kr=vs("service:fret"),Qi=class{mode="passive";store=new Od;cfg;node;stabilizing=!1;inflightAct=0;bucketNeighbors;bucketMaybeAct;bucketDiscovery;announcedIds=new Map;postBootstrapAnnounced=!1;sparsity=aA();cachedSelfCoord=null;preconnectRunning=!1;protocols;metadata;diag={peersDiscovered:0,snapshotsFetched:0,announcementsSent:0,pingsSent:0,pingsOk:0,pingsFail:0,maybeActForwarded:0,evictions:0};networkObservations=[];maxObservations=100;observationWindowMs=3e5;constructor(e,t){this.node=e,this.cfg={k:t?.k??15,m:t?.m??Math.ceil((t?.k??15)/2),capacity:t?.capacity??2048,profile:t?.profile??"core",bootstraps:t?.bootstraps??[],networkName:t?.networkName??"default"},this.protocols=XS(this.cfg.networkName),this.bucketDiscovery=new ji(this.cfg.profile==="core"?50:10,this.cfg.profile==="core"?25:3),this.bucketNeighbors=new ji(this.cfg.profile==="core"?20:8,this.cfg.profile==="core"?10:4),this.bucketMaybeAct=new ji(this.cfg.profile==="core"?32:8,this.cfg.profile==="core"?16:4)}getDiagnostics(){return this.diag}async selfCoord(){return this.cachedSelfCoord?this.cachedSelfCoord:(this.cachedSelfCoord=await qe(this.node.peerId),this.cachedSelfCoord)}enforceCapacity(){let e=Math.max(1,this.cfg.capacity);if(this.store.size()<=e)return;let t=this.cachedSelfCoord;if(!t)return;let n=this.store.protectedIdsAround(t,Math.max(2,this.cfg.m)),s=this.store.list();s.sort((o,i)=>o.relevance-i.relevance);for(let o of s){if(this.store.size()<=e)break;n.has(o.id)||this.store.remove(o.id)}}async applyTouch(e,t){let n=this.store.getById(e)??this.store.upsert(e,t),s=of(await this.selfCoord(),t),o=lA(n,s,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,accessCount:o.accessCount})}async applySuccess(e,t,n){let s=this.store.getById(e)??this.store.upsert(e,t),o=of(await this.selfCoord(),t),i=uA(s,n,o,this.sparsity);this.store.update(e,{lastAccess:i.lastAccess,relevance:i.relevance,successCount:i.successCount,avgLatencyMs:i.avgLatencyMs})}async applyFailure(e,t){let n=this.store.getById(e)??this.store.upsert(e,t),s=of(await this.selfCoord(),t),o=hA(n,s,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,failureCount:o.failureCount})}async start(){await this.seedFromPeerStore(),this.registerRpcHandlers(),await this.proactiveAnnounceOnStart(),this.startStabilizationLoop(),this.mode==="active"&&this.preconnectNeighbors(),this.node.addEventListener("peer:connect",async e=>{if(!this.postBootstrapAnnounced){this.postBootstrapAnnounced=!0;try{await this.announceNeighborsBounded(8)}catch(t){Kr("postBootstrap announce failed - %o",t)}}}),this.node.addEventListener("peer:connect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let n=this.store.getById(t)?.coord??await qe(Oe(t));this.store.setState(t,"connected"),await this.applyTouch(t,n)}catch(t){Kr("peer:connect handler failed - %o",t)}}),this.node.addEventListener("peer:disconnect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let n=this.store.getById(t)?.coord??await qe(Oe(t));this.store.setState(t,"disconnected"),await this.applyFailure(t,n)}catch(t){Kr("peer:disconnect handler failed - %o",t)}})}async stop(){this.stabilizing=!1;try{await this.sendLeaveToNeighbors()}catch(e){console.warn("sendLeaveToNeighbors failed",e)}}setMode(e){this.mode=e,e==="active"&&!this.preconnectRunning&&this.startActivePreconnectLoop()}async ready(){}registerRpcHandlers(){AI(this.node,async()=>this.handleNeighborsRequest(),(e,t)=>{this.mergeAnnounceSnapshot(e,t)},this.protocols),_I(this.node,async e=>this.handleMaybeAct(e),this.protocols.PROTOCOL_MAYBE_ACT),kI(this.node,async e=>this.handleLeave(e.from),this.protocols.PROTOCOL_LEAVE),MI(this.node,this.protocols.PROTOCOL_PING,()=>this.getNetworkSizeEstimate())}async handleNeighborsRequest(){return this.bucketNeighbors.tryTake()?await this.snapshot():{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:[],predecessors:[],sig:""}}async handleMaybeAct(e){if(e.ttl<=0)return await this.nearAnchorOnly(e);if(e.activity&&e.activity.length>128*1024)return await this.nearAnchorOnly(e);if(!this.bucketMaybeAct.tryTake())return await this.nearAnchorOnly(e);let t=this.cfg.profile==="core"?16:4;if(this.inflightAct>=t)return this.nearAnchorOnly(e);this.inflightAct++;try{return await this.routeAct(e)}catch(n){return console.error("routeAct failed:",n),await this.nearAnchorOnly(e)}finally{this.inflightAct--}}isConnected(e){try{return this.node.getConnections(Oe(e)).length>0}catch{return!1}}hasAddresses(e){try{let t=this.node.getMultiaddrsForPeer?.(Oe(e))??[];return Array.isArray(t)&&t.length>0}catch{return!1}}async proactiveAnnounceOnStart(){try{await this.announceNeighborsBounded(8)}catch(e){console.warn("proactiveAnnounceOnStart failed",e)}}async announceNeighborsBounded(e){let t=await qe(this.node.peerId),n=this.node.peerId.toString(),s=Array.from(new Set([...this.getNeighbors(t,"right",this.cfg.m),...this.getNeighbors(t,"left",this.cfg.m)])).filter(i=>i!==n).slice(0,e),o=await this.snapshot();for(let i of s)if(this.isConnected(i)||this.hasAddresses(i))try{await Py(this.node,i,o,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE),this.diag.announcementsSent++}catch(a){console.warn("announce failed",i,a)}}async preconnectNeighbors(){try{let e=await qe(this.node.peerId),t=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(e,"right",Math.min(6,this.cfg.m)),...this.getNeighbors(e,"left",Math.min(6,this.cfg.m))])).filter(s=>s!==t);for(let s of n)if(this.isConnected(s)||this.hasAddresses(s))try{await kl(this.node,s,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(o){Kr("preconnectNeighbors ping failed for %s - %o",s,o)}}catch(e){Kr("preconnectNeighbors outer failed - %o",e)}}startActivePreconnectLoop(){if(this.preconnectRunning)return;this.preconnectRunning=!0;let e=async()=>{if(!this.preconnectRunning||this.mode!=="active"){this.preconnectRunning=!1;return}try{let t=await this.selfCoord(),n=this.node.peerId.toString(),s=this.cfg.profile==="core"?6:3,o=Array.from(new Set([...this.getNeighbors(t,"right",Math.min(12,this.cfg.m)),...this.getNeighbors(t,"left",Math.min(12,this.cfg.m))])).filter(i=>i!==n).slice(0,s);for(let i of o)if(this.isConnected(i)||this.hasAddresses(i))try{await kl(this.node,i,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(a){Kr("active preconnect ping failed for %s - %o",i,a)}}catch(t){Kr("active preconnect tick failed - %o",t)}setTimeout(e,1e3)};e()}async sendLeaveToNeighbors(){try{let e=await qe(this.node.peerId),t=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(e,"right",this.cfg.m),...this.getNeighbors(e,"left",this.cfg.m)])).filter(o=>o!==t).slice(0,8),s={v:1,from:this.node.peerId.toString(),timestamp:Date.now()};for(let o of n)try{await LI(this.node,o,s,this.protocols.PROTOCOL_LEAVE)}catch(i){Kr("sendLeave failed for %s - %o",o,i)}}catch(e){Kr("sendLeaveToNeighbors outer failed - %o",e)}}async handleLeave(e){try{let t=null,n=this.store.getById(e);if(n)t=n.coord;else try{t=await qe(Oe(e))}catch(l){console.warn("handleLeave: could not hash departing peer id",e,l)}if(this.store.remove(e),t)try{await this.applyFailure(e,t)}catch{}if(!t)return;let s=Array.from(new Set([...this.store.neighborsRight(t,this.cfg.m),...this.store.neighborsLeft(t,this.cfg.m)])),o=this.expandCohort(s,t,Math.max(2,Math.ceil(this.cfg.m/2))),i=new Set(s),a=o.filter(l=>!i.has(l)),c=a.slice(0,Math.min(a.length,6));for(let l of c)try{if(await kl(this.node,l,this.protocols.PROTOCOL_PING),!this.isConnected(l)){let u=await this.snapshot();await Py(this.node,l,u,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE)}}catch(u){console.warn("warm/announce failed for",l,u)}await this.mergeNeighborSnapshots(c.slice(0,4))}catch(t){console.error("handleLeave failed for",e,t)}}async mergeAnnounceSnapshot(e,t){try{let n=Oe(e),s=await qe(n),o=[];this.store.getById(e)||o.push(e),this.store.upsert(e,s),await this.applyTouch(e,s),t.metadata&&this.store.update(e,{metadata:t.metadata});for(let i of[...t.successors??[],...t.predecessors??[]])try{let a=await qe(Oe(i));this.store.getById(i)||o.push(i),this.store.upsert(i,a),await this.applyTouch(i,a)}catch(a){console.warn("mergeAnnounceSnapshot: failed for",i,a)}for(let i of t.sample??[])try{let a=D(i.coord,"base64url");this.store.getById(i.id)||o.push(i.id),this.store.upsert(i.id,a),await this.applyTouch(i.id,a)}catch(a){Kr("mergeAnnounceSnapshot sample upsert failed for %s - %o",i.id,a)}this.enforceCapacity(),this.emitDiscovered(o)}catch(n){console.warn("mergeAnnounceSnapshot failed for",e,n)}}async seedFromPeerStore(){try{let e=this.node.peerStore?.getPeers?.()??[],t=[];for(let n of e)try{let s=await qe(n.id),o=n.id.toString();this.store.getById(o)||t.push(o),this.store.upsert(o,s)}catch(s){console.warn("failed to add peer from peerStore",n?.id?.toString?.(),s)}try{let n=await qe(this.node.peerId),s=this.node.peerId.toString();this.store.getById(s)||t.push(s),this.store.upsert(s,n)}catch(n){console.error("failed to add self to store",n)}this.enforceCapacity(),this.emitDiscovered(t)}catch(e){console.error("seedFromPeerStore failed:",e)}}startStabilizationLoop(){if(this.stabilizing)return;this.stabilizing=!0;let e=async()=>{if(this.stabilizing)try{await this.seedFromPeerStore(),await this.seedFromBootstraps(),await this.stabilizeOnce()}catch(t){console.error("stabilize tick failed:",t)}finally{let t=this.mode==="active"?300:1500;setTimeout(e,t)}};e()}async seedFromBootstraps(){if(!this.cfg.bootstraps||this.cfg.bootstraps.length===0)return;let e=[];for(let t of this.cfg.bootstraps.slice(0,8))try{let n=t;if(t.startsWith("/"))try{let a=Rl(t).getPeerId();a&&(n=a)}catch{}let s=Oe(n),o=await qe(s);this.store.getById(n)||e.push(n),this.store.upsert(n,o),await this.applyTouch(n,o)}catch(n){console.warn("seedFromBootstraps failed for",t,n)}this.enforceCapacity(),this.emitDiscovered(e)}async stabilizeOnce(){let e=await qe(this.node.peerId),t=this.node.peerId.toString(),s=this.getNeighbors(e,"both",Math.max(2,this.cfg.m)).filter(o=>o!==t&&(this.isConnected(o)||this.hasAddresses(o)));await this.probeNeighborsLatency(s.slice(0,4)),await this.mergeNeighborSnapshots(s.slice(0,4))}async probeNeighborsLatency(e){for(let t of e)try{let n=await kl(this.node,t,this.protocols.PROTOCOL_PING);if(this.diag.pingsSent++,n.ok){let s=this.store.getById(t)?.coord??await qe(Oe(t));await this.applySuccess(t,s,n.rttMs),this.diag.pingsOk++}else{let s=this.store.getById(t)?.coord??await qe(Oe(t));await this.applyFailure(t,s),this.diag.pingsFail++}}catch{try{let s=this.store.getById(t)?.coord??await qe(Oe(t));await this.applyFailure(t,s),this.diag.pingsFail++}catch{}}}async mergeNeighborSnapshots(e){let t=[];for(let n of e)try{let s=await CI(this.node,n,this.protocols.PROTOCOL_NEIGHBORS);this.diag.snapshotsFetched++;let o=this.cfg.profile==="core"?16:8,i=this.cfg.profile==="core"?16:8,a=(s.successors??[]).slice(0,o),c=(s.predecessors??[]).slice(0,i);for(let u of[...a,...c])try{let d=await qe(Oe(u));this.store.getById(u)||t.push(u),this.store.upsert(u,d),await this.applyTouch(u,d)}catch(d){console.warn("failed to merge neighbor",u,d)}let l=this.cfg.profile==="core"?8:6;for(let u of(s.sample??[]).slice(0,l))try{let d=D(u.coord,"base64url");this.store.getById(u.id)||t.push(u.id),this.store.upsert(u.id,d),await this.applyTouch(u.id,d)}catch(d){Kr("mergeNeighborSnapshots sample upsert failed for %s - %o",u.id,d)}}catch(s){console.warn("fetchNeighbors failed for",n,s)}this.enforceCapacity(),this.emitDiscovered(t)}async snapshot(){let e=await qe(this.node.peerId),{n:t,confidence:n}=Yd(this.store,this.cfg.m),s=this.cfg.profile==="core"?12:6,o=this.cfg.profile==="core"?12:6,i=this.cfg.profile==="core"?8:6,a=this.getNeighbors(e,"right",this.cfg.m),c=this.getNeighbors(e,"left",this.cfg.m),l=a.slice(0,s),u=c.slice(0,o),d=Array.from(new Set([...l.slice(0,4),...u.slice(0,4)])).slice(0,i),p=await Promise.all(d.map(async f=>{let h=this.store.getById(f);return h?{id:f,coord:YS(h.coord),relevance:h.relevance}:{id:f,coord:"",relevance:0}}));return{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:l,predecessors:u,sample:p,size_estimate:t,confidence:n,sig:"",metadata:this.metadata}}neighborDistance(e,t,n){let s=new Set,o=Math.max(1,n),a=this.assembleCohort(t,o,s).findIndex(c=>c===e);return a>=0?a:Number.POSITIVE_INFINITY}getNeighbors(e,t,n){let s=[];return(t==="right"||t==="both")&&s.push(...this.store.neighborsRight(e,n)),(t==="left"||t==="both")&&s.push(...this.store.neighborsLeft(e,n)),Array.from(new Set(s)).slice(0,n)}nextSuccessor(e,t){let n=t.findIndex(s=>s.id===e.id);return t[(n+1)%t.length]}nextPredecessor(e,t){let n=t.findIndex(s=>s.id===e.id);return t[(n-1+t.length)%t.length]}assembleCohort(e,t,n){let s=[],o=n??new Set,i=this.store.neighborsRight(e,t*2),a=this.store.neighborsLeft(e,t*2),c=0,l=0;for(;s.length<t&&(c<i.length||l<a.length);)if(s.length%2===0){let u=i[c++];u&&!o.has(u)&&s.push(u)}else{let u=a[l++];u&&!o.has(u)&&s.push(u)}return Array.from(new Set(s)).slice(0,t)}expandCohort(e,t,n,s){let o=new Set(e),i=this.assembleCohort(t,e.length+n,s);for(let a of i)o.add(a);return Array.from(o)}async nearAnchorOnly(e){let t=D(e.key,"base64url"),n=await ir(t),s=this.getNeighbors(n,"right",this.cfg.m),o=this.getNeighbors(n,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...s.slice(0,3),...o.slice(0,3)]),cohort_hint:Array.from(new Set([...s.slice(0,2),...o.slice(0,2)])),estimated_cluster_size:this.cfg.k,confidence:.5}}emitDiscovered(e){if(e.length===0)return;let t=Date.now(),n=this.cfg.profile==="core"?10*6e4:30*6e4,s=this.node,o=0;for(let i of Array.from(new Set(e)))if(!((this.announcedIds.get(i)??0)>t)){if(!this.bucketDiscovery.tryTake())break;try{let c=Oe(i);s.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:c,multiaddrs:[]}})),this.announcedIds.set(i,t+n),o++}catch(c){console.warn("emitDiscovered failed for",i,c)}}if(o>0&&this.announcedIds.size>4096)for(let[i,a]of this.announcedIds)a<=t&&this.announcedIds.delete(i)}pickAnchors(e){let t=Array.from(new Set(e));if(t.length===0)return[];let n=c=>.5,s=new Uint8Array(32),o=sf(this.store,s,t,c=>this.isConnected(c),n),i=t.filter(c=>c!==o),a=sf(this.store,s,i,c=>this.isConnected(c),n);return[o,a].filter(c=>!!c)}async routeAct(e){let t=D(e.key,"base64url"),n=await ir(t),s=this.node.peerId.toString();if(this.neighborDistance(s,n,2)>1&&e.ttl>0){let d=new Set([...e.breadcrumbs??[],s]),p=this.assembleCohort(n,Math.max(4,this.cfg.m)).filter(m=>!d.has(m)),f=m=>.5,h=sf(this.store,n,p,m=>this.isConnected(m),f);if(h){let m={...e,ttl:e.ttl-1,breadcrumbs:[...e.breadcrumbs??[],s]};try{return await PI(this.node,h,m,this.protocols.PROTOCOL_MAYBE_ACT)}catch(g){console.warn("forward maybeAct failed to",h,g)}}}let{n:i,confidence:a}=Yd(this.store,this.cfg.m),c=this.getNeighbors(n,"right",this.cfg.m),l=this.getNeighbors(n,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...c.slice(0,4),...l.slice(0,4)]),cohort_hint:Array.from(new Set([...c.slice(0,4),...l.slice(0,4)])),estimated_cluster_size:Math.max(this.cfg.k,i),confidence:a}}report(e){}reportNetworkSize(e,t,n="external"){let s=Date.now();this.networkObservations.push({estimate:e,confidence:t,timestamp:s,source:n});let o=s-this.observationWindowMs;this.networkObservations=this.networkObservations.filter(i=>i.timestamp>o),this.networkObservations.length>this.maxObservations&&(this.networkObservations=this.networkObservations.slice(-this.maxObservations))}getNetworkSizeEstimate(){let e=Yd(this.store,this.cfg.m),t=Date.now(),n=[{estimate:e.n,confidence:e.confidence,timestamp:t,source:"fret"},...this.networkObservations];if(n.length===0)return{size_estimate:0,confidence:0,sources:0};let s=0,o=0,i=0;for(let l of n){let u=t-l.timestamp,d=Math.exp(-u/(this.observationWindowMs/3)),p=d*l.confidence;o+=l.estimate*p,i+=l.confidence*d,s+=p}if(s===0)return{size_estimate:0,confidence:0,sources:0};let a=Math.round(o/s),c=i/n.length;return{size_estimate:a,confidence:Math.min(1,c),sources:n.length}}getNetworkChurn(){if(this.networkObservations.length<2)return 0;let e=Date.now(),t=this.observationWindowMs/2,n=e-t,s=this.networkObservations.filter(l=>l.timestamp>n),o=this.networkObservations.filter(l=>l.timestamp<=n);if(s.length===0||o.length===0)return 0;let i=s.reduce((l,u)=>l+u.estimate,0)/s.length,a=o.reduce((l,u)=>l+u.estimate,0)/o.length;return(i-a)/t*6e4}detectPartition(){if(this.networkObservations.length<10)return!1;let e=this.getNetworkSizeEstimate();if(e.confidence<.3)return!1;let t=Date.now()-3e4,n=this.networkObservations.filter(c=>c.timestamp<t);if(n.length<3)return!1;let s=n.slice(-5).reduce((c,l)=>c+l.estimate,0)/Math.min(5,n.length);if(e.size_estimate/s<.5)return!0;let i=Math.abs(this.getNetworkChurn()),a=e.size_estimate*.1;return i>a}setMetadata(e){this.metadata=e}getMetadata(e){return this.store.getById(e)?.metadata}listPeers(){return this.store.list().map(e=>({id:e.id,metadata:e.metadata}))}};var WB=vs("service:discovery");function a3(r,e){let t=r;for(let n of e.list())try{let s=Oe(n.id);t.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:s,multiaddrs:[]}}))}catch(s){WB("seedDiscovery failed for %s - %o",n.id,s)}}var af=class{components;cfg;inner=null;nodeRef=null;constructor(e,t){this.components=e,this.cfg=t}get[Symbol.toStringTag](){return"@optimystic/fret"}setLibp2p(e){this.nodeRef=e}ensure(){if(!this.inner){if(!this.nodeRef)throw new Error("Libp2pFretService: libp2p node not injected");this.inner=new Qi(this.nodeRef,this.cfg)}return this.inner}async start(){if(this.ensure(),!this.nodeRef)throw new Error("Libp2pFretService.start: libp2p node not injected");a3(this.nodeRef,this.inner?.store??{}),await this.ensure().start()}async stop(){await this.inner?.stop()}async routeAct(e){return await this.ensure().routeAct(e)}getNeighborsForKey(e,t,n){return this.ensure().getNeighbors(e,t,n)}assembleCohortForKey(e,t){return this.ensure().assembleCohort(e,t)}getDiagnostics(){return this.ensure().getDiagnostics?.()}neighborDistance(e,t,n){return this.ensure().neighborDistance(e,t,n)}getNeighbors(e,t,n){return this.ensure().getNeighbors(e,t,n)}assembleCohort(e,t,n){return this.ensure().assembleCohort(e,t,n)}expandCohort(e,t,n,s){return this.ensure().expandCohort(e,t,n,s)}async ready(){await this.ensure().ready()}setMode(e){this.ensure().setMode(e)}setMetadata(e){this.ensure().setMetadata(e)}report(e){this.ensure().report(e)}getMetadata(e){return this.ensure().getMetadata(e)}listPeers(){return this.ensure().listPeers()}};function c3(r){return e=>new af(e,r)}ke();var dA="/db-p2p/sync/",fA="1.0.0",Ul=(r="")=>`${r}${dA}${fA}`;var ho=class extends Cn{protocol;constructor(e,t,n=""){super(e,t),this.protocol=Ul(n)}async requestBlock(e){return await this.processMessage(e,this.protocol)}getProtocol(){return this.protocol}};var Kl=class{fretAdapter;peerNetwork;protocolPrefix;metrics={totalRequests:0,successByRing:new Map,failureByRing:new Map,averageDurationMs:0};constructor(e,t,n){this.fretAdapter=e,this.peerNetwork=t,this.protocolPrefix=n}log=Sr("storage:restoration");async restore(e,t){let n=Date.now();this.metrics.totalRequests++;let s=await this.getMyRingPeers(e),o=this.getMyRingDepth();for(let a of s){let c=await this.queryPeer(a,e,t);if(c)return this.recordSuccess(o,e,Date.now()-n),c}for(let a=o-1;a>=0;a--){let c=this.fretAdapter.findPeersAtRing(a),l=this.filterByPartition(c,e,a);for(let u of l){let d=await this.queryPeer(u,e,t);if(d)return this.recordSuccess(a,e,Date.now()-n),d}}let i=Date.now()-n;this.log("restore failed for block %s after %dms",e,i)}createRestoreCallback(){return async(e,t)=>await this.restore(e,t)}async getMyRingPeers(e){let t=new TextEncoder().encode(e),n=await ir(t);return this.fretAdapter.getFret().assembleCohort(n,10)}getMyRingDepth(){return this.fretAdapter.getMyArachnodeInfo()?.ringDepth??8}filterByPartition(e,t,n){if(n===0)return e;let s=this.extractBlockPrefix(t,n);return e.filter(o=>{let i=this.fretAdapter.getArachnodeInfo(o);return!i||!i.partition?!1:i.partition.prefixValue===s})}extractBlockPrefix(e,t){let n=new TextEncoder().encode(e),s=new Uint8Array(32);for(let i=0;i<Math.min(n.length,s.length);i++)s[i]=n[i];let o=0;for(let i=0;i<t;i++){let a=Math.floor(i/8),c=7-i%8,l=s[a]>>c&1;o=o<<1|l}return o}async queryPeer(e,t,n){try{let s=de(e),i=await new ho(s,this.peerNetwork,this.protocolPrefix).requestBlock({blockId:t,rev:n});return i.success?i.archive:void 0}catch(s){this.log("queryPeer failed for %s - %o",e,s);return}}recordSuccess(e,t,n){let s=this.metrics.successByRing.get(e)??0;this.metrics.successByRing.set(e,s+1);let o=Array.from(this.metrics.successByRing.values()).reduce((a,c)=>a+c,0),i=this.metrics.averageDurationMs*(o-1);this.metrics.averageDurationMs=(i+n)/o,console.log(`[Ring ${e}] Successfully restored block ${t} in ${n}ms`)}getMetrics(){return{...this.metrics}}};var Fl=class{fretAdapter;storageMonitor;config;constructor(e,t,n){this.fretAdapter=e,this.storageMonitor=t,this.config=n}async determineRing(){let e=await this.storageMonitor.getCapacity();if(e.available<this.config.minCapacity)return-1;let s=1e3*(100*1024),o=e.available/s,i=Math.max(0,Math.ceil(-Math.log2(Math.max(.001,o))));return Math.min(i,16)}async calculatePartition(e,t){if(e===0)return;let n=await qe({toString:()=>t}),s=e,o=this.extractPrefix(n,s);return{prefixBits:s,prefixValue:o}}async createArachnodeInfo(e){let t=await this.storageMonitor.getCapacity(),n=await this.determineRing(),s=n>=0?await this.calculatePartition(n,e):void 0;return{ringDepth:Math.max(0,n),partition:s,capacity:{total:t.total,used:t.used,available:t.available},status:"active"}}async shouldTransition(){let e=await this.storageMonitor.getCapacity(),t=e.used/e.total;if(t>this.config.thresholds.moveOut)return{shouldMove:!0,direction:"out",newRingDepth:await this.determineRing()+1};if(t<this.config.thresholds.moveIn){let n=await this.determineRing();if(n>0)return{shouldMove:!0,direction:"in",newRingDepth:n-1}}return{shouldMove:!1}}extractPrefix(e,t){let n=0;for(let s=0;s<t;s++){let o=Math.floor(s/8),i=7-s%8,a=e[o]>>i&1;n=n<<1|a}return n}};var zl=class{storage;config;constructor(e,t={}){this.storage=e,this.config=t}async getCapacity(){let t=this.config.totalBytes??10737418240,n=this.config.usedBytes,s=this.config.availableBytes;if(n!==void 0||s!==void 0||this.config.totalBytes!==void 0){let a=n??Math.max(0,t-(s??t)),c=s??Math.max(0,t-a);return{total:t,used:Math.min(t,Math.max(0,a)),available:Math.max(0,Math.min(t,c))}}let o=await this.estimateUsedSpace(),i=Math.max(0,t-o);return{total:t,used:o,available:i}}async estimateUsedSpace(){return 0}};var $l=class r{fret;static ARACHNODE_KEY="arachnode";constructor(e){this.fret=e}setArachnodeInfo(e){this.fret.setMetadata({[r.ARACHNODE_KEY]:e})}getArachnodeInfo(e){return this.fret.getMetadata(e)?.[r.ARACHNODE_KEY]}getMyArachnodeInfo(){let e=this.fret.node?.peerId?.toString();if(e)return this.getArachnodeInfo(e)}findPeersAtRing(e){return this.fret.listPeers().filter(n=>n.metadata?.[r.ARACHNODE_KEY]?.ringDepth===e).map(n=>n.id)}getKnownRings(){let e=this.fret.listPeers(),t=new Set;for(let n of e){let s=n.metadata?.[r.ARACHNODE_KEY];s?.ringDepth!==void 0&&t.add(s.ringDepth)}return Array.from(t).sort((n,s)=>n-s)}getRingStats(){let e=this.fret.listPeers(),t=new Map;for(let n of e){let s=n.metadata?.[r.ARACHNODE_KEY];if(s){let o=t.get(s.ringDepth)??{count:0,totalCapacity:0};t.set(s.ringDepth,{count:o.count+1,totalCapacity:o.totalCapacity+s.capacity.available})}}return Array.from(t.entries()).map(([n,s])=>({ringDepth:n,peerCount:s.count,avgCapacity:s.totalCapacity/s.count})).sort((n,s)=>n.ringDepth-s.ringDepth)}getFret(){return this.fret}};re();ie();var cf=class{components;running=!1;log;protocol;repo;registrar;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("db-p2p:sync-service"),this.protocol=Ul(t.protocolPrefix??""),this.repo=e.repo,this.registrar=e.registrar}async start(){this.running||(await this.registrar.handle(this.protocol,async e=>{await this.handleSyncRequest(e.stream)}),this.running=!0,this.log("Sync service started on protocol %s",this.protocol))}async stop(){this.running&&(await this.registrar.unhandle(this.protocol),this.running=!1,this.log("Sync service stopped"))}async handleSyncRequest(e){try{let t=await this.readRequest(e);this.log("[Ring Zulu] Received sync request for block %s revision %s",t.blockId,t.rev??"latest");let n=await this.buildArchive(t.blockId,t.rev,t.includePending,t.maxRevisions),s=n?{success:!0,archive:n,responderId:e.id}:{success:!1,error:"Block not found in local storage"};await this.sendResponse(e,s),this.log("[Ring Zulu] %s sync request for block %s",s.success?"Fulfilled":"Failed",t.blockId)}catch(t){this.log.error("Error handling sync request:",t);try{let n={success:!1,error:t instanceof Error?t.message:"Unknown error"};await this.sendResponse(e,n)}catch(n){this.log.error("Failed to send error response:",n)}}finally{try{await e.close()}catch{}}}async readRequest(e){let t=[];if(await ht(e,Pr,async s=>{for await(let o of s)t.push(o.subarray())}),t.length===0)throw new Error("No request received");let n=T(t[0],"utf8");return JSON.parse(n)}async sendResponse(e,t){let n=JSON.stringify(t),s=D(n,"utf8"),o=ht([s],yr);for await(let i of o)e.send(i)}async buildArchive(e,t,n,s){try{let o=t!==void 0?{rev:t,committed:[],pending:[]}:void 0,a=(await this.repo.get({blockIds:[e],context:o}))[e];if(!a||!a.state.latest)return;let c=a.state.latest;return{blockId:e,revisions:{[c.rev]:{action:{actionId:c.actionId,transform:{insert:a.block}},block:a.block}},range:[c.rev,c.rev+1]}}catch(o){this.log.error("Error building archive for block %s:",e,o);return}}},l3=(r={})=>e=>new cf(e,r);ie();ke();Ne();gr();bt();re();ie();var Et=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Un=class extends Error{static name="ValidationError";name="ValidationError"},lf=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},uf=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var yfe=new Uint8Array(0);function pA(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Tr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function mA(r){return new TextEncoder().encode(r)}function gA(r){return new TextDecoder().decode(r)}var p3={};z(p3,{base32:()=>Ss,base32hex:()=>nU,base32hexpad:()=>oU,base32hexpadupper:()=>iU,base32hexupper:()=>sU,base32pad:()=>tU,base32padupper:()=>rU,base32upper:()=>eU,base32z:()=>aU});function jB(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var YB=jB,XB=YB,bA=XB;var u3=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},h3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 wA(this,e)}},d3=class{decoders;constructor(e){this.decoders=e}or(e){return wA(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function wA(r,e){return new d3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var f3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new u3(e,t,n),this.decoder=new h3(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ji({name:r,prefix:e,encode:t,decode:n}){return new f3(r,e,t,n)}function Es({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=bA(t,r);return Ji({prefix:e,name:r,encode:n,decode:o=>Tr(s(o))})}function QB(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function JB(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function ZB(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function We({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=ZB(n);return Ji({prefix:e,name:r,encode(o){return JB(o,n,t)},decode(o){return QB(o,s,t,r)}})}var Ss=We({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),eU=We({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tU=We({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rU=We({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),nU=We({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),sU=We({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),oU=We({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),iU=We({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aU=We({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var m3={};z(m3,{base36:()=>Hl,base36upper:()=>cU});var Hl=Es({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cU=Es({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var g3={};z(g3,{base58btc:()=>an,base58flickr:()=>lU});var an=Es({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),lU=Es({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var uU=EA,xA=128,hU=127,dU=~hU,fU=Math.pow(2,31);function EA(r,e,t){e=e||[],t=t||0;for(var n=t;r>=fU;)e[t++]=r&255|xA,r/=128;for(;r&dU;)e[t++]=r&255|xA,r>>>=7;return e[t]=r|0,EA.bytes=t-n+1,e}var pU=y3,mU=128,vA=127;function y3(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw y3.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&vA)<<s:(i&vA)*Math.pow(2,s),s+=7}while(i>=mU);return y3.bytes=o-n,t}var gU=Math.pow(2,7),yU=Math.pow(2,14),bU=Math.pow(2,21),wU=Math.pow(2,28),xU=Math.pow(2,35),vU=Math.pow(2,42),EU=Math.pow(2,49),SU=Math.pow(2,56),IU=Math.pow(2,63),AU=function(r){return r<gU?1:r<yU?2:r<bU?3:r<wU?4:r<xU?5:r<vU?6:r<EU?7:r<SU?8:r<IU?9:10},CU={encode:uU,decode:pU,encodingLength:AU},TU=CU,ql=TU;function Vl(r,e=0){return[ql.decode(r,e),ql.decode.bytes]}function Zi(r,e,t=0){return ql.encode(r,e,t),e}function ea(r){return ql.encodingLength(r)}function ra(r,e){let t=e.byteLength,n=ea(r),s=n+ea(t),o=new Uint8Array(s+t);return Zi(r,o,0),Zi(t,o,n),o.set(e,s),new ta(r,t,e,o)}function SA(r){let e=Tr(r),[t,n]=Vl(e),[s,o]=Vl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ta(t,s,i,e)}function IA(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&pA(r.bytes,t.bytes)}}var ta=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function AA(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return PU(t,b3(r),e??an.encoder);default:return DU(t,b3(r),e??Ss.encoder)}}var CA=new WeakMap;function b3(r){let e=CA.get(r);if(e==null){let t=new Map;return CA.set(r,t),t}return e}var na=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Wl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==kU)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ra(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&IA(e.multihash,n.multihash)}toString(e){return AA(this,e)}toJSON(){return{"/":AA(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??TA(n,s,o.bytes))}else if(t[LU]===!0){let{version:n,multihash:s,code:o}=t,i=SA(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Wl)throw new Error(`Version 0 CID must use dag-pb (code: ${Wl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=TA(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Wl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Tr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ta(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=Vl(e.subarray(t));return t+=p,d},s=n(),o=Wl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=_U(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return b3(o).set(n,e),o}};function _U(r,e){switch(r[0]){case"Q":{let t=e??an;return[an.prefix,t.decode(`${an.prefix}${r}`)]}case an.prefix:{let t=e??an;return[an.prefix,t.decode(r)]}case Ss.prefix:{let t=e??Ss;return[Ss.prefix,t.decode(r)]}case Hl.prefix:{let t=e??Hl;return[Hl.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function PU(r,e,t){let{prefix:n}=t;if(n!==an.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function DU(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Wl=112,kU=18;function TA(r,e,t){let n=ea(r),s=n+ea(e),o=new Uint8Array(s+t.byteLength);return Zi(r,o,0),Zi(e,o,n),o.set(t,s),o}var LU=Symbol.for("@ipld/js-cid/CID");var MU=20;function x3({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new w3(r,e,t,n,s)}var w3=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??MU,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?_A(n,this.code,t?.truncate):n.then(s=>_A(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _A(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ra(e,r)}var E3={};z(E3,{base64:()=>OU,base64pad:()=>RU,base64url:()=>v3,base64urlpad:()=>NU});var OU=We({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),RU=We({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),v3=We({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),NU=We({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var S3={};z(S3,{base10:()=>BU});var BU=Es({prefix:"9",name:"base10",alphabet:"0123456789"});var I3={};z(I3,{base16:()=>UU,base16upper:()=>KU});var UU=We({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),KU=We({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var A3={};z(A3,{base2:()=>FU});var FU=We({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var C3={};z(C3,{base256emoji:()=>VU});var DA=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}"),zU=DA.reduce((r,e,t)=>(r[t]=e,r),[]),$U=DA.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function HU(r){return r.reduce((e,t)=>(e+=zU[t],e),"")}function qU(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=$U[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var VU=Ji({prefix:"\u{1F680}",name:"base256emoji",encode:HU,decode:qU});var T3={};z(T3,{base8:()=>GU});var GU=We({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var _3={};z(_3,{identity:()=>WU});var WU=Ji({prefix:"\0",name:"identity",encode:r=>gA(r),decode:r=>mA(r)});var Qfe=new TextEncoder,Jfe=new TextDecoder;var P3={};z(P3,{identity:()=>JU});var kA=0,XU="identity",LA=Tr;function QU(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ra(kA,LA(r))}var JU={code:kA,name:XU,encode:LA,digest:QU};var k3={};z(k3,{sha256:()=>ZU,sha512:()=>eK});var D3=ae(te("crypto"),1);var ZU=x3({name:"sha2-256",code:18,encode:r=>Tr(D3.default.createHash("sha256").update(r).digest())}),eK=x3({name:"sha2-512",code:19,encode:r=>Tr(D3.default.createHash("sha512").update(r).digest())});var MA={..._3,...A3,...T3,...S3,...I3,...p3,...m3,...g3,...E3,...C3},spe={...k3,...P3};bt();re();ie();function M3(r){return e=>T(e,r)}function O3(r){return e=>D(e,r)}function sa(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function fo(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function OA(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=fo(n);return Ee([t,s],t.length+s.length)}function RA(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ss.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 s=fo(n);return Ee([t,s],t.length+s.length)}function R3(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=T(e,"base32"),s=sa(t);return`${n}:${s}`}var N3=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new Et("Invalid byte value in IP address");e[n]=s}),e},NA=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,fe.isIPv4)(t[n]),i;o&&(i=N3(t[n]),t[n]=T(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,T(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new Et("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},BA=function(r){if(r.byteLength!==4)throw new Et("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},UA=function(r){if(r.byteLength!==16)throw new Et("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${t}"`)}};function KA(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${r}"`)}}var L3=Object.values(MA).map(r=>r.decoder),tK=(function(){let r=L3[0].or(L3[1]);return L3.slice(2).forEach(e=>r=r.or(e)),r})();function FA(r){return tK.decode(r)}function zA(r){return e=>r.encoder.encode(e)}function rK(r){if(parseInt(r).toString()!==r)throw new Un("Value must be an integer")}function nK(r){if(r<0)throw new Un("Value must be a positive integer, or zero")}function sK(r){return e=>{if(e>r)throw new Un(`Value must be smaller than or equal to ${r}`)}}function oK(...r){return e=>{for(let t of r)t(e)}}var jl=oK(rK,nK,sK(65535));var mt=-1,B3=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new uf(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Kn=new B3,xK=[{code:4,name:"ip4",size:32,valueToBytes:N3,bytesToValue:BA,validate:r=>{if(!(0,fe.isIPv4)(r))throw new Un(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:273,name:"udp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:33,name:"dccp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:41,name:"ip6",size:128,valueToBytes:NA,bytesToValue:UA,stringToValue:KA,validate:r=>{if(!(0,fe.isIPv6)(r))throw new Un(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mt},{code:43,name:"ipcidr",size:8,bytesToValue:M3("base10"),valueToBytes:O3("base10")},{code:53,name:"dns",size:mt},{code:54,name:"dns4",size:mt},{code:55,name:"dns6",size:mt},{code:56,name:"dnsaddr",size:mt},{code:132,name:"sctp",size:16,valueToBytes:fo,bytesToValue:sa,validate:jl},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mt,bytesToValue:M3("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?O3("base58btc")(r):na.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:R3,valueToBytes:OA},{code:445,name:"onion3",size:296,bytesToValue:R3,valueToBytes:RA},{code:446,name:"garlic64",size:mt},{code:447,name:"garlic32",size:mt},{code:448,name:"tls"},{code:449,name:"sni",size:mt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:mt,bytesToValue:zA(v3),valueToBytes:FA},{code:480,name:"http"},{code:481,name:"http-path",size:mt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:mt}];xK.forEach(r=>{Kn.addProtocol(r)});function $A(r){let e=[],t=0;for(;t<r.length;){let n=jt(r,t),s=Kn.getProtocol(n),o=Ae(n),i=vK(s,r,t+o),a=0;i>0&&s.size===mt&&(a=Ae(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,d=r.subarray(u,u+i);l.value=s.bytesToValue?.(d)??T(d)}e.push(l),t+=c}return e}function HA(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=Kn.getProtocol(n.code),o=Ae(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,s.size===mt&&(c=Ae(a)));let l=new Uint8Array(o+c+a),u=0;In(n.code,l,u),u+=o,i!=null&&(s.size===mt&&(In(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ee(t,e)}function qA(r){if(r.charAt(0)!=="/")throw new Et('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=Kn.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new Et(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Et(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new Et("Incomplete multiaddr");return e}function VA(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Kn.getProtocol(e.code);if(t==null)throw new Et(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function vK(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:jt(e,t)}var EK=Symbol.for("nodejs.util.inspect.custom"),Y3=Symbol.for("@multiformats/multiaddr");function SK(r){if(r==null&&(r="/"),As(r))return r.getComponents();if(r instanceof Uint8Array)return $A(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qA(r);if(Array.isArray(r))return r;throw new Et("Must be a string, Uint8Array, Component[], or another Multiaddr")}var mf=class r{[Y3]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=SK(e),t.validate!==!1&&IK(this)}get bytes(){return this.#r==null&&(this.#r=HA(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=VA(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new lf(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return W(this.bytes,e.bytes)}[EK](){return`Multiaddr(${this.toString()})`}};function IK(r){r.getComponents().forEach(e=>{let t=Kn.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function As(r){return!!r?.[Y3]}function q(r){return new mf(r)}var Xl=class r{libp2p;clusterSize;selfCoordinationConfig;networkHighWaterMark=1;lastConnectedTime=Date.now();constructor(e,t=16,n){this.libp2p=e,this.clusterSize=t,this.selfCoordinationConfig={gracePeriodMs:n?.gracePeriodMs??3e4,shrinkageThreshold:n?.shrinkageThreshold??.5,allowSelfCoordination:n?.allowSelfCoordination??!0},this.setupConnectionTracking()}coordinatorCache=new Map;static MAX_CACHE_ENTRIES=1e3;log=Sr("libp2p-key-network");toCacheKey(e){return T(e,"base64url")}setupConnectionTracking(){this.libp2p.addEventListener("connection:open",()=>{this.updateNetworkObservations()})}updateNetworkObservations(){(this.libp2p.getConnections?.()??[]).length>0&&(this.lastConnectedTime=Date.now());try{let n=this.getFret().getNetworkSizeEstimate();n.size_estimate>this.networkHighWaterMark&&(this.networkHighWaterMark=n.size_estimate,this.log("network-hwm-updated mark=%d confidence=%f",this.networkHighWaterMark,n.confidence))}catch{let n=(this.libp2p.getConnections?.().length??0)+1;n>this.networkHighWaterMark&&(this.networkHighWaterMark=n,this.log("network-hwm-updated mark=%d (from connections)",this.networkHighWaterMark))}}shouldAllowSelfCoordination(){if(!this.selfCoordinationConfig.allowSelfCoordination)return{allow:!1,reason:"disabled"};if(this.networkHighWaterMark<=1)return{allow:!0,reason:"bootstrap-node"};try{let t=this.getFret();if(t.detectPartition())return this.log("self-coord-blocked: partition-detected"),{allow:!1,reason:"partition-detected"};let n=t.getNetworkSizeEstimate(),s=1-n.size_estimate/this.networkHighWaterMark;if(s>this.selfCoordinationConfig.shrinkageThreshold)return this.log("self-coord-blocked: suspicious-shrinkage current=%d hwm=%d shrinkage=%f",n.size_estimate,this.networkHighWaterMark,s),{allow:!1,reason:"suspicious-shrinkage"}}catch{let t=this.libp2p.getConnections?.()??[];if(this.networkHighWaterMark>1&&t.length===0){let n=Date.now()-this.lastConnectedTime;if(n<this.selfCoordinationConfig.gracePeriodMs)return this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",n),{allow:!1,reason:"grace-period-not-elapsed"}}}let e=Date.now()-this.lastConnectedTime;return e<this.selfCoordinationConfig.gracePeriodMs&&(this.libp2p.getConnections?.()??[]).length===0?(this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",e),{allow:!1,reason:"grace-period-not-elapsed"}):(this.log("self-coord-allowed: extended-isolation (warn)"),{allow:!0,reason:"extended-isolation",warn:!0})}recordCoordinator(e,t,n=1800*1e3){let s=this.toCacheKey(e),o=Date.now();for(let[i,a]of this.coordinatorCache)a.expires<=o&&this.coordinatorCache.delete(i);for(this.coordinatorCache.set(s,{id:t,expires:o+n});this.coordinatorCache.size>r.MAX_CACHE_ENTRIES;){let i=this.coordinatorCache.keys().next().value;if(i==null)break;this.coordinatorCache.delete(i)}}getCachedCoordinator(e){let t=this.toCacheKey(e),n=this.coordinatorCache.get(t);if(n&&n.expires>Date.now())return n.id;n&&this.coordinatorCache.delete(t)}connect(e,t,n){let s=this.libp2p.getConnections?.(e)??[];if(Array.isArray(s)&&s.length>0&&typeof s[0]?.newStream=="function")return s[0].newStream([t]);let o={runOnLimitedConnection:!0,negotiateFully:!1};return this.libp2p.dialProtocol(e,[t],o)}getFret(){let e=this.libp2p.services?.fret;if(e==null)throw new Error("FRET service is not registered on this libp2p node");return e}async getNeighborIdsForKey(e,t){let n=this.getFret(),s=await ir(e),o=n.getNeighbors(s,"both",t);return Array.from(new Set(o)).slice(0,t)}async findCoordinator(e,t){let n=new Set((t?.excludedPeers??[]).map(l=>l.toString())),s=this.toCacheKey(e).substring(0,12);this.log("findCoordinator:start key=%s excluded=%o",s,Array.from(n).map(l=>l.substring(0,12)));let o=this.getCachedCoordinator(e);if(o!=null&&!n.has(o.toString()))return this.log("findCoordinator:cached-hit key=%s coordinator=%s",s,o.toString().substring(0,12)),o;let i=3,a=500;for(let l=0;l<i;l++){let u=(this.libp2p.getConnections?.()??[]).map(f=>f.remotePeer),d=new Set(u.map(f=>f.toString()));this.log("findCoordinator:connected-peers key=%s count=%d peers=%o attempt=%d",s,u.length,u.map(f=>f.toString().substring(0,12)),l);try{let f=await this.getNeighborIdsForKey(e,this.clusterSize);this.log("findCoordinator:fret-neighbors key=%s candidates=%o",s,f.map(g=>g.substring(0,12)));let h=f.filter(g=>d.has(g)||g===this.libp2p.peerId.toString());this.log("findCoordinator:fret-connected key=%s count=%d peers=%o",s,h.length,h.map(g=>g.substring(0,12)));let m=h.find(g=>!n.has(g));if(m){let g=de(m);return this.recordCoordinator(e,g),this.log("findCoordinator:fret-selected key=%s coordinator=%s",s,m.substring(0,12)),g}}catch(f){this.log("findCoordinator getNeighborIdsForKey failed - %o",f)}let p=u.find(f=>!n.has(f.toString()));if(p)return this.recordCoordinator(e,p),this.log("findCoordinator:connected-fallback key=%s coordinator=%s",s,p.toString().substring(0,12)),p;if(u.length===0&&l<i-1){this.log("findCoordinator:no-connections-retry key=%s attempt=%d delay=%dms",s,l,a),await new Promise(f=>setTimeout(f,a));continue}}let c=this.libp2p.peerId;if(!n.has(c.toString())){let l=this.shouldAllowSelfCoordination();if(!l.allow)throw this.log("findCoordinator:self-coord-blocked key=%s reason=%s",s,l.reason),new Error(`Self-coordination blocked: ${l.reason}. No coordinator available for key.`);return l.warn?this.log("findCoordinator:self-selected-warn key=%s coordinator=%s reason=%s",s,c.toString().substring(0,12),l.reason):this.log("findCoordinator:self-selected key=%s coordinator=%s reason=%s",s,c.toString().substring(0,12),l.reason),c}throw this.log("findCoordinator:all-excluded key=%s self=%s",s,c.toString().substring(0,12)),new Error("No coordinator available for key (all candidates excluded)")}getConnectedAddrsByPeer(){let e=this.libp2p.getConnections(),t={};for(let n of e){let s=n.remotePeer.toString(),o=n.remoteAddr?.toString?.();o&&(t[s]??=[]).push(o)}return t}parseMultiaddrs(e){let t=[];for(let n of e)try{q(n),t.push(n)}catch(s){console.warn("invalid multiaddr from connection",n,s)}return t}async findCluster(e){let t=this.getFret(),n=await ir(e),s=t.assembleCohort(n,this.clusterSize),o=this.toCacheKey(e).substring(0,12),i=Array.from(new Set([...s,this.libp2p.peerId.toString()])),a=this.getConnectedAddrsByPeer(),c=Object.keys(a);this.log("findCluster key=%s fretCohort=%d connected=%d cohortPeers=%o",o,s.length,c.length,i.map(u=>u.substring(0,12)));let l={};for(let u of i){if(u===this.libp2p.peerId.toString()){l[u]={multiaddrs:this.libp2p.getMultiaddrs().map(p=>p.toString()),publicKey:this.libp2p.peerId.publicKey?.raw??new Uint8Array};continue}let d=a[u]??[];l[u]={multiaddrs:this.parseMultiaddrs(d),publicKey:new Uint8Array}}return this.log("findCluster:result key=%s clusterSize=%d withAddrs=%d connectedInCohort=%d",o,Object.keys(l).length,Object.values(l).filter(u=>u.multiaddrs.length>0).length,i.filter(u=>c.includes(u)||u===this.libp2p.peerId.toString()).length),l}};var v8=ae(te("net"),1);V();var Pe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),X=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),GA=r=>({match:e=>r.match(e)===!1?e:!1}),he=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Pt=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),we=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function De(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var AK=X(421),WA=De(AK),yf=X(54),bf=X(55),wf=X(56),Q3=X(53),Ype=De(yf,he(X(421))),Xpe=De(bf,he(X(421))),Qpe=De(wf,he(X(421))),Jpe=De(Pt(Q3,wf,yf,bf),he(X(421))),jA=we(X(4),he(X(43))),YA=we(he(X(42)),X(41),he(X(43))),J3=Pt(jA,YA),bo=Pt(J3,Q3,yf,bf,wf),XA=De(Pt(J3,we(Pt(Q3,wf,yf,bf),he(X(421))))),Z3=De(jA),eb=De(YA),Zpe=De(J3),tb=we(bo,X(6)),Ql=we(bo,X(273)),Fn=De(we(tb,he(X(421)))),e1e=De(Ql),rb=we(Ql,Pe(460),he(X(421))),xf=we(Ql,Pe(461),he(X(421))),CK=Pt(rb,xf),t1e=De(rb),QA=De(xf),X3=Pt(bo,tb,Ql,rb,xf),JA=Pt(we(X3,Pe(477),he(X(421)))),Jl=De(JA),ZA=Pt(we(X3,Pe(478),he(X(421))),we(X3,Pe(448),he(X(449)),Pe(477),he(X(421)))),Zl=De(ZA),e8=we(Ql,Pe(280),he(X(466)),he(X(466)),he(X(421))),nb=De(e8),t8=we(xf,Pe(465),he(X(466)),he(X(466)),he(X(421))),sb=De(t8),gf=Pt(JA,ZA,we(tb,he(X(421))),we(CK,he(X(421))),we(bo,he(X(421))),e8,t8,X(421)),vf=De(gf),TK=we(he(gf),Pe(290),GA(Pe(281)),he(X(421))),Jt=De(TK),_K=Pt(we(gf,Pe(290),Pe(281),he(X(421))),we(gf,Pe(281),he(X(421))),we(Pe(281),he(X(421)))),ob=De(_K),PK=Pt(we(bo,X(6),Pe(480),he(X(421))),we(bo,Pe(480),he(X(421)))),r1e=De(PK),DK=we(bo,Pt(we(X(6,"443"),Pe(480)),we(X(6),Pe(443)),we(X(6),Pe(448),Pe(480)),we(Pe(448),Pe(480)),Pe(448),Pe(443)),he(X(421))),n1e=De(DK),kK=Pt(we(X(777),he(X(421)))),s1e=De(kK),LK=Pt(we(X(400),he(X(421)))),Ef=De(LK);var Le=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var x8=ae(te("node:net"),1);V();gv();var ib={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},r8={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},n8=new globalThis.TextEncoder;function MK(r,e){let t=ib[e],n=r8[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function OK(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ib[e],s=r8[e],o=r;for(;o.length>0;){let i=n8.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function ab(r,{size:e=32,utf8Buffer:t}={}){if(!ib[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return OK(r,e,t);r=n8.encode(r)}return MK(r,e)}re();var eu={hash:r=>Number(ab(r,{size:32})),hashV:(r,e)=>RK(eu.hash(r,e))};function RK(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),D(e,"base16")}re();rt();Ne();var cb=64,Fr=class{fp;h;seed;constructor(e,t,n,s=2){if(s>cb)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=ce(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?W(this.fp,e.fp):!1}};function wo(r,e){return Math.floor(Math.random()*(e-r))+r}var xo=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");let t=wo(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var NK=500,tu=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??eu,this.seed=e.seed??wo(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=D(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new xo(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new xo(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[wo(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new xo(this.bucketSize));for(let a=0;a<NK;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new xo(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=D(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=D(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},BK={1:.5,2:.84,4:.95,8:.98};function UK(r=.001){return r>.002?2:r>1e-5?4:8}function s8(r,e=.001){let t=UK(e),n=BK[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),cb);return{filterSize:s,bucketSize:t,fingerprintSize:o}}re();var Sf=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??eu,this.seed=e.seed??wo(0,Math.pow(2,10)),this.filterSeries=[new tu({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=D(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new tu({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function ln(r,e=.001,t){return new Sf({...s8(r,e),...t??{}})}V();function oe(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new B(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}function o8(r){try{let e=oe(r);switch(e.type){case"ip6":return sA("2000::/3",e.host);default:return!1}}catch{return!1}}function i8(r){try{let e=oe(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function a8(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function ru(r){try{let e=oe(r);switch(e.type){case"ip4":case"ip6":return a8(e.host);default:return!1}}catch{return!1}}function St(r){try{return oe(r),!0}catch{return!1}}var l8=ae(c8(),1),KK=["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"],FK=KK.map(r=>new l8.Netmask(r));function lb(r){for(let e of FK)if(e.contains(r))return!0;return!1}function zK(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function $K(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return lb(s)}function HK(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function qK(r){let e=r.split(":"),t=e[e.length-1];return lb(t)}function VK(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function la(r){if((0,fe.isIPv4)(r))return lb(r);if(zK(r))return $K(r);if(HK(r))return qK(r);if((0,fe.isIPv6)(r))return VK(r)}function zn(r){try{let e=oe(r);switch(e.type){case"ip4":case"ip6":return la(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}V();Ue();var ub=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},u8=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function hb(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((d,p)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){p(u8(i));return}if(i&&(c=()=>{p(u8(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,p),t===Number.POSITIVE_INFINITY)return;let f=new ub;a=o.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(h){p(h)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?d():s instanceof Error?p(s):(f.message=s??`Promise timed out after ${t} milliseconds`,p(f))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var GK=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function WK(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=GK(r),d=async(...f)=>{let h=t.multiArgs?f:f[0];if(t.filter)try{if(!await t.filter(h))return}catch(m){n(),i(m);return}c.push(h),t.count===c.length&&(n(),o(c))},p=(...f)=>{n(),i(t.rejectionMultiArgs?f:f[0])};n=()=>{for(let f of a)u(f,d);for(let f of t.rejectionEvents)a.includes(f)||u(f,p)};for(let f of a)l(f,d);for(let f of t.rejectionEvents)a.includes(f)||l(f,p);t.signal&&t.signal.addEventListener("abort",()=>{p(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=hb(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function Re(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=WK(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function vo(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var If=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Af=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Eo=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Cf=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Tf=class extends Error{static name="StreamClosedError";name="StreamClosedError"};V();Ue();function jK(r){return r.reason}async function Cs(r,e,t){if(e==null)return r;let n=t?.translateError??jK;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}V();var _f=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ut(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new rr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function YK(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Pf=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=YK(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,Y(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new rr),this.cleanup())}async join(e={}){let t=new _f(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Cs(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var ua=class extends me{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=vo(this.emitEmpty.bind(this),1),this.emitIdle=vo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Af;let n=new Pf(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new rr)}),this.clear()}async onEmpty(e){this.size!==0&&await Re(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Re(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Re(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ot({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new rr("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};V();Be();var XK=Math.pow(2,20)*4,Ts=class extends me{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??XK,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new U,this.writeBuffer=new U,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new Tf)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Cs(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Ot(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new ns(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new Th(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ns(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new wh;this.dispatchEvent(new _h(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new as))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new U(o);this.writeBuffer.consume(o.byteLength);let a=this.sendData(o);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Ch(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new dc(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new dc(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var ha=class extends Ts{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Re(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Re(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};V();function h8(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Df=class extends me{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let s=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",s);let o=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",o)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Cs(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Tn;let t=this.onCreateStream({...this.streamOptions,...e});return h8(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Cf(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let s=this.streams.findIndex(o=>o===e);s!==-1&&this.streams.splice(s,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var kf=class extends Ts{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Re(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Re(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};function zt(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}Ue();var da=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var QK=1.2,JK=2,ZK=5e3,eF=6e4,tF=5e3,Lf=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??tF;this.success=new da(t),this.failure=new da(t),this.next=new da(t),this.failureMultiplier=e.failureMultiplier??JK,this.timeoutMultiplier=e.timeoutMultiplier??QK,this.minTimeout=e.minTimeout??ZK,this.maxTimeout=e.maxTimeout??eF,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),s=zt([e.signal,n]);return Y(1/0,s,n),s.start=Date.now(),s.timeout=t,s}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var f8=ae(te("node:os"),1);function d8(r){return!!(r.startsWith("169.254.")||r.toLowerCase().startsWith("fe80"))}function db(r,e,t){let n=[r.type,t??r.host];if(r.protocol!=null){let s=e??r.port;s!=null&&n.push(r.protocol,s)}return r.type==="ip6"&&r.zone!=null&&n.unshift("ip6zone",r.zone),r.cidr!=null&&n.push("ipcidr",r.cidr),q(`/${n.join("/")}`)}var rF={4:"IPv4",6:"IPv6"};function nF(r){return["0.0.0.0","::"].includes(r)}function sF(r){let e=[],t=f8.default.networkInterfaces();for(let[,n]of Object.entries(t))if(n!=null)for(let s of n)d8(s.address)||s.family===rF[r]&&e.push(s.address);return e}function p8(r,e){if(r==null)return[];let t=oe(r);return(t.type==="ip4"||t.type==="ip6")&&nF(t.host)?sF(t.type==="ip4"?4:6).map(n=>db(t,e,n)):[db(t,e)]}V();function m8(r,e){if(typeof r!="string")throw new B(`invalid ip provided: ${r}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new B(`invalid port provided: ${e}`);if((0,fe.isIPv4)(r))return q(`/ip4/${r}/tcp/${e}`);if((0,fe.isIPv6)(r))return q(`/ip6/${r}/tcp/${e}`);throw new B(`invalid ip:port for creating a multiaddr: ${r}:${e}`)}V();gr();Be();V();gr();Be();var oF=4194304,Mf=class extends Error{static name="UnwrappedError";name="UnwrappedError"},su=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},pb=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},mb=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function iF(r){return typeof r?.closeRead=="function"}function aF(r){return typeof r?.close=="function"}function fb(r){return iF(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:aF(r)?r.status!=="open":!1}function cF(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function gb(r,e){let t=e?.maxBufferSize??oF,n=new U,s,o=!1;if(!cF(r))throw new B("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),s?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}s?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?s?.reject(u.error):s?.resolve()};r.addEventListener("close",a);let c=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(o===!0)throw new Mf("Stream was unwrapped");if(fb(r)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Eo(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=d){s.resolve();break}if(await Cs(s.promise,u?.signal),fb(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}s=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(fb(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,p),new Eo(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return l.read(u)}let f=n.sublist(0,p);return n.consume(p),f},async write(u,d){if(o===!0)throw new Mf("Stream was unwrapped");r.send(u)||await Re(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function _s(r,e={}){let t=gb(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ae(e.maxDataLength));let n=e?.lengthDecoder??jt,s=e?.lengthEncoder??Vr;return{async read(i){let a=-1,c=new U;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new su("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new mb(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new pb(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Eo(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Eo(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new U(s(i.byteLength),i),a)},async writeV(i,a){let c=new U(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function zr(r,e){let t=_s(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function lF(r){return r?.addEventListener!=null}function uF(r){let e=Ot(),t,n=i=>{e.push(i.data)},s=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)};return r.addEventListener("message",n),r.addEventListener("close",o,{once:!0}),r.addEventListener("remoteCloseWrite",s,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){t=Promise.withResolvers();let{done:l,value:u}=await Promise.race([c.next(),t.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(u!=null&&(r.send(u)||await Promise.race([Re(r,"drain",{rejectionEvents:["close"]})])),l===!0))break}await r.close()}}}function g8(...r){let e=r.map(t=>lF(t)?uF(t):t);return ht(...e)}var hF=1024*1024*4,dF=1024*1024*4,Of=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new U,this.maxBufferSize=e.maxBufferSize??hF,this.maxDataLength=e.maxDataLength??dF,this.lengthDecoder=e.lengthDecoder??jt,this.encodingLength=e.encodingLength??Ae}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new B(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(t<0||t>this.maxDataLength)throw new su("Invalid message length");let n=this.encodingLength(t),s=n+t;if(this.buffer.byteLength>=s){let o=this.buffer.sublist(n,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}};var Ps=class extends ua{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Rf=class extends ua{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Nf=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new yb}consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new If("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},yb=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};Ue();function y8(r,e,t){let n,s,o=!1;function i(){let l={signal:s.signal};if(t?.timeout!=null){let u=zt([s.signal,AbortSignal.timeout(t.timeout)]);Y(1/0,u),l.signal=u}o=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{o=!1,!s.signal.aborted&&(n=setTimeout(i,e))})}let a=vo(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{o||(clearTimeout(n),a())},start:()=>{c||(c=!0,s=new AbortController,Y(1/0,s.signal),t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),s?.abort(),c=!1}}}var bb=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Dt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new bb({name:e,metrics:t}):n=new Map,n}Ue();V();var wb=class extends ha{socket;constructor(e){let t=e.remoteAddr;if(e.localAddr!=null&&Ef.matches(e.localAddr))t=e.localAddr;else if(t==null){if(e.socket.remoteAddress==null||e.socket.remotePort==null)throw new B("Could not determine remote address or port");t=m8(e.socket.remoteAddress,e.socket.remotePort)}super({...e,remoteAddr:t}),this.socket=e.socket,this.socket.on("data",n=>{this.onData(n)}),this.socket.on("error",n=>{this.log("tcp error",t,n),this.abort(n)}),this.socket.setTimeout(e.inactivityTimeout??120*1e3),this.socket.once("timeout",()=>{this.log("tcp timeout",t),this.abort(new Gr)}),this.socket.once("end",()=>{this.log("tcp end",t),this.onTransportClosed()}),this.socket.once("close",n=>{if(this.log("tcp close",t),n){this.abort(new Error("TCP transmission error"));return}this.onTransportClosed()}),this.socket.on("drain",()=>{this.log("tcp drain"),this.safeDispatchEvent("drain")})}sendData(e){let t=0,n=!0;for(let s of e)if(t+=s.byteLength,n=this.socket.write(s),!n)break;return{sentBytes:t,canSendMore:n}}async sendClose(e){this.socket.destroyed||(this.socket.destroySoon(),await Re(this.socket,"close",e))}sendReset(){this.socket.resetAndDestroy()}sendPause(){this.socket.pause()}sendResume(){this.socket.resume()}},Bf=r=>new wb(r);var b8=ae(te("os"),1),w8=ae(te("path"),1);V();function Uf(r,e={}){if(Ef.exactMatch(r)){let o=r.getComponents().find(i=>i.code===400)?.value;if(o==null)throw new B(`Multiaddr ${r} was not a Unix address`);return b8.default.platform()==="win32"?{path:w8.default.join("\\\\.\\pipe\\",o)}:{path:o}}let t=oe(r),n=t.host,s=t.port;return{host:n,port:s,ipv6Only:t.type==="ip6",...e}}var gt;(function(r){r[r.INACTIVE=0]="INACTIVE",r[r.ACTIVE=1]="ACTIVE",r[r.PAUSED=2]="PAUSED"})(gt||(gt={}));var Kf=class extends me{context;server;sockets=new Set;status={code:gt.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,e.allowHalfOpen=e.allowHalfOpen??!1,this.shutdownController=new AbortController,Y(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=x8.default.createServer(e,this.onSocket.bind(this)),e.maxConnections!==void 0&&(this.server.maxConnections=e.maxConnections),e.closeServerOnMaxConnections!=null&&e.closeServerOnMaxConnections.closeAbove<e.closeServerOnMaxConnections.listenBelow)throw new B("closeAbove must be >= listenBelow");e.metrics?.registerMetricGroup("libp2p_tcp_inbound_connections_total",{label:"address",help:"Current active connections in TCP listener",calculate:()=>({[this.addr]:this.sockets.size})}),this.metrics={status:e.metrics?.registerMetricGroup("libp2p_tcp_listener_status_info",{label:"address",help:"Current status of the TCP listener socket"}),errors:e.metrics?.registerMetricGroup("libp2p_tcp_listener_errors_total",{label:"address",help:"Total count of TCP listener errors by type"}),events:e.metrics?.registerMetricGroup("libp2p_tcp_listener_events_total",{label:"address",help:"Total count of TCP listener events by type"})},this.server.on("listening",()=>{let t=this.server.address();t==null?this.addr="unknown":typeof t=="string"?this.addr=t:this.addr=`${t.address}:${t.port}`,this.metrics.status?.update({[this.addr]:gt.ACTIVE}),this.safeDispatchEvent("listening")}).on("error",t=>{this.metrics.errors?.increment({[`${this.addr} listen_error`]:!0}),this.safeDispatchEvent("error",{detail:t})}).on("close",()=>{this.metrics.status?.update({[this.addr]:this.status.code}),this.status.code!==gt.PAUSED&&this.safeDispatchEvent("close")}).on("drop",()=>{this.metrics.events?.increment({[`${this.addr} drop`]:!0})})}onSocket(e){if(this.metrics.events?.increment({[`${this.addr} connection`]:!0}),this.status.code!==gt.ACTIVE)throw e.destroy(),new Dr("Server is not listening yet");let t;try{t=Bf({socket:e,inactivityTimeout:this.context.inactivityTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,direction:"inbound",localAddr:this.status.listeningAddr,log:this.context.logger.forComponent("libp2p:tcp:connection")})}catch(n){this.log.error("inbound connection failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_to_connection`]:!0}),e.destroy();return}this.log("new inbound connection %s",t.remoteAddr),this.sockets.add(e),this.context.upgrader.upgradeInbound(t,{signal:this.shutdownController.signal}).then(()=>{this.log("inbound connection upgraded %s",t.remoteAddr),e.once("close",()=>{this.sockets.delete(e),this.context.closeServerOnMaxConnections!=null&&this.sockets.size<this.context.closeServerOnMaxConnections.listenBelow&&this.resume().catch(n=>{this.log.error("error attempting to listen server once connection count under limit - %e",n),this.context.closeServerOnMaxConnections?.onListenError?.(n)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&(this.log("pausing incoming connections as limit is exceeded - %d/%d",this.sockets.size,this.context.closeServerOnMaxConnections.closeAbove),this.pause())}).catch(async n=>{this.log.error("inbound connection upgrade failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),t.abort(n)})}getAddrs(){if(this.status.code===gt.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[q(`/unix/${encodeURIComponent(e)}`)]:p8(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===gt.ACTIVE||this.status.code===gt.PAUSED)throw new Ih("server is already listening");try{this.status={code:gt.ACTIVE,listeningAddr:e,netConfig:Uf(e,this.context)},await this.resume()}catch(t){throw this.status={code:gt.INACTIVE},t}}async close(e){let t=[];this.server.listening&&t.push(Re(this.server,"close",e)),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(n=>{n.readable&&(t.push(Re(n,"close",e)),n.destroy())}),await Promise.all(t)}async resume(){if(this.server.listening||this.status.code===gt.INACTIVE)return;let e=this.status.netConfig;await new Promise((t,n)=>{this.server.once("error",n),this.server.listen(e,t)}),this.status={...this.status,code:gt.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===gt.PAUSED&&e){this.status={code:gt.INACTIVE};return}!this.server.listening||this.status.code!==gt.ACTIVE||(this.log("%s server on %s",e?"closing":"pausing",this.server.address()),this.status=e?{code:gt.INACTIVE}:{...this.status,code:gt.PAUSED},this.server.close())}};var Ff=class{opts;metrics;components;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:tcp"),this.opts=t,this.components=e,e.metrics!=null&&(this.metrics={events:e.metrics.registerCounterGroup("libp2p_tcp_dialer_events_total",{label:"event",help:"Total count of TCP dialer events by type"}),errors:e.metrics.registerCounterGroup("libp2p_tcp_dialer_errors_total",{label:"event",help:"Total count of TCP dialer events by type"})})}[Mh]=!0;[Symbol.toStringTag]="@libp2p/tcp";[nt]=["@libp2p/transport"];async dial(e,t){t.keepAlive=t.keepAlive??!0,t.noDelay=t.noDelay??!0,t.allowHalfOpen=t.allowHalfOpen??!1;let n=await this._connect(e,t),s;try{s=Bf({socket:n,inactivityTimeout:this.opts.outboundSocketInactivityTimeout,metrics:this.metrics?.events,direction:"outbound",remoteAddr:e,log:this.log.newScope("connection")})}catch(o){throw this.metrics?.errors.increment({outbound_to_connection:!0}),n.destroy(o),o}try{return this.log("new outbound connection %s",s.remoteAddr),await t.upgrader.upgradeOutbound(s,t)}catch(o){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection - %e",o),s.abort(o),o}}async _connect(e,t){t.signal.throwIfAborted(),t.onProgress?.(new Le("tcp:open-connection"));let n;return new Promise((s,o)=>{let i=Date.now(),a=Uf(e,{...this.opts.dialOpts??{},...t});this.log("dialing %a with opts %o",e,a),n=v8.default.connect(a);let c=f=>{this.log.error("dial to %a errored - %e",e,f);let h=a.path??`${a.host??""}:${a.port}`;f.message=`connection error ${h}: ${f.message}`,this.metrics?.events.increment({error:!0}),p(f)},l=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let f=new Gr(`Connection timeout after ${Date.now()-i}ms`);n.emit("error",f)},u=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),p()},d=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),p(new rr)},p=f=>{if(n.removeListener("error",c),n.removeListener("timeout",l),n.removeListener("connect",u),t.signal!=null&&t.signal.removeEventListener("abort",d),f!=null){o(f);return}s(n)};n.on("error",c),n.on("timeout",l),n.on("connect",u),t.signal.addEventListener("abort",d)}).catch(s=>{throw n?.destroy(),s})}createListener(e){return new Kf({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,inactivityTimeout:this.opts.inboundSocketInactivityTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(t=>Fn.exactMatch(t)||t.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function E8(r={}){return e=>new Ff(e,r)}Bt();ke();Bt();gr();Be();Ne();re();wr();rt();var ou;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:ce(0),payloadType:ce(0),payload:ce(0),signature:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(ou||(ou={}));var zf=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var lr=class r{static createFromProtobuf=e=>{let t=ou.decode(e),n=Ft(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=S8(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new zf("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=ou.encode({publicKey:dt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:W(this.marshal(),e.marshal())}async validate(e,t){let n=S8(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},S8=(r,e,t)=>{let n=D(r),s=Vr(n.byteLength),o=Vr(e.length),i=Vr(t.length);return new U(s,n,o,e,i,t)};ke();var u2e=new Uint8Array(0);function I8(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var fF=T8,A8=128,pF=127,mF=~pF,gF=Math.pow(2,31);function T8(r,e,t){e=e||[],t=t||0;for(var n=t;r>=gF;)e[t++]=r&255|A8,r/=128;for(;r&mF;)e[t++]=r&255|A8,r>>>=7;return e[t]=r|0,T8.bytes=t-n+1,e}var yF=xb,bF=128,C8=127;function xb(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw xb.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&C8)<<s:(i&C8)*Math.pow(2,s),s+=7}while(i>=bF);return xb.bytes=o-n,t}var wF=Math.pow(2,7),xF=Math.pow(2,14),vF=Math.pow(2,21),EF=Math.pow(2,28),SF=Math.pow(2,35),IF=Math.pow(2,42),AF=Math.pow(2,49),CF=Math.pow(2,56),TF=Math.pow(2,63),_F=function(r){return r<wF?1:r<xF?2:r<vF?3:r<EF?4:r<SF?5:r<IF?6:r<AF?7:r<CF?8:r<TF?9:10},PF={encode:fF,decode:yF,encodingLength:_F},DF=PF,vb=DF;function Eb(r,e=0){return[vb.decode(r,e),vb.decode.bytes]}function _8(r){let e=I8(r),[t,n]=Eb(e),[s,o]=Eb(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Sb(t,s,i,e)}var Sb=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var P8="libp2p-peer-record",D8=Uint8Array.from([3,1]);wr();rt();var iu;(function(r){let e;(function(n){let s;n.codec=()=>(s==null&&(s=Z((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:ce(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(u&7);break}}}return c})),s),n.encode=o=>J(o,n.codec()),n.decode=(o,i)=>Q(o,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Z((n,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(s.uint32(10),s.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(s.uint32(16),s.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)s.uint32(26),r.AddressInfo.codec().encode(i,s);o.lengthDelimited!==!1&&s.ldelim()},(n,s,o={})=>{let i={peerId:ce(0),seq:0n,addresses:[]},a=s==null?n.len:n.pos+s;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(o.limits?.addresses!=null&&i.addresses.length===o.limits.addresses)throw new _e('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:o.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>J(n,r.codec()),r.decode=(n,s)=>Q(n,r.codec(),s)})(iu||(iu={}));function k8(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var ur=class r{static createFromProtobuf=e=>{let t=iu.decode(e),n=Br(_8(t.peerId)),s=(t.addresses??[]).map(i=>q(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=P8;static CODEC=D8;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=iu.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!k8(this.multiaddrs,e.multiaddrs))}};Ue();var L2e=new Uint8Array(0);function L8(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function $n(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var MF=R8,M8=128,OF=127,RF=~OF,NF=Math.pow(2,31);function R8(r,e,t){e=e||[],t=t||0;for(var n=t;r>=NF;)e[t++]=r&255|M8,r/=128;for(;r&RF;)e[t++]=r&255|M8,r>>>=7;return e[t]=r|0,R8.bytes=t-n+1,e}var BF=Ib,UF=128,O8=127;function Ib(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ib.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&O8)<<s:(i&O8)*Math.pow(2,s),s+=7}while(i>=UF);return Ib.bytes=o-n,t}var KF=Math.pow(2,7),FF=Math.pow(2,14),zF=Math.pow(2,21),$F=Math.pow(2,28),HF=Math.pow(2,35),qF=Math.pow(2,42),VF=Math.pow(2,49),GF=Math.pow(2,56),WF=Math.pow(2,63),jF=function(r){return r<KF?1:r<FF?2:r<zF?3:r<$F?4:r<HF?5:r<qF?6:r<VF?7:r<GF?8:r<WF?9:10},YF={encode:MF,decode:BF,encodingLength:jF},XF=YF,au=XF;function cu(r,e=0){return[au.decode(r,e),au.decode.bytes]}function fa(r,e,t=0){return au.encode(r,e,t),e}function pa(r){return au.encodingLength(r)}function $f(r,e){let t=e.byteLength,n=pa(r),s=n+pa(t),o=new Uint8Array(s+t);return fa(r,o,0),fa(t,o,n),o.set(e,s),new ma(r,t,e,o)}function ga(r){let e=$n(r),[t,n]=cu(e),[s,o]=cu(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new ma(t,s,i,e)}function B8(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&L8(r.bytes,t.bytes)}}var ma=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};V();var Ab=1e3,U8=60*Ab,K8=15,F8=120*U8,z8=1,qf=5e3,$8=100,Cb="circuit-relay-source",lu=`${mc}-circuit-relay`,H8=2*U8,q8=BigInt(1<<17),un="/libp2p/circuit/relay/0.2.0/hop",uu="/libp2p/circuit/relay/0.2.0/stop",V8=30*Ab,U2e=30*Ab,hu=300,G8=4096,W8=.001;wr();rt();var Ce;(function(r){let e;(function(s){s.RESERVE="RESERVE",s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.RESERVE=0]="RESERVE",s[s.CONNECT=1]="CONNECT",s[s.STATUS=2]="STATUS"})(t||(t={})),(function(s){s.codec=()=>sr(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Z((s,o,i={})=>{i.lengthDelimited!==!1&&o.fork(),s.type!=null&&(o.uint32(8),r.Type.codec().encode(s.type,o)),s.peer!=null&&(o.uint32(18),ya.codec().encode(s.peer,o)),s.reservation!=null&&(o.uint32(26),Vf.codec().encode(s.reservation,o)),s.limit!=null&&(o.uint32(34),ba.codec().encode(s.limit,o)),s.status!=null&&(o.uint32(40),le.codec().encode(s.status,o)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=ya.codec().decode(s,s.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=Vf.codec().decode(s,s.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=ba.codec().decode(s,s.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=le.codec().decode(s);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>J(s,r.codec()),r.decode=(s,o)=>Q(s,r.codec(),o)})(Ce||(Ce={}));var hr;(function(r){let e;(function(s){s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.CONNECT=0]="CONNECT",s[s.STATUS=1]="STATUS"})(t||(t={})),(function(s){s.codec=()=>sr(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Z((s,o,i={})=>{i.lengthDelimited!==!1&&o.fork(),s.type!=null&&(o.uint32(8),r.Type.codec().encode(s.type,o)),s.peer!=null&&(o.uint32(18),ya.codec().encode(s.peer,o)),s.limit!=null&&(o.uint32(26),ba.codec().encode(s.limit,o)),s.status!=null&&(o.uint32(32),le.codec().encode(s.status,o)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=ya.codec().decode(s,s.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=ba.codec().decode(s,s.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=le.codec().decode(s);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>J(s,r.codec()),r.decode=(s,o)=>Q(s,r.codec(),o)})(hr||(hr={}));var ya;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let o of t.addrs)n.uint32(18),n.bytes(o);s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={id:ce(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.id=t.bytes();break}case 2:{if(s.limits?.addrs!=null&&o.addrs.length===s.limits.addrs)throw new _e('Decode error - map field "addrs" had too many elements');o.addrs.push(t.bytes());break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(ya||(ya={}));var Vf;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let o of t.addrs)n.uint32(18),n.bytes(o);t.voucher!=null&&(n.uint32(26),Gf.codec().encode(t.voucher,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.expire=t.uint64();break}case 2:{if(s.limits?.addrs!=null&&o.addrs.length===s.limits.addrs)throw new _e('Decode error - map field "addrs" had too many elements');o.addrs.push(t.bytes());break}case 3:{o.voucher=Gf.codec().decode(t,t.uint32(),{limits:s.limits?.voucher});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Vf||(Vf={}));var ba;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.duration=t.uint32();break}case 2:{o.data=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(ba||(ba={}));var le;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(le||(le={}));var Tb;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Tb||(Tb={}));(function(r){r.codec=()=>sr(Tb)})(le||(le={}));var wa;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={relay:ce(0),peer:ce(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.relay=t.bytes();break}case 2:{o.peer=t.bytes();break}case 3:{o.expiration=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(wa||(wa={}));var Gf;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&(n.uint32(26),wa.codec().encode(t.payload,n)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:ce(0),payloadType:ce(0),signature:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=wa.codec().decode(t,t.uint32(),{limits:s.limits?.payload});break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Gf||(Gf={}));V();function QF(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var JF=QF,ZF=JF,j8=ZF;var _b=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Pb=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 Y8(this,e)}},Db=class{decoders;constructor(e){this.decoders=e}or(e){return Y8(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Y8(r,e){return new Db({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var kb=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new _b(e,t,n),this.decoder=new Pb(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function X8({name:r,prefix:e,encode:t,decode:n}){return new kb(r,e,t,n)}function xa({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=j8(t,r);return X8({prefix:e,name:r,encode:n,decode:o=>$n(s(o))})}function ez(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function tz(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function rz(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function hn({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=rz(n);return X8({prefix:e,name:r,encode(o){return tz(o,n,t)},decode(o){return ez(o,s,t,r)}})}var du=hn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),j2e=hn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Y2e=hn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),X2e=hn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Q2e=hn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),J2e=hn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Z2e=hn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ege=hn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tge=hn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Wf=xa({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sge=xa({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Hn=xa({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),age=xa({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});function Q8(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return sz(t,Lb(r),e??Hn.encoder);default:return oz(t,Lb(r),e??du.encoder)}}var J8=new WeakMap;function Lb(r){let e=J8.get(r);if(e==null){let t=new Map;return J8.set(r,t),t}return e}var Mb=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==fu)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==iz)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=$f(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&B8(e.multihash,n.multihash)}toString(e){return Q8(this,e)}toJSON(){return{"/":Q8(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Z8(n,s,o.bytes))}else if(t[az]===!0){let{version:n,multihash:s,code:o}=t,i=ga(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==fu)throw new Error(`Version 0 CID must use dag-pb (code: ${fu}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Z8(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,fu,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=$n(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new ma(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=cu(e.subarray(t));return t+=p,d},s=n(),o=fu;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=nz(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Lb(o).set(n,e),o}};function nz(r,e){switch(r[0]){case"Q":{let t=e??Hn;return[Hn.prefix,t.decode(`${Hn.prefix}${r}`)]}case Hn.prefix:{let t=e??Hn;return[Hn.prefix,t.decode(r)]}case du.prefix:{let t=e??du;return[du.prefix,t.decode(r)]}case Wf.prefix:{let t=e??Wf;return[Wf.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function sz(r,e,t){let{prefix:n}=t;if(n!==Hn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function oz(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var fu=112,iz=18;function Z8(r,e,t){let n=pa(r),s=n+pa(e),o=new Uint8Array(s+t.byteLength);return fa(r,o,0),fa(e,o,n),o.set(t,s),o}var az=Symbol.for("@ipld/js-cid/CID");var Nb=ae(te("crypto"),1);var cz=20;function Rb({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Ob(r,e,t,n,s)}var Ob=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??cz,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?eC(n,this.code,t?.truncate):n.then(s=>eC(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function eC(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return $f(e,r)}var lz=Rb({name:"sha2-256",code:18,encode:r=>$n(Nb.default.createHash("sha256").update(r).digest())}),bge=Rb({name:"sha2-512",code:19,encode:r=>$n(Nb.default.createHash("sha512").update(r).digest())});var jf=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},Yf=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},pu=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Xf=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},Qf=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function tC(r,e,t){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new jf(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",s)}function rC(r,e,t,n,s){function o(u){r.abort(u),e.abort(u)}let i=[t,n.signal];if(n.limit?.duration!=null){s.log("limiting relayed connection duration to %dms",n.limit.duration);let u=AbortSignal.timeout(n.limit.duration);Y(1/0,u),i.push(u)}let a=zt(i);Y(1/0,a);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let l=()=>{let u;t.aborted?u=t.reason:u=new Yf(`duration limit of ${n.limit?.duration} ms exceeded`),o(u)};a.addEventListener("abort",l,{once:!0}),c!=null&&(tC(e,c,s),tC(r,c,s)),g8(r,e,r).catch(u=>{o(u)}).finally(()=>{a.clear()})}function Bb(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var mu=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},Jf=De(we(vf.matchers[0],Pe(290))),Zf=De(Pe(290));ke();var kge=new Uint8Array(0);function ep(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function uz(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var hz=uz,dz=hz,nC=dz;var Ub=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Kb=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 sC(this,e)}},Fb=class{decoders;constructor(e){this.decoders=e}or(e){return sC(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function sC(r,e){return new Fb({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var zb=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Ub(e,t,n),this.decoder=new Kb(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function fz({name:r,prefix:e,encode:t,decode:n}){return new zb(r,e,t,n)}function $b({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=nC(t,r);return fz({prefix:e,name:r,encode:n,decode:o=>ep(s(o))})}var oC=$b({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Uge=$b({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var pz=cC,iC=128,mz=127,gz=~mz,yz=Math.pow(2,31);function cC(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yz;)e[t++]=r&255|iC,r/=128;for(;r&gz;)e[t++]=r&255|iC,r>>>=7;return e[t]=r|0,cC.bytes=t-n+1,e}var bz=Hb,wz=128,aC=127;function Hb(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Hb.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&aC)<<s:(i&aC)*Math.pow(2,s),s+=7}while(i>=wz);return Hb.bytes=o-n,t}var xz=Math.pow(2,7),vz=Math.pow(2,14),Ez=Math.pow(2,21),Sz=Math.pow(2,28),Iz=Math.pow(2,35),Az=Math.pow(2,42),Cz=Math.pow(2,49),Tz=Math.pow(2,56),_z=Math.pow(2,63),Pz=function(r){return r<xz?1:r<vz?2:r<Ez?3:r<Sz?4:r<Iz?5:r<Az?6:r<Cz?7:r<Tz?8:r<_z?9:10},Dz={encode:pz,decode:bz,encodingLength:Pz},kz=Dz,qb=kz;function Vb(r,e=0){return[qb.decode(r,e),qb.decode.bytes]}function lC(r){let e=ep(r),[t,n]=Vb(e),[s,o]=Vb(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Gb(t,s,i,e)}var Gb=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function So(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function tp(r){let e=lC(oC.decode(`z${r}`));return Br(e)}var Zt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return So(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return So(this.map.values(),e=>e.key)}values(){return So(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Io=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return So(this.set.entries(),e=>{let t=tp(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=tp(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return So(this.set.values(),e=>tp(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var rp=class{filter;constructor(e,t){this.filter=ln(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function Wb(r,e=.001){return new rp(r,e)}var jb=class extends Zt{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function gu(r){let{name:e,metrics:t}=r,n;return t!=null?n=new jb({name:e,metrics:t}):n=new Zt,n}var Yb=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};function uC(r,e){let t=new Yb(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,s=()=>{n.abort(t)},o=AbortSignal.timeout(r);o.addEventListener("abort",s);let i=n.signal;return i.reset=a=>{o?.removeEventListener("abort",s),o=AbortSignal.timeout(a??r),o.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{o?.removeEventListener("abort",s),o=void 0},i}var np=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=t.maxReservations??K8,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??F8,this.defaultDurationLimit=t.defaultDurationLimit??H8,this.defaultDataLimit=t.defaultDataLimit??q8,this.reservations=gu({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let s=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&s==null)return{status:le.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",e),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),s={addr:t,expiry:o,limit:i,signal:uC(this.reservationTtl)}),this.reservations.set(e,s),s.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:le.OK,expire:Math.round(o.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var sp=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return wa.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof r)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var Oz={maxOutboundStopStreams:hu},op=class extends me{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=t?.hopTimeout??V8,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Oz.maxOutboundStopStreams,this.reservationStore=new np(e,t.reservations),this.shutdownController=new AbortController,Y(1/0,this.shutdownController.signal),this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(un,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(un),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);Y(1/0,n);let s={signal:n},o=zr(e);try{let i=await o.pb(Ce).read(s);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},s)}catch(i){this.log.error("error while handling hop - %e",i),await o.pb(Ce).write({type:Ce.Type.STATUS,status:le.MALFORMED_MESSAGE},s),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},s){switch(this.log("received hop message"),t.type){case Ce.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},s);break;case Ce.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(Ce).write({type:Ce.Type.STATUS,status:le.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let s=e.pb(Ce);if(this.log("hop reserve request from %p",t.remotePeer),Jt.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await s.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await s.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},n);return}let o=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(o.status!==le.OK){await s.write({type:Ce.Type.STATUS,status:o.status},n);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[Cb]:{value:1,ttl:i}}},n)}await s.write({type:Ce.Type.STATUS,status:le.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await s.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[Cb]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let n=[];for(let o of this.components.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||n.push(o.bytes);let s=await lr.seal(new sp({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:dt(s.publicKey),payloadType:s.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:s.signature}}}async handleConnect({stream:e,request:t,connection:n},s){let o=e.pb(Ce);if(Jt.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await o.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(q),i=Br(ga(t.peer.id))}catch(d){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,d),await o.write({type:Ce.Type.STATUS,status:le.MALFORMED_MESSAGE},s);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,le.NO_RESERVATION),await o.write({type:Ce.Type.STATUS,status:le.NO_RESERVATION},s);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await o.write({type:Ce.Type.STATUS,status:le.PERMISSION_DENIED},s);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await o.write({type:Ce.Type.STATUS,status:le.NO_RESERVATION},s);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:hr.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await o.write({type:Ce.Type.STATUS,status:le.CONNECTION_FAILED},s);return}await o.write({type:Ce.Type.STATUS,status:le.OK,limit:a?.limit},s),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),rC(e.unwrap(),u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let s=await e.newStream(uu,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=zr(s),i=o.pb(hr);await i.write(t,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await s.close(n);return}if(a.status===le.OK)return this.log("stop request to %p was successful",e.remotePeer),o.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};V();ke();Ue();Ue();ie();var ip=class extends me{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,Y(1/0,this.discoveryController.signal),this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(un,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,Y(1/0,this.discoveryController.signal),this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(un)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let o=hC(n),i=hC(s);return o>i?-1:i>o?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Ps({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(s=>s.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p - %e",n.id,s)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,s)})}async dialPeer({peerId:e,signal:t}){let n=zt([AbortSignal.timeout(5e3),t]);Y(1/0,n);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function hC(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(T(e)).getTime()}V();Ue();var Xb=class extends me{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??qf,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(Zf.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Jf.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);Y(1/0,t);let n=e.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let o=await this.reservationStore.addRelay(s.remotePeer,"configured");this.addedRelay(o)}}else throw new Hs(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>q(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function dC(r){return new Xb(r)}V();Ue();var Qb=te("node:crypto");var fC="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Rz=128,Ao,va;function Nz(r){!Ao||Ao.length<r?(Ao=Buffer.allocUnsafe(r*Rz),Qb.webcrypto.getRandomValues(Ao),va=0):va+r>Ao.length&&(Qb.webcrypto.getRandomValues(Ao),va=0),va+=r}function pC(r=21){Nz(r|=0);let e="";for(let t=va-r;t<va;t++)e+=fC[Ao[t]&63];return e}var Bz=60*1e3*10,Uz=60*1e3*5,Kz=30*1e3,ap=class extends me{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Zt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??$8,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??qf,this.started=!1,this.relayFilter=ln(100),this.reserveQueue=new Ps({concurrency:t?.reservationConcurrency??z8,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(o=>o.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(o=>{this.log("could not remove relay %p - %e",n.detail,o)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(lu)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[lu]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=pC();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new Hs("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Qf("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new Hs("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let s=Date.now();try{let o=this.reservations.get(e);if(o!=null){let h=this.connectionManager.getConnections(e),m=!1;if(h.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),h.map(g=>g.id).includes(o.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),m=!0),m&&Bb(o.reservation.expire)>Bz)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new pu("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);Y(1/0,i);let a=await this.connectionManager.openConnection(e,{signal:i});if(Jt.matches(a.remoteAddr))throw new Xf("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=Bb(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-Uz,Kz),Math.pow(2,31)-1),d=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async h=>{this.log.error("could not refresh reservation to relay %p - %e",e,h),await this.#t(e)}).catch(h=>{this.log.error("could not remove expired reservation to relay %p - %e",e,h)})},u),p;if(t==="discovered"){let h=this.pendingReservations.pop();if(h==null)throw new pu("Made reservation on relay but did not need any more discovered relays");p={timeout:d,reservation:c,type:t,connection:a.id,id:h}}else p={timeout:d,reservation:c,type:t,connection:a.id};this.reservations.set(e,p),await this.peerStore.merge(e,{tags:{[lu]:{value:1,ttl:l}}}),this.#r();let f={relay:e,details:p};return this.safeDispatchEvent("relay:created-reservation",{detail:f}),f}catch(o){throw t==="discovered"&&o.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-s,o),(o.name==="DialError"||o.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),o}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(un,t),o=zr(n).pb(Ce);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:Ce.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===le.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=q(l);u.getComponents().find(d=>d.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=q(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>q(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[lu]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=ln(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};Be();var Jb=class extends ha{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function Zb(r){return new Jb(r)}var Fz=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(q)}catch{return!1}return!0},mC={maxInboundStopStreams:hu,maxOutboundStopStreams:hu,stopTimeout:3e4},cp=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??mC.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??mC.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new ip(e,{filter:t.discoveryFilter??Wb(G8,W8)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,s)})}),this.reservationStore=new ap(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[nt]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[yc](){return this.discovery!=null?["@libp2p/identify"]:[]}[Mh]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,Y(1/0,this.shutdownController.signal),await this.components.registrar.handle(uu,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await kh(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Lh(this.discovery,this.reservationStore),await this.components.registrar.unhandle(uu),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),s=q(n[0]),o=q(n[n.length-1]),i=s.getComponents().find(f=>f.code===421)?.value,a=o.getComponents().find(f=>f.code===421)?.value;if(i==null||a==null){let f=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${f}`),new os(`C${f}`)}let c=de(i),l=de(a),d=this.components.connectionManager.getConnections(c)[0];d==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),t.onProgress?.(new Le("circuit-relay:open-connection")),d=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Le("circuit-relay:reuse-connection"));let p;try{t.onProgress?.(new Le("circuit-relay:open-hop-stream")),p=await d.newStream(un,t);let f=zr(p).pb(Ce);t.onProgress?.(new Le("circuit-relay:write-connect-message")),await f.write({type:Ce.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[q(o).bytes]}},t),t.onProgress?.(new Le("circuit-relay:read-connect-response"));let h=await f.read(t);if(h.status!==le.OK)throw new Rt(`failed to connect via relay with status ${h?.status?.toString()??"undefined"}`);let m=new mu(h.limit),g=Zb({stream:f.unwrap().unwrap(),remoteAddr:e,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:m.onData,onDataWrite:m.onData,log:p.log.newScope("circuit-relay:connection")}),y=await this.components.upgrader.upgradeOutbound(g,{...t,limits:m.getLimits()});return y.log("outbound relayed connection established to %p with limits %o, over connection %s",y.remotePeer,h.limit??"none",d.id),y}catch(f){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,f),p?.abort(f),f}}createListener(e){return dC({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Jf.exactMatch(t)||Zf.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Jt.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(d){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",d)}let s=zr(e).pb(hr),o=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:hr.Type.STATUS,status:le.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(o.type!==hr.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:hr.Type.STATUS,status:le.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!Fz(o)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:hr.Type.STATUS,status:le.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Br(ga(o.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:hr.Type.STATUS,status:le.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:hr.Type.STATUS,status:le.OK},{signal:n});let a=new mu(o.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=Zb({stream:s.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,o.limit??"none",t.id)}finally{n?.clear()}}};function gC(r={}){return e=>new op(e,r)}function yC(r={}){return e=>new cp(e,r)}Bt();ke();V();async function bC(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new B("Private network is enforced, but no protector was provided");return r}Bt();V();var P3e=new Uint8Array(0);function wC(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function zz(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var $z=zz,Hz=$z,xC=Hz;var ew=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},tw=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 vC(this,e)}},rw=class{decoders;constructor(e){this.decoders=e}or(e){return vC(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function vC(r,e){return new rw({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var nw=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new ew(e,t,n),this.decoder=new tw(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function EC({name:r,prefix:e,encode:t,decode:n}){return new nw(r,e,t,n)}function sw({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=xC(t,r);return EC({prefix:e,name:r,encode:n,decode:o=>wC(s(o))})}function qz(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Vz(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function Gz(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function $t({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Gz(n);return EC({prefix:e,name:r,encode(o){return Vz(o,n,t)},decode(o){return qz(o,s,t,r)}})}var SC=$t({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),N3e=$t({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),B3e=$t({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),U3e=$t({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),K3e=$t({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),F3e=$t({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),z3e=$t({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$3e=$t({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),H3e=$t({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var IC=sw({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),G3e=sw({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var AC=$t({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Y3e=$t({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),X3e=$t({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Q3e=$t({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var CC=ae(te("node:tty"),1),up=ae(te("node:util"),1);function Wz(r,e){if(typeof r=="string")return jz(r);if(typeof r=="number")return Qz(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var lp=Wz;function jz(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,s=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return s*315576e5;case"months":case"month":case"mo":return s*26298e5;case"weeks":case"week":case"w":return s*6048e5;case"days":case"day":case"d":return s*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return s*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return s*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return s*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function Yz(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Xz(r){let e=Math.abs(r);return e>=315576e5?Co(r,e,315576e5,"year"):e>=26298e5?Co(r,e,26298e5,"month"):e>=6048e5?Co(r,e,6048e5,"week"):e>=864e5?Co(r,e,864e5,"day"):e>=36e5?Co(r,e,36e5,"hour"):e>=6e4?Co(r,e,6e4,"minute"):e>=1e3?Co(r,e,1e3,"second"):`${r} ms`}function Qz(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?Xz(r):Yz(r)}function Co(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}Vg();function ow(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=i,t.humanize=lp,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let p=0;p<u.length;p++)d=(d<<5)-d+u.charCodeAt(p),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let p,f=null,h,m;function g(...y){if(!g.enabled)return;let b=g,E=Number(new Date),w=E-(p||E);b.diff=w,b.prev=p,b.curr=E,p=E,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let v=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(x,I)=>{if(x==="%%")return"%";v++;let A=t.formatters[I];if(typeof A=="function"){let j=y[v];x=A.call(b,j),y.splice(v,1),v--}return x}),t.formatArgs.call(b,y),d?.onLog!=null&&d.onLog(...y),(b.log||t.log).apply(b,y)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==t.namespaces&&(h=t.namespaces,m=t.enabled(u)),m),set:y=>{f=y}}),typeof t.init=="function"&&t.init(g),g}function n(u,d){let p=t(this.namespace+(typeof d>"u"?":":d)+u);return p.log=this.log,p}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,p=(typeof u=="string"?u:"").split(/[\s,]+/),f=p.length;for(d=0;d<f;d++)p[d]&&(u=p[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let d,p;for(d=0,p=t.skips.length;d<p;d++)if(t.skips[d].test(u))return!1;for(d=0,p=t.names.length;d<p;d++)if(t.names[d].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var TC=[6,2,3,4,5,1];pl.stderr!==!1&&(pl.stderr??pl).level>=2&&(TC=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]);var Ea=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,o)=>o.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function Jz(){return"colors"in Ea?!!Ea.colors:CC.default.isatty(process.stderr.fd)}function Zz(r){let{namespace:e,useColors:t}=this;if(t===!0){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),o=` ${s};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
4
+ `+o),r.push(s+"m+"+Gh.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=FM()+e+" "+r[0]}function FM(){return st.inspectOpts.hideDate?"":new Date().toISOString()+" "}function zM(...r){return process.stderr.write(Vh.formatWithOptions(st.inspectOpts,...r)+`
5
+ `)}function $M(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function HM(){return process.env.DEBUG}function qM(r){r.inspectOpts={};let e=Object.keys(st.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=st.inspectOpts[e[t]]}Gh.exports=M2()(st);var{formatters:av}=Gh.exports;av.o=function(r){return this.inspectOpts.colors=this.useColors,Vh.inspect(r,this.inspectOpts).split(`
6
+ `).map(e=>e.trim()).join(" ")};av.O=function(r){return this.inspectOpts.colors=this.useColors,Vh.inspect(r,this.inspectOpts)}});var U2=mt((bse,B2)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?B2.exports=sv():B2.exports=cv()});var RS=mt(Dl=>{(function(){var r,e,t,n,s,o,i,a;a=function(c){var l,u,d,p;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,d=(c&65280)>>>8,p=c&255,[l,u,d,p].join(".")},i=function(c){var l,u,d,p,f,h;for(l=[],d=p=0;p<=3&&c.length!==0;d=++p){if(d>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}h=e(c),f=h[0],u=h[1],c=c.substring(u),l.push(f)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),s=t("A"),e=function(c){var l,u,d,p,f;for(p=0,l=10,u="9",d=0,c.length>1&&c[d]==="0"&&(c[d+1]==="x"||c[d+1]==="X"?(d+=2,l=16):"0"<=c[d+1]&&c[d+1]<="9"&&(d++,l=8,u="7")),f=d;d<c.length;){if("0"<=c[d]&&c[d]<=u)p=p*l+(t(c[d])-n)>>>0;else if(l===16)if("a"<=c[d]&&c[d]<="f")p=p*l+(10+t(c[d])-o)>>>0;else if("A"<=c[d]&&c[d]<="F")p=p*l+(10+t(c[d])-s)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");d++}if(d===f)throw new Error("empty octet");return[p,d]},r=(function(){function c(l,u){var d,p,f,h;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(h=l.split("/",2),l=h[0],u=h[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw d=m,new Error("Invalid mask: "+u)}for(p=f=32;f>=0;p=--f)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw d=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,d,p;for(p=i(this.first),d=i(this.last),u=0;p<=d;)l(a(p),p,u),u++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),Dl.ip2long=i,Dl.long2ip=a,Dl.Netmask=r}).call(Dl)});var e8=mt((Awe,ZA)=>{ZA.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Bb=mt(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.TAG_LENGTH=Qr.DATA_CHUNK_LENGTH=Qr.NONCE_LENGTH=Qr.KEY_LENGTH=void 0;Qr.KEY_LENGTH=32;Qr.NONCE_LENGTH=12;Qr.DATA_CHUNK_LENGTH=65536;Qr.TAG_LENGTH=16});var p8=mt(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});Up.ChaCha20Poly1305=void 0;var Fe=Bb(),Ub=class{constructor(e){this.ctx=e;let t=e.cpKey.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,Fe.KEY_LENGTH);let n=e.cpNonce.value;this.wasmNonceArr=new Uint8Array(e.memory.buffer,n,Fe.NONCE_LENGTH);let s=e.cpAssociatedData.value;this.wasmAdArr=new Uint8Array(e.memory.buffer,s,Fe.KEY_LENGTH);let o=e.cpInput.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,o,Fe.DATA_CHUNK_LENGTH);let i=e.chacha20Output.value;this.wasmChacha20OutputArr=new Uint8Array(e.memory.buffer,i,Fe.DATA_CHUNK_LENGTH);let a=e.poly1305Output.value;this.wasmPoly1305OutputArr=new Uint8Array(e.memory.buffer,a,Fe.TAG_LENGTH);let c=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,c,64)}seal(e,t,n,s,o){this.init(e,t,s);let i=n.length+Fe.TAG_LENGTH,a;if(o){if(o.length!==i)throw new Error("ChaCha20Poly1305: incorrect destination length");a=o}else a=new Uint8Array(i);let c=s?.length??0;return this.sealUpdate(n,c,a),a.set(this.wasmPoly1305OutputArr,n.length),a}open(e,t,n,s,o){this.init(e,t,s);let i=n.subarray(0,n.length-Fe.TAG_LENGTH),a;if(o){if(o.length!==i.length)throw new Error("ChaCha20Poly1305: incorrect destination length");a=o}else a=new Uint8Array(i.length);let c=s?.length??0;this.openUpdate(i,c,a);let l=n.subarray(n.length-Fe.TAG_LENGTH,n.length);return this.isSameTag(l)?a:null}init(e,t,n=new Uint8Array(0)){if(e.length!=Fe.KEY_LENGTH)throw Error(`Invalid chacha20poly1305 key length ${e.length}, expect ${Fe.KEY_LENGTH}`);if(n.length>Fe.KEY_LENGTH)throw Error(`Invalid ad length ${n.length}, expect <= ${Fe.KEY_LENGTH}`);if(t.length!==Fe.NONCE_LENGTH)throw Error(`Invalid nonce length ${t.length}, expect ${Fe.NONCE_LENGTH}`);this.wasmKeyArr.set(e),this.wasmNonceArr.set(t),this.wasmAdArr.set(n)}openUpdate(e,t,n){this.commonUpdate(e,this.ctx.openUpdate,t,n)}sealUpdate(e,t,n){this.commonUpdate(e,this.ctx.sealUpdate,t,n)}commonUpdate(e,t,n,s){let o=e.length;if(e.length<=Fe.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),t(!0,!0,o,o,n),s.set(o===Fe.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,o));return}for(let i=0;i<o;i+=Fe.DATA_CHUNK_LENGTH){let a=Math.min(o,i+Fe.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(i,a));let c=i===0,l=i+Fe.DATA_CHUNK_LENGTH>=o;t(c,l,a-i,o,n),s.set(a-i===Fe.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,a-i),i)}}isSameTag(e){let t=!0;for(let n=0;n<Fe.TAG_LENGTH;n++)if(this.wasmPoly1305OutputArr[n]!==e[n]){t=!1;break}return t}};Up.ChaCha20Poly1305=Ub});var m8=mt(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});Kp.Poly1305=void 0;var Dn=Bb(),Kb=class{constructor(e){this.ctx=e;let t=e.poly1305Key.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,Dn.KEY_LENGTH);let n=e.poly1305Input.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,n,Dn.DATA_CHUNK_LENGTH);let s=e.poly1305Output.value;this.wasmOutputArr=new Uint8Array(e.memory.buffer,s,Dn.TAG_LENGTH);let o=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,o,64)}init(e){if(e.length!=Dn.KEY_LENGTH)throw Error(`Invalid poly1305 key length ${e.length}, expect ${Dn.KEY_LENGTH}`);this.wasmKeyArr.set(e),this.ctx.poly1305Init()}update(e){if(e.length<=Dn.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),this.ctx.poly1305Update(e.length);return}for(let t=0;t<e.length;t+=Dn.DATA_CHUNK_LENGTH){let n=Math.min(e.length,t+Dn.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(t,n)),this.ctx.poly1305Update(n-t)}}digest(){this.ctx.poly1305Digest();let e=new Uint8Array(Dn.TAG_LENGTH);return e.set(this.wasmOutputArr),e}};Kp.Poly1305=Kb});var g8=mt(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});Fp.wasmCode=void 0;Fp.wasmCode=Uint8Array.from([0,97,115,109,1,0,0,0,1,58,10,96,0,0,96,2,127,127,0,96,1,127,0,96,3,127,127,127,0,96,1,127,1,127,96,4,127,127,127,127,0,96,5,127,127,127,127,127,0,96,0,1,127,96,2,127,127,1,127,96,5,127,127,127,127,127,1,127,2,13,1,3,101,110,118,5,97,98,111,114,116,0,5,3,34,33,2,8,1,4,0,4,7,0,0,3,3,2,1,9,4,2,0,3,1,2,2,1,0,0,0,5,1,1,1,6,1,6,0,5,3,1,0,1,6,238,1,47,127,0,65,32,11,127,0,65,16,11,127,0,65,128,128,4,11,127,0,65,16,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,7,226,2,23,6,109,101,109,111,114,121,2,0,21,67,72,65,67,72,65,50,48,95,73,78,80,85,84,95,76,69,78,71,84,72,3,2,23,67,72,65,67,72,65,50,48,95,67,79,85,78,84,69,82,95,76,69,78,71,84,72,3,3,13,99,104,97,99,104,97,50,48,73,110,112,117,116,3,6,11,99,104,97,99,104,97,50,48,75,101,121,3,8,15,99,104,97,99,104,97,50,48,67,111,117,110,116,101,114,3,10,14,99,104,97,99,104,97,50,48,79,117,116,112,117,116,3,12,23,99,104,97,99,104,97,50,48,83,116,114,101,97,109,88,79,82,85,112,100,97,116,101,0,15,10,75,69,89,95,76,69,78,71,84,72,3,0,10,84,65,71,95,76,69,78,71,84,72,3,1,12,112,111,108,121,49,51,48,53,73,110,105,116,0,17,14,112,111,108,121,49,51,48,53,85,112,100,97,116,101,0,20,14,112,111,108,121,49,51,48,53,68,105,103,101,115,116,0,24,13,112,111,108,121,49,51,48,53,73,110,112,117,116,3,19,11,112,111,108,121,49,51,48,53,75,101,121,3,18,14,112,111,108,121,49,51,48,53,79,117,116,112,117,116,3,20,10,111,112,101,110,85,112,100,97,116,101,0,30,10,115,101,97,108,85,112,100,97,116,101,0,32,5,99,112,75,101,121,3,37,7,99,112,78,111,110,99,101,3,39,7,99,112,73,110,112,117,116,3,43,16,99,112,65,115,115,111,99,105,97,116,101,100,68,97,116,97,3,41,5,100,101,98,117,103,3,46,8,1,33,10,195,47,33,70,1,2,127,32,0,63,0,34,2,65,16,116,34,1,75,4,64,32,2,32,0,32,1,107,65,255,255,3,106,65,128,128,124,113,65,16,118,34,1,32,2,32,1,74,27,64,0,65,0,72,4,64,32,1,64,0,65,0,72,4,64,0,11,11,11,32,0,36,5,11,82,1,3,127,32,0,65,240,255,255,255,3,75,4,64,0,11,35,5,65,16,106,34,3,32,0,65,15,106,65,112,113,34,2,65,16,32,2,65,16,75,27,34,4,106,16,1,32,3,65,16,107,34,2,32,4,54,2,0,32,2,65,1,54,2,4,32,2,32,1,54,2,8,32,2,32,0,54,2,12,32,3,11,37,1,1,127,3,64,32,1,4,64,32,0,34,2,65,1,106,33,0,32,2,65,0,58,0,0,32,1,65,1,107,33,1,12,1,11,11,11,42,1,1,127,32,0,65,240,255,255,255,3,75,4,64,65,32,65,208,0,65,54,65,42,16,0,0,11,32,0,65,0,16,2,34,1,32,0,16,3,32,1,11,67,0,65,128,3,36,4,65,128,3,36,5,65,128,128,4,16,4,36,6,35,6,36,7,65,32,16,4,36,8,35,8,36,9,65,16,16,4,36,10,35,10,36,11,65,128,128,4,16,4,36,12,35,12,36,13,65,192,0,16,4,36,14,35,14,36,15,11,83,1,1,127,65,128,2,65,0,16,2,34,1,65,128,2,16,3,32,0,69,4,64,65,12,65,2,16,2,33,0,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,40,2,0,26,32,0,32,1,54,2,0,32,0,32,1,54,2,4,32,0,65,128,2,54,2,8,32,0,11,10,0,65,12,65,3,16,2,16,6,11,95,0,16,7,36,16,35,16,40,2,0,36,17,65,32,16,4,36,18,65,128,128,4,16,4,36,19,65,16,16,4,36,20,35,18,36,21,35,19,36,22,35,20,36,23,65,16,16,4,36,24,35,24,36,25,65,20,16,4,36,26,35,26,36,27,65,20,16,4,36,28,35,28,36,29,65,16,16,4,36,30,35,30,36,31,65,20,16,4,36,35,35,35,36,36,11,55,0,65,32,16,4,36,37,35,37,36,38,65,12,16,4,36,39,35,39,36,40,65,32,16,4,36,41,35,41,36,42,65,128,128,4,16,4,36,43,35,43,36,44,16,7,36,45,35,45,40,2,0,36,46,11,22,0,32,1,32,2,65,255,1,113,65,4,110,65,2,116,106,32,0,54,2,0,11,188,6,1,31,127,65,229,240,193,139,6,33,5,65,238,200,129,153,3,33,6,65,178,218,136,203,7,33,14,65,244,202,129,217,6,33,7,32,2,40,2,0,34,19,33,4,32,2,65,4,106,40,2,0,34,20,33,8,32,2,65,8,106,40,2,0,34,21,33,3,32,2,65,12,106,40,2,0,34,22,33,13,32,2,65,16,106,40,2,0,34,23,33,15,32,2,65,20,106,40,2,0,34,24,33,9,32,2,65,24,106,40,2,0,34,25,33,10,32,2,65,28,106,40,2,0,34,26,33,2,32,1,40,2,0,34,27,33,11,32,1,65,4,106,40,2,0,34,28,33,16,32,1,65,8,106,40,2,0,34,29,33,12,32,1,65,12,106,40,2,0,34,30,33,1,3,64,32,18,65,20,72,4,64,32,3,32,10,32,12,32,3,32,14,106,34,3,115,65,16,119,34,14,106,34,10,115,65,12,119,34,12,32,10,32,14,32,3,32,12,106,34,3,115,65,8,119,34,14,106,34,10,115,33,12,32,13,32,2,32,1,32,7,32,13,106,34,1,115,65,16,119,34,2,106,34,13,115,65,12,119,34,7,32,13,32,2,32,1,32,7,106,34,13,115,65,8,119,34,1,106,34,2,115,33,7,32,4,32,15,32,11,32,4,32,5,106,34,4,115,65,16,119,34,5,106,34,15,115,65,12,119,34,11,32,15,32,5,32,4,32,11,106,34,4,115,65,8,119,34,5,106,34,15,115,33,11,32,10,32,1,32,8,32,9,32,16,32,6,32,8,106,34,1,115,65,16,119,34,8,106,34,6,115,65,12,119,34,9,32,6,32,8,32,1,32,9,106,34,1,115,65,8,119,34,6,106,34,9,115,65,7,119,34,10,32,4,106,34,17,115,65,16,119,34,31,106,33,8,32,2,32,5,32,12,65,7,119,34,5,32,1,106,34,32,115,65,16,119,34,33,106,33,1,32,9,32,14,32,13,32,11,65,7,119,34,9,106,34,11,115,65,16,119,34,12,106,33,4,32,15,32,6,32,3,32,7,65,7,119,34,3,106,34,6,115,65,16,119,34,7,106,34,2,32,6,32,2,32,3,115,65,12,119,34,3,106,34,14,32,7,115,65,8,119,34,16,106,34,15,32,3,115,65,7,119,33,13,32,11,32,4,32,9,115,65,12,119,34,2,106,34,7,32,12,115,65,8,119,34,12,32,4,106,34,9,32,2,115,65,7,119,33,4,32,32,32,1,32,5,115,65,12,119,34,3,106,34,6,32,33,115,65,8,119,34,11,32,1,106,34,2,32,3,115,65,7,119,33,3,32,17,32,8,32,10,115,65,12,119,34,17,106,34,5,32,31,115,65,8,119,34,1,32,8,106,34,10,32,17,115,65,7,119,33,8,32,18,65,2,106,33,18,12,1,11,11,32,5,65,229,240,193,139,6,106,32,0,65,0,16,10,32,6,65,238,200,129,153,3,106,32,0,65,4,16,10,32,14,65,178,218,136,203,7,106,32,0,65,8,16,10,32,7,65,244,202,129,217,6,106,32,0,65,12,16,10,32,4,32,19,106,32,0,65,16,16,10,32,8,32,20,106,32,0,65,20,16,10,32,3,32,21,106,32,0,65,24,16,10,32,13,32,22,106,32,0,65,28,16,10,32,15,32,23,106,32,0,65,32,16,10,32,9,32,24,106,32,0,65,36,16,10,32,10,32,25,106,32,0,65,40,16,10,32,2,32,26,106,32,0,65,44,16,10,32,11,32,27,106,32,0,65,48,16,10,32,16,32,28,106,32,0,65,52,16,10,32,12,32,29,106,32,0,65,56,16,10,32,1,32,30,106,32,0,65,60,16,10,11,97,1,4,127,65,4,33,3,65,1,33,1,3,64,32,3,34,2,65,1,107,33,3,32,2,65,255,1,113,4,64,32,1,32,0,32,4,65,255,1,113,106,34,2,45,0,0,106,33,1,32,2,32,1,58,0,0,32,1,65,8,118,33,1,32,4,65,1,106,33,4,12,1,11,11,32,1,65,0,74,4,64,65,144,1,65,208,1,65,135,2,65,4,16,0,0,11,11,8,0,32,0,32,1,16,3,11,108,1,2,127,3,64,32,6,32,1,73,4,64,35,15,32,3,32,2,16,11,32,6,33,5,3,64,32,5,32,1,73,65,0,32,5,32,6,65,64,107,73,27,4,64,32,4,32,5,106,32,0,32,5,106,45,0,0,35,15,32,5,32,6,107,106,45,0,0,115,58,0,0,32,5,65,1,106,33,5,12,1,11,11,32,3,16,12,32,6,65,64,107,33,6,12,1,11,11,35,15,65,192,0,16,13,32,1,11,14,0,35,7,32,0,35,9,35,11,35,13,16,14,11,204,4,1,1,127,35,27,32,0,45,0,0,32,0,65,1,106,45,0,0,65,8,116,114,34,1,65,255,63,113,59,1,0,35,27,65,2,106,32,1,65,13,118,32,0,65,2,106,45,0,0,32,0,65,3,106,45,0,0,65,8,116,114,34,1,65,3,116,114,65,255,63,113,59,1,0,35,27,65,4,106,32,1,65,10,118,32,0,65,4,106,45,0,0,32,0,65,5,106,45,0,0,65,8,116,114,34,1,65,6,116,114,65,131,62,113,59,1,0,35,27,65,6,106,32,1,65,7,118,32,0,65,6,106,45,0,0,32,0,65,7,106,45,0,0,65,8,116,114,34,1,65,9,116,114,65,255,63,113,59,1,0,35,27,65,8,106,32,1,65,4,118,32,0,65,8,106,45,0,0,32,0,65,9,106,45,0,0,65,8,116,114,34,1,65,12,116,114,65,255,1,113,59,1,0,35,27,65,10,106,32,1,65,1,118,65,254,63,113,59,1,0,35,27,65,12,106,32,1,65,14,118,32,0,65,10,106,45,0,0,32,0,65,11,106,45,0,0,65,8,116,114,34,1,65,2,116,114,65,255,63,113,59,1,0,35,27,65,14,106,32,1,65,11,118,32,0,65,12,106,45,0,0,32,0,65,13,106,45,0,0,65,8,116,114,34,1,65,5,116,114,65,129,63,113,59,1,0,35,27,65,16,106,32,1,65,8,118,32,0,65,14,106,45,0,0,32,0,65,15,106,45,0,0,65,8,116,114,34,1,65,8,116,114,65,255,63,113,59,1,0,35,27,65,18,106,32,1,65,5,118,65,255,0,113,59,1,0,35,31,32,0,65,16,106,45,0,0,32,0,65,17,106,45,0,0,65,8,116,114,59,1,0,35,31,65,2,106,32,0,65,18,106,45,0,0,32,0,65,19,106,45,0,0,65,8,116,114,59,1,0,35,31,65,4,106,32,0,65,20,106,45,0,0,32,0,65,21,106,45,0,0,65,8,116,114,59,1,0,35,31,65,6,106,32,0,65,22,106,45,0,0,32,0,65,23,106,45,0,0,65,8,116,114,59,1,0,35,31,65,8,106,32,0,65,24,106,45,0,0,32,0,65,25,106,45,0,0,65,8,116,114,59,1,0,35,31,65,10,106,32,0,65,26,106,45,0,0,32,0,65,27,106,45,0,0,65,8,116,114,59,1,0,35,31,65,12,106,32,0,65,28,106,45,0,0,32,0,65,29,106,45,0,0,65,8,116,114,59,1,0,35,31,65,14,106,32,0,65,30,106,45,0,0,32,0,65,31,106,45,0,0,65,8,116,114,59,1,0,11,6,0,35,21,16,16,11,166,13,1,32,127,65,0,65,128,16,35,33,27,33,34,35,29,47,1,0,33,3,35,29,65,2,106,47,1,0,33,4,35,29,65,4,106,47,1,0,33,8,35,29,65,6,106,47,1,0,33,9,35,29,65,8,106,47,1,0,33,10,35,29,65,10,106,47,1,0,33,11,35,29,65,12,106,47,1,0,33,12,35,29,65,14,106,47,1,0,33,13,35,29,65,16,106,47,1,0,33,14,35,29,65,18,106,47,1,0,33,6,35,27,47,1,0,33,17,35,27,65,2,106,47,1,0,33,18,35,27,65,4,106,47,1,0,33,20,35,27,65,6,106,47,1,0,33,22,35,27,65,8,106,47,1,0,33,24,35,27,65,10,106,47,1,0,33,26,35,27,65,12,106,47,1,0,33,29,35,27,65,14,106,47,1,0,33,30,35,27,65,16,106,47,1,0,33,31,35,27,65,18,106,47,1,0,33,33,3,64,32,2,65,16,79,4,64,32,3,32,0,32,1,106,45,0,0,32,0,32,1,65,1,106,106,45,0,0,65,8,116,114,34,15,65,255,63,113,106,34,3,32,17,108,32,4,32,0,32,1,65,2,106,106,45,0,0,32,0,32,1,65,3,106,106,45,0,0,65,8,116,114,34,16,65,3,116,32,15,65,255,255,3,113,65,13,118,114,65,255,63,113,106,34,4,32,33,65,5,108,34,15,108,106,32,8,32,0,32,1,65,4,106,106,45,0,0,32,0,32,1,65,5,106,106,45,0,0,65,8,116,114,34,19,65,6,116,32,16,65,255,255,3,113,65,10,118,114,65,255,63,113,106,34,8,32,31,65,5,108,34,16,108,106,32,9,32,0,32,1,65,6,106,106,45,0,0,32,0,32,1,65,7,106,106,45,0,0,65,8,116,114,34,21,65,9,116,32,19,65,255,255,3,113,65,7,118,114,65,255,63,113,106,34,9,32,30,65,5,108,34,19,108,106,32,10,32,0,32,1,65,8,106,106,45,0,0,32,0,32,1,65,9,106,106,45,0,0,65,8,116,114,34,23,65,12,116,32,21,65,255,255,3,113,65,4,118,114,65,255,63,113,106,34,10,32,29,65,5,108,34,21,108,106,34,32,65,255,63,113,32,11,32,23,65,255,255,3,113,65,1,118,65,255,63,113,106,34,11,32,26,65,5,108,34,27,108,106,32,12,32,0,32,1,65,10,106,106,45,0,0,32,0,32,1,65,11,106,106,45,0,0,65,8,116,114,34,28,65,2,116,32,23,65,255,255,3,113,65,14,118,114,65,255,63,113,106,34,12,32,24,65,5,108,34,23,108,106,32,13,32,0,32,1,65,12,106,106,45,0,0,32,0,32,1,65,13,106,106,45,0,0,65,8,116,114,34,25,65,5,116,32,28,65,255,255,3,113,65,11,118,114,65,255,63,113,106,34,13,32,22,65,5,108,34,28,108,106,32,14,32,25,65,255,255,3,113,65,8,118,32,0,32,1,65,14,106,106,45,0,0,32,0,32,1,65,15,106,106,45,0,0,65,8,116,114,34,25,65,8,116,114,65,255,63,113,106,34,14,32,20,65,5,108,34,7,108,106,33,5,32,11,32,21,108,32,32,65,13,118,32,5,32,6,32,34,32,25,65,255,255,3,113,65,5,118,114,65,255,255,3,113,106,34,6,32,18,65,5,108,108,106,34,32,65,13,118,106,32,3,32,18,108,106,32,4,32,17,108,106,32,8,32,15,108,106,32,9,32,16,108,106,32,10,32,19,108,106,34,25,65,255,63,113,106,32,12,32,27,108,106,32,13,32,23,108,106,32,14,32,28,108,106,33,5,32,11,32,19,108,32,25,65,13,118,32,5,32,6,32,7,108,106,34,25,65,13,118,106,32,3,32,20,108,106,32,4,32,18,108,106,32,8,32,17,108,106,32,9,32,15,108,106,32,10,32,16,108,106,34,7,65,255,63,113,106,32,12,32,21,108,106,32,13,32,27,108,106,32,14,32,23,108,106,33,5,32,11,32,16,108,32,7,65,13,118,32,5,32,6,32,28,108,106,34,28,65,13,118,106,32,3,32,22,108,106,32,4,32,20,108,106,32,8,32,18,108,106,32,9,32,17,108,106,32,10,32,15,108,106,34,7,65,255,63,113,106,32,12,32,19,108,106,32,13,32,21,108,106,32,14,32,27,108,106,33,5,32,11,32,15,108,32,7,65,13,118,32,5,32,6,32,23,108,106,34,23,65,13,118,106,32,3,32,24,108,106,32,4,32,22,108,106,32,8,32,20,108,106,32,9,32,18,108,106,32,10,32,17,108,106,34,7,65,255,63,113,106,32,12,32,16,108,106,32,13,32,19,108,106,32,14,32,21,108,106,33,5,32,11,32,17,108,32,7,65,13,118,32,5,32,6,32,27,108,106,34,27,65,13,118,106,32,3,32,26,108,106,32,4,32,24,108,106,32,8,32,22,108,106,32,9,32,20,108,106,32,10,32,18,108,106,34,7,65,255,63,113,106,32,12,32,15,108,106,32,13,32,16,108,106,32,14,32,19,108,106,33,5,32,11,32,18,108,32,7,65,13,118,32,5,32,6,32,21,108,106,34,21,65,13,118,106,32,3,32,29,108,106,32,4,32,26,108,106,32,8,32,24,108,106,32,9,32,22,108,106,32,10,32,20,108,106,34,7,65,255,63,113,106,32,12,32,17,108,106,32,13,32,15,108,106,32,14,32,16,108,106,33,5,32,11,32,20,108,32,7,65,13,118,32,5,32,6,32,19,108,106,34,19,65,13,118,106,32,3,32,30,108,106,32,4,32,29,108,106,32,8,32,26,108,106,32,9,32,24,108,106,32,10,32,22,108,106,34,7,65,255,63,113,106,32,12,32,18,108,106,32,13,32,17,108,106,32,14,32,15,108,106,33,5,32,11,32,22,108,32,7,65,13,118,32,5,32,6,32,16,108,106,34,16,65,13,118,106,32,3,32,31,108,106,32,4,32,30,108,106,32,8,32,29,108,106,32,9,32,26,108,106,32,10,32,24,108,106,34,7,65,255,63,113,106,32,12,32,20,108,106,32,13,32,18,108,106,32,14,32,17,108,106,33,5,32,11,32,24,108,32,7,65,13,118,32,5,32,6,32,15,108,106,34,15,65,13,118,106,32,3,32,33,108,106,32,4,32,31,108,106,32,8,32,30,108,106,32,9,32,29,108,106,32,10,32,26,108,106,34,3,65,255,63,113,106,32,12,32,22,108,106,32,13,32,20,108,106,32,14,32,18,108,106,33,4,32,3,65,13,118,32,4,32,6,32,17,108,106,34,6,65,13,118,106,34,3,32,3,65,2,116,106,32,32,65,255,63,113,106,34,3,65,13,118,33,4,32,3,65,255,63,113,33,3,32,25,65,255,63,113,32,4,106,33,4,32,28,65,255,63,113,33,8,32,23,65,255,63,113,33,9,32,27,65,255,63,113,33,10,32,21,65,255,63,113,33,11,32,19,65,255,63,113,33,12,32,16,65,255,63,113,33,13,32,15,65,255,63,113,33,14,32,6,65,255,63,113,33,6,32,1,65,16,106,33,1,32,2,65,16,107,33,2,12,1,11,11,35,29,32,3,59,1,0,35,29,65,2,106,32,4,59,1,0,35,29,65,4,106,32,8,59,1,0,35,29,65,6,106,32,9,59,1,0,35,29,65,8,106,32,10,59,1,0,35,29,65,10,106,32,11,59,1,0,35,29,65,12,106,32,12,59,1,0,35,29,65,14,106,32,13,59,1,0,35,29,65,16,106,32,14,59,1,0,35,29,65,18,106,32,6,59,1,0,11,203,1,1,3,127,35,32,4,64,65,16,35,32,107,34,3,32,1,75,4,64,32,1,33,3,11,3,64,32,2,32,3,73,4,64,35,25,32,2,35,32,106,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,32,3,107,33,1,32,3,33,4,32,3,35,32,106,36,32,35,32,65,16,73,4,64,15,11,35,25,65,0,65,16,16,18,65,0,36,32,11,2,127,32,1,65,16,79,4,64,32,0,32,4,32,1,32,1,65,15,113,107,34,3,16,18,32,3,32,4,106,33,4,32,1,32,3,107,33,1,11,32,1,11,4,64,65,0,33,2,3,64,32,2,32,1,73,4,64,35,25,32,2,35,32,106,106,32,0,32,2,32,4,106,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,35,32,106,36,32,11,11,8,0,35,22,32,0,16,19,11,149,9,1,3,127,35,32,4,64,35,32,34,1,35,25,106,65,1,58,0,0,32,1,65,1,106,33,1,3,64,32,1,65,16,73,4,64,32,1,35,25,106,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,65,1,36,33,35,25,65,0,65,16,16,18,11,35,29,65,2,106,47,1,0,65,13,118,33,2,35,29,65,2,106,35,29,65,2,106,47,1,0,65,255,63,113,59,1,0,65,2,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,29,106,32,2,32,3,35,29,106,47,1,0,106,59,1,0,32,3,35,29,106,47,1,0,65,13,118,33,2,32,3,35,29,106,32,3,35,29,106,47,1,0,65,255,63,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,29,47,1,0,32,2,65,5,108,106,59,1,0,35,29,47,1,0,33,1,35,29,35,29,47,1,0,65,255,63,113,59,1,0,35,29,65,2,106,35,29,65,2,106,47,1,0,32,1,65,255,255,3,113,65,13,118,106,59,1,0,35,29,65,2,106,47,1,0,33,1,35,29,65,2,106,35,29,65,2,106,47,1,0,65,255,63,113,59,1,0,35,29,65,4,106,35,29,65,4,106,47,1,0,32,1,65,255,255,3,113,65,13,118,106,59,1,0,35,36,35,29,47,1,0,65,5,106,59,1,0,35,36,47,1,0,65,13,118,33,2,35,36,35,36,47,1,0,65,255,63,113,59,1,0,65,1,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,36,106,32,2,32,3,35,29,106,47,1,0,106,59,1,0,32,3,35,36,106,47,1,0,65,13,118,33,2,32,3,35,36,106,32,3,35,36,106,47,1,0,65,255,63,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,36,65,18,106,35,36,65,18,106,47,1,0,65,128,64,106,59,1,0,32,2,65,1,115,65,1,107,33,2,65,0,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,36,106,32,2,32,3,35,36,106,47,1,0,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,32,2,65,127,115,33,3,65,0,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,2,35,29,106,32,2,35,36,106,47,1,0,32,3,32,2,35,29,106,47,1,0,113,114,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,29,47,1,0,35,29,65,2,106,47,1,0,65,13,116,114,59,1,0,35,29,65,2,106,35,29,65,4,106,47,1,0,65,10,116,35,29,65,2,106,47,1,0,65,3,118,114,59,1,0,35,29,65,4,106,35,29,65,6,106,47,1,0,65,7,116,35,29,65,4,106,47,1,0,65,6,118,114,59,1,0,35,29,65,6,106,35,29,65,8,106,47,1,0,65,4,116,35,29,65,6,106,47,1,0,65,9,118,114,59,1,0,35,29,65,8,106,35,29,65,10,106,47,1,0,65,1,116,35,29,65,8,106,47,1,0,65,12,118,114,35,29,65,12,106,47,1,0,65,14,116,114,59,1,0,35,29,65,10,106,35,29,65,14,106,47,1,0,65,11,116,35,29,65,12,106,47,1,0,65,2,118,114,59,1,0,35,29,65,12,106,35,29,65,16,106,47,1,0,65,8,116,35,29,65,14,106,47,1,0,65,5,118,114,59,1,0,35,29,65,14,106,35,29,65,18,106,47,1,0,65,5,116,35,29,65,16,106,47,1,0,65,8,118,114,59,1,0,35,29,35,29,47,1,0,35,31,47,1,0,106,34,2,59,1,0,65,1,33,1,3,64,32,1,65,8,73,4,64,32,1,65,1,116,34,3,35,29,106,47,1,0,32,3,35,31,106,47,1,0,106,32,2,65,16,118,106,33,2,35,29,32,3,106,32,2,59,1,0,32,1,65,1,106,33,1,12,1,11,11,32,0,35,29,47,1,0,58,0,0,32,0,65,1,106,35,29,47,1,0,65,8,118,58,0,0,32,0,65,2,106,35,29,65,2,106,47,1,0,58,0,0,32,0,65,3,106,35,29,65,2,106,47,1,0,65,8,118,58,0,0,32,0,65,4,106,35,29,65,4,106,47,1,0,58,0,0,32,0,65,5,106,35,29,65,4,106,47,1,0,65,8,118,58,0,0,32,0,65,6,106,35,29,65,6,106,47,1,0,58,0,0,32,0,65,7,106,35,29,65,6,106,47,1,0,65,8,118,58,0,0,32,0,65,8,106,35,29,65,8,106,47,1,0,58,0,0,32,0,65,9,106,35,29,65,8,106,47,1,0,65,8,118,58,0,0,32,0,65,10,106,35,29,65,10,106,47,1,0,58,0,0,32,0,65,11,106,35,29,65,10,106,47,1,0,65,8,118,58,0,0,32,0,65,12,106,35,29,65,12,106,47,1,0,58,0,0,32,0,65,13,106,35,29,65,12,106,47,1,0,65,8,118,58,0,0,32,0,65,14,106,35,29,65,14,106,47,1,0,58,0,0,32,0,65,15,106,35,29,65,14,106,47,1,0,65,8,118,58,0,0,65,1,36,34,11,11,0,32,0,32,1,65,1,116,16,3,11,38,0,35,25,65,16,16,13,35,27,65,10,16,22,35,29,65,10,16,22,35,31,65,8,16,22,65,0,36,32,65,0,36,33,65,0,36,34,11,33,1,1,127,35,23,33,0,35,34,4,64,65,144,2,65,208,2,65,226,3,65,4,16,0,0,11,32,0,16,21,16,23,11,39,1,1,127,3,64,32,0,65,32,73,4,64,32,0,35,7,106,65,0,58,0,0,32,0,65,1,106,33,0,12,1,11,11,65,32,16,15,26,11,152,2,1,1,127,3,64,32,4,65,32,72,4,64,32,4,35,9,106,32,0,32,4,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,65,0,33,4,3,64,32,4,65,4,72,4,64,32,4,35,11,106,65,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,65,4,33,4,3,64,32,4,65,16,72,4,64,32,4,35,11,106,32,1,32,4,65,4,107,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,16,25,65,0,33,4,3,64,32,4,65,32,72,4,64,32,4,35,21,106,32,4,35,13,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,35,21,16,16,32,3,65,0,75,4,64,65,0,33,4,3,64,32,4,32,3,73,4,64,32,4,35,22,106,32,2,32,4,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,32,3,16,20,32,3,65,15,113,65,0,75,4,64,65,16,32,3,65,15,113,107,34,1,65,0,74,4,64,65,0,33,0,3,64,32,0,32,1,72,4,64,32,0,35,22,106,65,0,58,0,0,32,0,65,1,106,33,0,12,1,11,11,32,1,16,20,11,11,11,11,65,1,1,127,3,64,32,2,32,1,73,4,64,35,22,32,2,106,32,0,32,2,106,45,0,0,58,0,0,35,7,32,2,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,20,32,1,16,15,26,11,27,0,32,0,32,1,65,0,16,10,32,0,173,66,128,128,128,128,16,127,167,32,1,65,4,16,10,11,87,1,2,127,32,0,65,15,113,65,0,75,4,64,65,16,32,0,65,15,113,107,34,3,65,0,74,4,64,3,64,32,2,32,3,72,4,64,32,2,35,22,106,65,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,3,16,20,11,11,32,1,35,22,16,28,65,8,16,20,32,0,35,22,16,28,65,8,16,20,16,24,11,34,0,32,0,4,64,35,38,35,40,35,42,32,4,16,26,11,35,44,32,2,16,27,32,1,4,64,32,3,32,4,16,29,11,11,89,1,1,127,3,64,32,2,32,1,73,4,64,35,7,32,2,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,15,26,65,0,33,2,3,64,32,2,32,1,73,4,64,35,22,32,2,106,32,2,35,13,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,20,11,34,0,32,0,4,64,35,38,35,40,35,42,32,4,16,26,11,35,44,32,2,16,31,32,1,4,64,32,3,32,4,16,29,11,11,8,0,16,5,16,8,16,9,11,11,234,2,6,0,65,16,11,43,28,0,0,0,1,0,0,0,1,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,192,0,11,53,38,0,0,0,1,0,0,0,1,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,128,1,11,63,48,0,0,0,1,0,0,0,1,0,0,0,48,0,0,0,67,0,104,0,97,0,67,0,104,0,97,0,58,0,32,0,99,0,111,0,117,0,110,0,116,0,101,0,114,0,32,0,111,0,118,0,101,0,114,0,102,0,108,0,111,0,119,0,65,192,1,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,99,0,104,0,97,0,99,0,104,0,97,0,50,0,48,0,46,0,116,0,115,0,65,128,2,11,57,42,0,0,0,1,0,0,0,1,0,0,0,42,0,0,0,80,0,111,0,108,0,121,0,49,0,51,0,48,0,53,0,32,0,119,0,97,0,115,0,32,0,102,0,105,0,110,0,105,0,115,0,104,0,101,0,100,0,65,192,2,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,112,0,111,0,108,0,121,0,49,0,51,0,48,0,53,0,46,0,116,0,115])});var Fb=mt(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});zp.newInstance=void 0;var vz=g8(),Ez=new WebAssembly.Module(vz.wasmCode),Sz={env:{abort:function(r,e,t,n){throw Error(`abort: ${r}:${e}:${t}:${n}`)}}};function Iz(){return new WebAssembly.Instance(Ez,Sz).exports}zp.newInstance=Iz});var w8=mt($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});$p.chacha20StreamXOR=void 0;var Az=Fb(),Jr=Az.newInstance(),Cz=Jr.chacha20Input.value,Tz=Jr.chacha20Output.value,_z=Jr.chacha20Key.value,Pz=Jr.chacha20Counter.value,{CHACHA20_INPUT_LENGTH:fa,KEY_LENGTH:zb,CHACHA20_COUNTER_LENGTH:b8}=Jr,Dz=new Uint8Array(Jr.memory.buffer,Cz,fa),y8=new Uint8Array(Jr.memory.buffer,Tz,fa),kz=new Uint8Array(Jr.memory.buffer,_z,zb),Lz=new Uint8Array(Jr.memory.buffer,Pz,b8);function Mz(r,e,t){if(r.length!=zb)throw new Error("ChaCha: key size must be 32 bytes, expected "+zb+" got "+r.length);if(e.length!=b8)throw new Error("ChaCha nonce with counter must be 16 bytes");kz.set(r),Lz.set(e);let n=new Uint8Array(t.length),s=Math.floor(t.length/fa);for(let o=0;o<=s;o++){let i=o*fa,a=Math.min((o+1)*fa,t.length);Dz.set(s===0?t:t.subarray(i,a));let c=a-i,l=Jr.chacha20StreamXORUpdate(c);n.set(l===fa?y8:y8.subarray(0,l),i)}return n}$p.chacha20StreamXOR=Mz});var x8=mt(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.newInstance=Zr.chacha20StreamXOR=Zr.Poly1305=Zr.ChaCha20Poly1305=void 0;var Oz=p8();Object.defineProperty(Zr,"ChaCha20Poly1305",{enumerable:!0,get:function(){return Oz.ChaCha20Poly1305}});var Rz=m8();Object.defineProperty(Zr,"Poly1305",{enumerable:!0,get:function(){return Rz.Poly1305}});var Nz=w8();Object.defineProperty(Zr,"chacha20StreamXOR",{enumerable:!0,get:function(){return Nz.chacha20StreamXOR}});var Bz=Fb();Object.defineProperty(Zr,"newInstance",{enumerable:!0,get:function(){return Bz.newInstance}})});var T8=mt((e4e,C8)=>{function jz(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}C8.exports=jz});var AT=mt((J8e,IT)=>{"use strict";function Me(r,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(r)?this._fromArray(r):(this._capacityMask=3,this._list=new Array(4))}Me.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}};Me.prototype.get=function(e){return this.peekAt(e)};Me.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};Me.prototype.peekFront=function(){return this.peek()};Me.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(Me.prototype,"length",{get:function(){return this.size()}});Me.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Me.prototype.unshift=function(e){if(arguments.length===0)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Me.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};Me.prototype.push=function(e){if(arguments.length===0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Me.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var n=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),n}};Me.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var n=this.size(),s=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o=this._list[t],i;if(e<n/2){for(i=e;i>0;i--)this._list[t]=this._list[t=t-1+s&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+s&this._capacityMask}else{for(i=n-1-e;i>0;i--)this._list[t]=this._list[t=t+1+s&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+s&this._capacityMask}return o}}};Me.prototype.remove=function(e,t){var n=e,s,o=t;if(n===(n|0)&&this._head!==this._tail){var i=this.size(),a=this._list.length;if(!(n>=i||n<-i||t<1)){if(n<0&&(n+=i),t===1||!t)return s=new Array(1),s[0]=this.removeOne(n),s;if(n===0&&n+t>=i)return s=this.toArray(),this.clear(),s;n+t>i&&(t=i-n);var c;for(s=new Array(t),c=0;c<t;c++)s[c]=this._list[this._head+n+c&this._capacityMask];if(n=this._head+n&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return s}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[n=n+1+a&this._capacityMask]=void 0;return s}if(n<i/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[n=n-1+a&this._capacityMask]);for(n=this._head-1+a&this._capacityMask;o>0;)this._list[n=n-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=n)}else{for(this._tail=n,n=n+t+a&this._capacityMask,c=i-(t+e);c>0;c--)this.push(this._list[n++]);for(n=this._tail;o>0;)this._list[n=n+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),s}}};Me.prototype.splice=function(e,t){var n=e;if(n===(n|0)){var s=this.size();if(n<0&&(n+=s),!(n>s))if(arguments.length>2){var o,i,a,c=arguments.length,l=this._list.length,u=2;if(!s||n<s/2){for(i=new Array(n),o=0;o<n;o++)i[o]=this._list[this._head+o&this._capacityMask];for(t===0?(a=[],n>0&&(this._head=this._head+n+l&this._capacityMask)):(a=this.remove(n,t),this._head=this._head+n+l&this._capacityMask);c>u;)this.unshift(arguments[--c]);for(o=n;o>0;o--)this.unshift(i[o-1])}else{i=new Array(s-(n+t));var d=i.length;for(o=0;o<d;o++)i[o]=this._list[this._head+n+t+o&this._capacityMask];for(t===0?(a=[],n!=s&&(this._tail=this._head+n+l&this._capacityMask)):(a=this.remove(n,t),this._tail=this._tail-d+l&this._capacityMask);u<c;)this.push(arguments[u++]);for(o=0;o<d;o++)this.push(i[o])}return a}else return this.remove(n,t)}};Me.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};Me.prototype.isEmpty=function(){return this._head===this._tail};Me.prototype.toArray=function(){return this._copyArray(!1)};Me.prototype._fromArray=function(e){var t=e.length,n=this._nextPowerOf2(t);this._list=new Array(n),this._capacityMask=n-1,this._tail=t;for(var s=0;s<t;s++)this._list[s]=e[s]};Me.prototype._copyArray=function(e,t){var n=this._list,s=n.length,o=this.length;if(t=t|o,t==o&&this._head<this._tail)return this._list.slice(this._head,this._tail);var i=new Array(t),a=0,c;if(e||this._head>this._tail){for(c=this._head;c<s;c++)i[a++]=n[c];for(c=0;c<this._tail;c++)i[a++]=n[c]}else for(c=this._head;c<this._tail;c++)i[a++]=n[c];return i};Me.prototype._growArray=function(){if(this._head!=0){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1};Me.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};Me.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),n=1<<t+1;return Math.max(n,4)};IT.exports=Me});var yG={};z(yG,{ArachnodeFretAdapter:()=>ml,BlockStorage:()=>yi,ClusterClient:()=>Ks,ClusterCoordinator:()=>$c,ClusterMember:()=>Wh,ClusterService:()=>jh,CoordinatorRepo:()=>Yh,Libp2pKeyPeerNetwork:()=>Sl,MemoryRawStorage:()=>Hc,NetworkManagerService:()=>z1,ProtocolClient:()=>un,RepoClient:()=>z2,RepoService:()=>Qh,RestorationCoordinator:()=>dl,RingSelector:()=>fl,SYNC_PROTOCOL_PREFIX:()=>KE,SYNC_PROTOCOL_VERSION:()=>FE,StorageMonitor:()=>pl,StorageRepo:()=>qc,SyncClient:()=>js,SyncService:()=>_d,asyncIteratorToArray:()=>Ha,buildKnownPeers:()=>pG,buildSyncProtocol:()=>hl,clusterMember:()=>K2,clusterService:()=>F2,computeResponsibility:()=>fG,coordinatorRepo:()=>$2,createLibp2pNode:()=>dG,first:()=>Z1,getNetworkManager:()=>gG,lessThanLex:()=>i_,networkManagerService:()=>_6,reduce:()=>P_,repoService:()=>H2,sortPeersByDistance:()=>a_,syncService:()=>ey,xorDistanceBytes:()=>o_});function tt(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ru=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},ko=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ru(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Ru(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var H1=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function It(r={}){return p_(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function p_(r,e){e=e??{};let t=e.onEnd,n=new ko,s,o,i,a=tt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{o=b=>{o=null,n.push(b);try{g(r(n))}catch(E){y(E)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=tt()})}},l=g=>o!=null?o(g):(n.push(g),s),u=g=>(n=new ko,o!=null?o({error:g}):(n.push({error:g}),s)),d=g=>{if(i)return s;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},p=g=>i?s:(i=!0,g!=null?u(g):l({done:!0})),f=()=>(n=new ko,p(),{done:!0}),h=g=>(p(g),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:f,throw:h,push:d,end:p,get readableLength(){return n.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let b,E;y!=null&&(b=new Promise((x,v)=>{E=()=>{v(new H1)},y.addEventListener("abort",E)}));try{await Promise.race([a.promise,b])}finally{E!=null&&y!=null&&y?.removeEventListener("abort",E)}}},t==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(g){return m.end(g),t!=null&&(t(g),t=void 0),s},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},s}var Nu=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Bu(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Nu(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new Nu(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var q1=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=tt(),this.haveNext=tt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=tt(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=tt(),await Bu(this.readNext.promise,t?.signal,t)}};function O6(){return new q1}function m_(r){return r[Symbol.asyncIterator]!=null}async function g_(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*y_(r){let e=new AbortController,t=O6();g_(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*b_(r){for(let e of r)yield*e}function w_(...r){let e=[];for(let t of r)m_(t)||e.push(t);return e.length===r.length?b_(e):y_(r)}var Ss=w_;function rt(r,...e){if(r==null)throw new Error("Empty pipeline");if(V1(r)){let n=r;r=()=>n.source}else if(N6(r)||R6(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&V1(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)V1(t[n])&&(t[n]=v_(t[n]));return x_(...t)}var x_=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},R6=r=>r?.[Symbol.asyncIterator]!=null,N6=r=>r?.[Symbol.iterator]!=null,V1=r=>r==null?!1:r.sink!=null&&r.source!=null,v_=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=It({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(R6(o))s=async function*(){yield*o,n.end()};else if(N6(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ss(n,s())}return r.source};var G1=Z("node:buffer");function Kn(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function se(r=0){return Kn(G1.Buffer.alloc(r))}function We(r=0){return Kn(G1.Buffer.allocUnsafe(r))}var E_=Math.pow(2,7),S_=Math.pow(2,14),I_=Math.pow(2,21),W1=Math.pow(2,28),j1=Math.pow(2,35),Y1=Math.pow(2,42),X1=Math.pow(2,49),we=128,gt=127;function ve(r){if(r<E_)return 1;if(r<S_)return 2;if(r<I_)return 3;if(r<W1)return 4;if(r<j1)return 5;if(r<Y1)return 6;if(r<X1)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function cn(r,e,t=0){switch(ve(r)){case 8:e[t++]=r&255|we,r/=128;case 7:e[t++]=r&255|we,r/=128;case 6:e[t++]=r&255|we,r/=128;case 5:e[t++]=r&255|we,r/=128;case 4:e[t++]=r&255|we,r>>>=7;case 3:e[t++]=r&255|we,r>>>=7;case 2:e[t++]=r&255|we,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function A_(r,e,t=0){switch(ve(r)){case 8:e.set(t++,r&255|we),r/=128;case 7:e.set(t++,r&255|we),r/=128;case 6:e.set(t++,r&255|we),r/=128;case 5:e.set(t++,r&255|we),r/=128;case 4:e.set(t++,r&255|we),r>>>=7;case 3:e.set(t++,r&255|we),r>>>=7;case 2:e.set(t++,r&255|we),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Q1(r,e){let t=r[e],n=0;if(n+=t&gt,t<we||(t=r[e+1],n+=(t&gt)<<7,t<we)||(t=r[e+2],n+=(t&gt)<<14,t<we)||(t=r[e+3],n+=(t&gt)<<21,t<we)||(t=r[e+4],n+=(t&gt)*W1,t<we)||(t=r[e+5],n+=(t&gt)*j1,t<we)||(t=r[e+6],n+=(t&gt)*Y1,t<we)||(t=r[e+7],n+=(t&gt)*X1,t<we))return n;throw new RangeError("Could not decode varint")}function C_(r,e){let t=r.get(e),n=0;if(n+=t&gt,t<we||(t=r.get(e+1),n+=(t&gt)<<7,t<we)||(t=r.get(e+2),n+=(t&gt)<<14,t<we)||(t=r.get(e+3),n+=(t&gt)<<21,t<we)||(t=r.get(e+4),n+=(t&gt)*W1,t<we)||(t=r.get(e+5),n+=(t&gt)*j1,t<we)||(t=r.get(e+6),n+=(t&gt)*Y1,t<we)||(t=r.get(e+7),n+=(t&gt)*X1,t<we))return n;throw new RangeError("Could not decode varint")}function Dr(r,e,t=0){return e==null&&(e=We(ve(r))),e instanceof Uint8Array?cn(r,e,t):A_(r,e,t)}function Bt(r,e=0){return r instanceof Uint8Array?Q1(r,e):C_(r,e)}var B6=Z("node:buffer");function be(r,e){return Kn(B6.Buffer.concat(r,e))}function V(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var K6=Symbol.for("@achingbrain/uint8arraylist");function U6(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Uu(r){return!!r?.[K6]}var B=class r{bufs;length;[K6]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Uu(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Uu(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=U6(this.bufs,e);return t.buf[t.index]}set(e,t){let n=U6(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Uu(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return be(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:be(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Uu(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let d=0;d<o;d++)i[d]=-1;for(let d=0;d<s;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let p=l;p>=0;p--){let f=this.get(d+p);if(n[p]!==f){u=Math.max(1,p-a[f]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=We(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=se(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=se(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=se(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=We(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=se(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=se(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=se(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=se(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=se(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!V(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var Ku=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Lo=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Fu=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},$a=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function zu(r){return r[Symbol.asyncIterator]!=null}function F6(r,e){if(r.byteLength>e)throw new Lo("Message length too long")}var Hu=r=>{let e=ve(r),t=We(e);return Dr(r,t),Hu.bytes=e,t};Hu.bytes=0;function or(r,e){e=e??{};let t=e.lengthEncoder??Hu,n=e?.maxDataLength??4194304;function*s(o){F6(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return zu(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}or.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Hu,n=e?.maxDataLength??4194304;return F6(r,n),new B(t(r.byteLength),r)};var Is;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Is||(Is={}));var J1=r=>{let e=Bt(r);return J1.bytes=ve(e),e};J1.bytes=0;function gr(r,e){let t=new B,n=Is.LENGTH,s=-1,o=e?.lengthDecoder??J1,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Is.LENGTH)try{if(s=o(t),s<0)throw new Ku("Invalid message length");if(s>a)throw new Lo("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Is.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Fu("Message length length too long");break}throw l}if(n===Is.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Is.LENGTH}}}return zu(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new $a("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new $a("Unexpected end of input")})()}gr.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return gr(n,{...e??{},onLength:o=>{t=o}})};async function Z1(r,e=()=>{throw new Error("No items found")},t){let n=new AbortController,s=typeof t=="number"?setTimeout(()=>n.abort(),t):void 0;try{for await(let o of r(n.signal))return o;return e()}finally{s!==void 0&&clearTimeout(s),n.abort()}}async function Ha(r){let e=[];for await(let t of r)e.push(t);return e}function P_(r,e,t){let n=t,s=0;for(let o of r)n=e(n,o,s),++s;return n}var un=class{peerId;peerNetwork;constructor(e,t){this.peerId=e,this.peerNetwork=t}async processMessage(e,t,n){let s=await this.peerNetwork.connect(this.peerId,t,{signal:n?.signal});try{let o=rt([new TextEncoder().encode(JSON.stringify(e))],or);for await(let a of o)s.send(a);let i=rt(s,gr,async function*(a){for await(let c of a){let l=new TextDecoder().decode(c.subarray());yield JSON.parse(l)}});return await Z1(()=>i,()=>{throw new Error("No response received")})}finally{await s.close()}}};var z6=Symbol.for("@libp2p/connection");var em=Symbol.for("@libp2p/content-routing");var Vt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},qu=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Vu=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},N=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Mo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},qa=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var As=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var hn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Gu=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var Fn=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Va=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},Cs=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Oo=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},zn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Wu=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},ju=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Yu=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},At=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},Xu=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},kr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},yr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},Qu=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}},$n=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Ts=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},Ga=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Ju=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Ro=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Hn=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Zu=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},qn=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},eh=class extends qn{constructor(e,t){super(!0,e,t)}},th=class extends qn{constructor(e,t){super(!1,e,t)}};var Wa=Symbol.for("@libp2p/peer-discovery");var rh=Symbol.for("@libp2p/peer-id");function Vn(r){return!!r?.[rh]}var tm=Symbol.for("@libp2p/peer-routing");var ja="keep-alive";function nh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function sh(...r){let e=[];for(let t of r)nh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function oh(...r){let e=[];for(let t of r)nh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var ih=Symbol.for("@libp2p/transport");var Ya;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ya||(Ya={}));var $6=Z("node:events"),W=(r,...e)=>{try{(0,$6.setMaxListeners)(r,...e)}catch{}};var he=class extends EventTarget{#e=new Map;constructor(){super(),W(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var je=Symbol.for("@libp2p/service-capabilities"),Xa=Symbol.for("@libp2p/service-dependencies");var YW=new Uint8Array(0);function H6(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Gn(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function D_(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var k_=D_,L_=k_,q6=L_;var rm=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},nm=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 V6(this,e)}},sm=class{decoders;constructor(e){this.decoders=e}or(e){return V6(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function V6(r,e){return new sm({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var om=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new rm(e,t,n),this.decoder=new nm(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function G6({name:r,prefix:e,encode:t,decode:n}){return new om(r,e,t,n)}function No({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=q6(t,r);return G6({prefix:e,name:r,encode:n,decode:o=>Gn(s(o))})}function M_(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function O_(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function R_(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Lr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=R_(n);return G6({prefix:e,name:r,encode(o){return O_(o,n,t)},decode(o){return M_(o,s,t,r)}})}var lt=No({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rj=No({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qa=Lr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),oj=Lr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ij=Lr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),aj=Lr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),cj=Lr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),lj=Lr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),uj=Lr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hj=Lr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),dj=Lr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ah=No({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),mj=No({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var N_=Y6,W6=128,B_=127,U_=~B_,K_=Math.pow(2,31);function Y6(r,e,t){e=e||[],t=t||0;for(var n=t;r>=K_;)e[t++]=r&255|W6,r/=128;for(;r&U_;)e[t++]=r&255|W6,r>>>=7;return e[t]=r|0,Y6.bytes=t-n+1,e}var F_=im,z_=128,j6=127;function im(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw im.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&j6)<<s:(i&j6)*Math.pow(2,s),s+=7}while(i>=z_);return im.bytes=o-n,t}var $_=Math.pow(2,7),H_=Math.pow(2,14),q_=Math.pow(2,21),V_=Math.pow(2,28),G_=Math.pow(2,35),W_=Math.pow(2,42),j_=Math.pow(2,49),Y_=Math.pow(2,56),X_=Math.pow(2,63),Q_=function(r){return r<$_?1:r<H_?2:r<q_?3:r<V_?4:r<G_?5:r<W_?6:r<j_?7:r<Y_?8:r<X_?9:10},J_={encode:N_,decode:F_,encodingLength:Q_},Z_=J_,Ja=Z_;function Za(r,e=0){return[Ja.decode(r,e),Ja.decode.bytes]}function Bo(r,e,t=0){return Ja.encode(r,e,t),e}function Uo(r){return Ja.encodingLength(r)}function Wn(r,e){let t=e.byteLength,n=Uo(r),s=n+Uo(t),o=new Uint8Array(s+t);return Bo(r,o,0),Bo(t,o,n),o.set(e,s),new Ko(r,t,e,o)}function Q6(r){let e=Gn(r),[t,n]=Za(e),[s,o]=Za(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ko(t,s,i,e)}function J6(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&H6(r.bytes,t.bytes)}}var Ko=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function e5(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return tP(t,am(r),e??lt.encoder);default:return rP(t,am(r),e??Qa.encoder)}}var t5=new WeakMap;function am(r){let e=t5.get(r);if(e==null){let t=new Map;return t5.set(r,t),t}return e}var Mr=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==ec)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==nP)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Wn(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&J6(e.multihash,n.multihash)}toString(e){return e5(this,e)}toJSON(){return{"/":e5(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??r5(n,s,o.bytes))}else if(t[sP]===!0){let{version:n,multihash:s,code:o}=t,i=Q6(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ec)throw new Error(`Version 0 CID must use dag-pb (code: ${ec}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=r5(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ec,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Gn(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Ko(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=Za(e.subarray(t));return t+=p,d},s=n(),o=ec;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=eP(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return am(o).set(n,e),o}};function eP(r,e){switch(r[0]){case"Q":{let t=e??lt;return[lt.prefix,t.decode(`${lt.prefix}${r}`)]}case lt.prefix:{let t=e??lt;return[lt.prefix,t.decode(r)]}case Qa.prefix:{let t=e??Qa;return[Qa.prefix,t.decode(r)]}case ah.prefix:{let t=e??ah;return[ah.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function tP(r,e,t){let{prefix:n}=t;if(n!==lt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function rP(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var ec=112,nP=18;function r5(r,e,t){let n=Uo(r),s=n+Uo(e),o=new Uint8Array(s+t.byteLength);return Bo(r,o,0),Bo(e,o,n),o.set(t,s),o}var sP=Symbol.for("@ipld/js-cid/CID");var n5=0,oP="identity",s5=Gn;function iP(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Wn(n5,s5(r))}var Fo={code:n5,name:oP,encode:s5,digest:iP};var C5=Z("node:buffer");var dm={};z(dm,{base10:()=>fP});var _j=new Uint8Array(0);function o5(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ir(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function i5(r){return new TextEncoder().encode(r)}function a5(r){return new TextDecoder().decode(r)}function aP(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var cP=aP,lP=cP,l5=lP;var cm=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},lm=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 u5(this,e)}},um=class{decoders;constructor(e){this.decoders=e}or(e){return u5(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function u5(r,e){return new um({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var hm=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new cm(e,t,n),this.decoder=new lm(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function zo({name:r,prefix:e,encode:t,decode:n}){return new hm(r,e,t,n)}function jn({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=l5(t,r);return zo({prefix:e,name:r,encode:n,decode:o=>ir(s(o))})}function uP(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function hP(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function dP(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Oe({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=dP(n);return zo({prefix:e,name:r,encode(o){return hP(o,n,t)},decode(o){return uP(o,s,t,r)}})}var fP=jn({prefix:"9",name:"base10",alphabet:"0123456789"});var fm={};z(fm,{base16:()=>pP,base16upper:()=>mP});var pP=Oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),mP=Oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var pm={};z(pm,{base2:()=>gP});var gP=Oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var mm={};z(mm,{base256emoji:()=>vP});var h5=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}"),yP=h5.reduce((r,e,t)=>(r[t]=e,r),[]),bP=h5.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function wP(r){return r.reduce((e,t)=>(e+=yP[t],e),"")}function xP(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=bP[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var vP=zo({prefix:"\u{1F680}",name:"base256emoji",encode:wP,decode:xP});var gm={};z(gm,{base32:()=>$o,base32hex:()=>AP,base32hexpad:()=>TP,base32hexpadupper:()=>_P,base32hexupper:()=>CP,base32pad:()=>SP,base32padupper:()=>IP,base32upper:()=>EP,base32z:()=>PP});var $o=Oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),EP=Oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),SP=Oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),IP=Oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),AP=Oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),CP=Oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),TP=Oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),_P=Oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),PP=Oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ym={};z(ym,{base36:()=>tc,base36upper:()=>DP});var tc=jn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),DP=jn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var bm={};z(bm,{base58btc:()=>Or,base58flickr:()=>kP});var Or=jn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kP=jn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var wm={};z(wm,{base64:()=>LP,base64pad:()=>MP,base64url:()=>OP,base64urlpad:()=>RP});var LP=Oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),MP=Oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),OP=Oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),RP=Oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var xm={};z(xm,{base8:()=>NP});var NP=Oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vm={};z(vm,{identity:()=>BP});var BP=zo({prefix:"\0",name:"identity",encode:r=>a5(r),decode:r=>i5(r)});var qj=new TextEncoder,Vj=new TextDecoder;var Sm={};z(Sm,{identity:()=>iD});var FP=p5,d5=128,zP=127,$P=~zP,HP=Math.pow(2,31);function p5(r,e,t){e=e||[],t=t||0;for(var n=t;r>=HP;)e[t++]=r&255|d5,r/=128;for(;r&$P;)e[t++]=r&255|d5,r>>>=7;return e[t]=r|0,p5.bytes=t-n+1,e}var qP=Em,VP=128,f5=127;function Em(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Em.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&f5)<<s:(i&f5)*Math.pow(2,s),s+=7}while(i>=VP);return Em.bytes=o-n,t}var GP=Math.pow(2,7),WP=Math.pow(2,14),jP=Math.pow(2,21),YP=Math.pow(2,28),XP=Math.pow(2,35),QP=Math.pow(2,42),JP=Math.pow(2,49),ZP=Math.pow(2,56),eD=Math.pow(2,63),tD=function(r){return r<GP?1:r<WP?2:r<jP?3:r<YP?4:r<XP?5:r<QP?6:r<JP?7:r<ZP?8:r<eD?9:10},rD={encode:FP,decode:qP,encodingLength:tD},nD=rD,rc=nD;function nc(r,e=0){return[rc.decode(r,e),rc.decode.bytes]}function Ho(r,e,t=0){return rc.encode(r,e,t),e}function qo(r){return rc.encodingLength(r)}function Go(r,e){let t=e.byteLength,n=qo(r),s=n+qo(t),o=new Uint8Array(s+t);return Ho(r,o,0),Ho(t,o,n),o.set(e,s),new Vo(r,t,e,o)}function m5(r){let e=ir(r),[t,n]=nc(e),[s,o]=nc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Vo(t,s,i,e)}function g5(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&o5(r.bytes,t.bytes)}}var Vo=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var y5=0,sD="identity",b5=ir;function oD(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Go(y5,b5(r))}var iD={code:y5,name:sD,encode:b5,digest:oD};var Tm={};z(Tm,{sha256:()=>cD,sha512:()=>lD});var Cm=ne(Z("crypto"),1);var aD=20;function Am({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Im(r,e,t,n,s)}var Im=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??aD,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?w5(n,this.code,t?.truncate):n.then(s=>w5(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function w5(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Go(e,r)}var cD=Am({name:"sha2-256",code:18,encode:r=>ir(Cm.default.createHash("sha256").update(r).digest())}),lD=Am({name:"sha2-512",code:19,encode:r=>ir(Cm.default.createHash("sha512").update(r).digest())});function v5(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return hD(t,_m(r),e??Or.encoder);default:return dD(t,_m(r),e??$o.encoder)}}var E5=new WeakMap;function _m(r){let e=E5.get(r);if(e==null){let t=new Map;return E5.set(r,t),t}return e}var lh=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==oc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==fD)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Go(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&g5(e.multihash,n.multihash)}toString(e){return v5(this,e)}toJSON(){return{"/":v5(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??S5(n,s,o.bytes))}else if(t[pD]===!0){let{version:n,multihash:s,code:o}=t,i=m5(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==oc)throw new Error(`Version 0 CID must use dag-pb (code: ${oc}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=S5(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,oc,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=ir(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Vo(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=nc(e.subarray(t));return t+=p,d},s=n(),o=oc;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=uD(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return _m(o).set(n,e),o}};function uD(r,e){switch(r[0]){case"Q":{let t=e??Or;return[Or.prefix,t.decode(`${Or.prefix}${r}`)]}case Or.prefix:{let t=e??Or;return[Or.prefix,t.decode(r)]}case $o.prefix:{let t=e??$o;return[$o.prefix,t.decode(r)]}case tc.prefix:{let t=e??tc;return[tc.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function hD(r,e,t){let{prefix:n}=t;if(n!==Or.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function dD(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var oc=112,fD=18;function S5(r,e,t){let n=qo(r),s=n+qo(e),o=new Uint8Array(s+t.byteLength);return Ho(r,o,0),Ho(e,o,n),o.set(t,s),o}var pD=Symbol.for("@ipld/js-cid/CID");var Pm={...vm,...pm,...xm,...dm,...fm,...gm,...ym,...bm,...wm,...mm},pY={...Tm,...Sm};function A5(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var I5=A5("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Dm=A5("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=We(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),mD={utf8:I5,"utf-8":I5,hex:Pm.base16,latin1:Dm,ascii:Dm,binary:Dm,...Pm},uh=mD;function P(r,e="utf8"){let t=uh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?Kn(C5.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var T5=Z("node:buffer");function C(r,e="utf8"){let t=uh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?T5.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var gD=parseInt("11111",2),km=parseInt("10000000",2),yD=parseInt("01111111",2),_5={0:ic,1:ic,2:bD,3:vD,4:ED,5:xD,6:wD,16:ic,22:ic,48:ic};function dn(r,e={offset:0}){let t=r[e.offset]&gD;if(e.offset++,_5[t]!=null)return _5[t](r,e);throw new Error("No decoder for tag "+t)}function ac(r,e){let t=0;if((r[e.offset]&km)===km){let n=r[e.offset]&yD,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function ic(r,e){ac(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=dn(r,e);if(n===null)break;t.push(n)}return t}function bD(r,e){let t=ac(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function wD(r,e){let t=ac(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function xD(r,e){return e.offset++,null}function vD(r,e){let t=ac(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function ED(r,e){let t=ac(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function SD(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new B;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function hh(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=SD(r.byteLength);return new B(Uint8Array.from([e.byteLength|km]),e)}function Ct(r){let e=new B,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new B(Uint8Array.from([2]),hh(e),e)}function cc(r){let e=Uint8Array.from([0]),t=new B(e,r);return new B(Uint8Array.from([3]),hh(t),t)}function P5(r){return new B(Uint8Array.from([4]),hh(r),r)}function br(r,e=48){let t=new B;for(let n of r)t.append(n);return new B(Uint8Array.from([e]),hh(t),t)}async function D5(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function k5(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function L5(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var ID=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),AD=Uint8Array.from([6,5,43,129,4,0,34]),CD=Uint8Array.from([6,5,43,129,4,0,35]),TD={ext:!0,kty:"EC",crv:"P-256"},_D={ext:!0,kty:"EC",crv:"P-384"},PD={ext:!0,kty:"EC",crv:"P-521"},Lm=32,Mm=48,Om=66;function Rm(r){let e=dn(r);return M5(e)}function M5(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===Lm*2+1)return n=C(e.subarray(t,t+Lm),"base64url"),s=C(e.subarray(t+Lm),"base64url"),new _s({...TD,key_ops:["verify"],x:n,y:s});if(e.byteLength===Mm*2+1)return n=C(e.subarray(t,t+Mm),"base64url"),s=C(e.subarray(t+Mm),"base64url"),new _s({..._D,key_ops:["verify"],x:n,y:s});if(e.byteLength===Om*2+1)return n=C(e.subarray(t,t+Om),"base64url"),s=C(e.subarray(t+Om),"base64url"),new _s({...PD,key_ops:["verify"],x:n,y:s});throw new N(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function O5(r){return br([Ct(Uint8Array.from([1])),P5(P(r.d??"","base64url")),br([N5(r.crv)],160),br([cc(new B(Uint8Array.from([4]),P(r.x??"","base64url"),P(r.y??"","base64url")))],161)]).subarray()}function R5(r){return br([Ct(Uint8Array.from([1])),br([N5(r.crv)],160),br([cc(new B(Uint8Array.from([4]),P(r.x??"","base64url"),P(r.y??"","base64url")))],161)]).subarray()}function N5(r){if(r==="P-256")return ID;if(r==="P-384")return AD;if(r==="P-521")return CD;throw new N(`Invalid curve ${r}`)}async function B5(r="P-256"){let e=await D5(r);return new dh(e.privateKey)}var _s=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=R5(this.jwk)),this._raw}toMultihash(){return Fo.digest(nt(this))}toCID(){return Mr.createV1(114,this.toMultihash())}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}async verify(e,t,n){return L5(this.jwk,t,e,n)}},dh=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new _s({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=O5(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}async sign(e,t){return k5(this.jwk,e,t)}};var Ps=ne(Z("crypto"),1);var DD=Ps.default.generateKeyPairSync,lc=32,fh=64,kD=32,LD=64;function MD(r){let t=Ps.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",x:"",d:C(r,"base64url"),kty:"OKP"}}).export({format:"jwk"});if(t.x==null||t.x==="")throw new Error("Could not export JWK public key");return P(t.x,"base64url")}function U5(){let r=DD("ed25519",{publicKeyEncoding:{type:"spki",format:"jwk"},privateKeyEncoding:{type:"pkcs8",format:"jwk"}}),e=P(r.privateKey.d,"base64url"),t=P(r.publicKey.x,"base64url");return{privateKey:be([e,t],e.byteLength+t.byteLength),publicKey:t}}function K5(r,e){if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');let t,n;if(r.byteLength===fh)t=r.subarray(0,32),n=r.subarray(32);else if(r.byteLength===kD)t=r.subarray(0,32),n=MD(t);else throw new TypeError('"key" must be 64 or 32 bytes in length.');let s=Ps.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",d:C(t,"base64url"),x:C(n,"base64url"),kty:"OKP"}});return Ps.default.sign(null,e instanceof Uint8Array?e:e.subarray(),s)}function F5(r,e,t){if(r.byteLength!==lc)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==LD)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=Ps.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:C(r,"base64url"),kty:"OKP"}});return Ps.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}function Nm(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var uc=class{type="Ed25519";raw;constructor(e){this.raw=mh(e,lc)}toMultihash(){return Fo.digest(nt(this))}toCID(){return Mr.createV1(114,this.toMultihash())}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=F5(this.raw,t,e);return Nm(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}},ph=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=mh(e,fh),this.publicKey=new uc(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=K5(this.raw,e);return Nm(n)?n.then(s=>(t?.signal?.throwIfAborted(),s)):(t?.signal?.throwIfAborted(),n)}};function Bm(r){return r=mh(r,lc),new uc(r)}async function $5(){let{privateKey:r,publicKey:e}=U5();return new ph(r,e)}function mh(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new N(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Um=new Float32Array([-0]),Yn=new Uint8Array(Um.buffer);function H5(r,e,t){Um[0]=r,e[t]=Yn[0],e[t+1]=Yn[1],e[t+2]=Yn[2],e[t+3]=Yn[3]}function q5(r,e){return Yn[0]=r[e],Yn[1]=r[e+1],Yn[2]=r[e+2],Yn[3]=r[e+3],Um[0]}var Km=new Float64Array([-0]),yt=new Uint8Array(Km.buffer);function V5(r,e,t){Km[0]=r,e[t]=yt[0],e[t+1]=yt[1],e[t+2]=yt[2],e[t+3]=yt[3],e[t+4]=yt[4],e[t+5]=yt[5],e[t+6]=yt[6],e[t+7]=yt[7]}function G5(r,e){return yt[0]=r[e],yt[1]=r[e+1],yt[2]=r[e+2],yt[3]=r[e+3],yt[4]=r[e+4],yt[5]=r[e+5],yt[6]=r[e+6],yt[7]=r[e+7],Km[0]}var OD=BigInt(Number.MAX_SAFE_INTEGER),RD=BigInt(Number.MIN_SAFE_INTEGER),Gt=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Ds;if(e<OD&&e>RD)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>W5&&(s=0n,++n>W5&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return Ds;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Ds}},Ds=new Gt(0,0);Ds.toBigInt=function(){return 0n};Ds.zzEncode=Ds.zzDecode=function(){return this};Ds.length=function(){return 1};var W5=4294967296n;function j5(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Y5(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Fm(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function wr(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function gh(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var zm=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,wr(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw wr(this,4);return gh(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw wr(this,4);return gh(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw wr(this,4);let e=q5(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw wr(this,4);let e=G5(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw wr(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Y5(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw wr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw wr(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Gt(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw wr(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw wr(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw wr(this,8);let e=gh(this.buf,this.pos+=4),t=gh(this.buf,this.pos+=4);return new Gt(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Q1(this.buf,this.pos);return this.pos+=ve(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function $m(r){return new zm(r instanceof Uint8Array?r:r.subarray())}function Y(r,e,t){let n=$m(r);return e.decode(n,void 0,t)}function Hm(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return We(i);s+i>e&&(n=We(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var ks=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function qm(){}var Gm=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ND=Hm();function BD(r){return globalThis.Buffer!=null?We(r):ND(r)}var dc=class{len;head;tail;states;constructor(){this.len=0,this.head=new ks(qm,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ks(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Wm((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(yh,10,Gt.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Gt.fromBigInt(e);return this._push(yh,t.length(),t)}uint64Number(e){return this._push(cn,ve(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Gt.fromBigInt(e).zzEncode();return this._push(yh,t.length(),t)}sint64Number(e){let t=Gt.fromNumber(e).zzEncode();return this._push(yh,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Vm,1,e?1:0)}fixed32(e){return this._push(hc,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Gt.fromBigInt(e);return this._push(hc,4,t.lo)._push(hc,4,t.hi)}fixed64Number(e){let t=Gt.fromNumber(e);return this._push(hc,4,t.lo)._push(hc,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(H5,4,e)}double(e){return this._push(V5,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Vm,1,0):this.uint32(t)._push(KD,t,e)}string(e){let t=j5(e);return t!==0?this.uint32(t)._push(Fm,t,e):this._push(Vm,1,0)}fork(){return this.states=new Gm(this),this.head=this.tail=new ks(qm,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ks(qm,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=BD(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Vm(r,e,t){e[t]=r&255}function UD(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Wm=class extends ks{next;constructor(e,t){super(UD,e,t),this.next=void 0}};function yh(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function hc(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function KD(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(dc.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(FD,e,r),this},dc.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(zD,e,r),this});function FD(r,e,t){e.set(r,t)}function zD(r,e,t){r.length<40?Fm(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(P(r),t)}function jm(){return new dc}function X(r,e){let t=jm();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Wo;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Wo||(Wo={}));function bh(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Wt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,i){let a=e(o);i.int32(a)},n=function(o){let i=o.int32();return e(i)};return bh("enum",Wo.VARINT,t,n)}function Q(r,e){return bh("message",Wo.LENGTH_DELIMITED,r,e)}var Ie=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},fc=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var qe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(qe||(qe={}));var Ym;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ym||(Ym={}));(function(r){r.codec=()=>Wt(Ym)})(qe||(qe={}));var Rr;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),qe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=qe.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(Rr||(Rr={}));var Xm;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),qe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=qe.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(Xm||(Xm={}));var vh=ne(Z("node:crypto"),1),hx=Z("node:util");function pc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ar(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function de(r,e,t=""){let n=pc(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Ls(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ar(r.outputLen),ar(r.blockLen)}function jo(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Z5(r,e){de(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function pn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function wh(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function xr(r,e){return r<<32-e|r>>>e}var ex=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",$D=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ms(r){if(de(r),ex)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=$D[r[t]];return e}var fn={_0:48,_9:57,A:65,F:70,a:97,f:102};function J5(r){if(r>=fn._0&&r<=fn._9)return r-fn._0;if(r>=fn.A&&r<=fn.F)return r-(fn.A-10);if(r>=fn.a&&r<=fn.f)return r-(fn.a-10)}function Os(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(ex)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=J5(r.charCodeAt(o)),a=J5(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function vr(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];de(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function tx(r,e={}){let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function Nr(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var rx=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Xn(r){if(isNaN(r)||r<=0)throw new N("random bytes length must be a Number bigger than 0");return Nr(r)}var gc={};z(gc,{MAX_RSA_KEY_SIZE:()=>Zm,generateRSAKeyPair:()=>c0,jwkToJWKKeyPair:()=>cx,jwkToPkcs1:()=>WD,jwkToPkix:()=>n0,jwkToRSAPrivateKey:()=>a0,pkcs1MessageToJwk:()=>t0,pkcs1MessageToRSAPrivateKey:()=>s0,pkcs1ToJwk:()=>GD,pkcs1ToRSAPrivateKey:()=>ax,pkixMessageToJwk:()=>r0,pkixMessageToRSAPublicKey:()=>i0,pkixToJwk:()=>jD,pkixToRSAPublicKey:()=>o0});function nx(r,e,t){return r&e^~r&t}function sx(r,e,t){return r&e^r&t^e&t}var xh=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=wh(this.buffer)}update(e){jo(this),de(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=wh(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){jo(this),Z5(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,pn(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let d=i;d<s;d++)t[d]=0;n.setBigUint64(s-8,BigInt(this.length*8),o),this.process(n,0);let a=wh(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},mn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var HD=Uint32Array.from([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]),Qn=new Uint32Array(64),Qm=class extends xh{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)Qn[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=Qn[d-15],f=Qn[d-2],h=xr(p,7)^xr(p,18)^p>>>3,m=xr(f,17)^xr(f,19)^f>>>10;Qn[d]=m+Qn[d-7]+h+Qn[d-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let p=xr(a,6)^xr(a,11)^xr(a,25),f=u+p+nx(a,c,l)+HD[d]+Qn[d]|0,m=(xr(n,2)^xr(n,13)^xr(n,22))+sx(n,s,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=s,s=n,n=f+m|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){pn(Qn)}destroy(){this.set(0,0,0,0,0,0,0,0),pn(this.buffer)}},Jm=class extends Qm{A=mn[0]|0;B=mn[1]|0;C=mn[2]|0;D=mn[3]|0;E=mn[4]|0;F=mn[5]|0;G=mn[6]|0;H=mn[7]|0;constructor(){super(32)}};var Ut=tx(()=>new Jm,rx(1));var Yo=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=gc.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Mr.createV1(114,this._multihash)}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}verify(e,t,n){return ix(this.jwk,t,e,n)}},mc=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=gc.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}sign(e,t){return ox(this.jwk,e,t)}};var Zm=8192,e0=18,qD=1062,VD=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function GD(r){let e=dn(r);return t0(e)}function t0(r){return{n:C(r[1],"base64url"),e:C(r[2],"base64url"),d:C(r[3],"base64url"),p:C(r[4],"base64url"),q:C(r[5],"base64url"),dp:C(r[6],"base64url"),dq:C(r[7],"base64url"),qi:C(r[8],"base64url"),kty:"RSA"}}function WD(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new N("JWK was missing components");return br([Ct(Uint8Array.from([0])),Ct(P(r.n,"base64url")),Ct(P(r.e,"base64url")),Ct(P(r.d,"base64url")),Ct(P(r.p,"base64url")),Ct(P(r.q,"base64url")),Ct(P(r.dp,"base64url")),Ct(P(r.dq,"base64url")),Ct(P(r.qi,"base64url"))]).subarray()}function jD(r){let e=dn(r,{offset:0});return r0(e)}function r0(r){let e=dn(r[1],{offset:0});return{kty:"RSA",n:C(e[0],"base64url"),e:C(e[1],"base64url")}}function n0(r){if(r.n==null||r.e==null)throw new N("JWK was missing components");return br([VD,cc(br([Ct(P(r.n,"base64url")),Ct(P(r.e,"base64url"))]))]).subarray()}function ax(r){let e=dn(r);return s0(e)}function s0(r){let e=t0(r);return a0(e)}function o0(r,e){if(r.byteLength>=qD)throw new Mo("Key size is too large");let t=dn(r,{offset:0});return i0(t,r,e)}function i0(r,e,t){let n=r0(r);if(t==null){let s=Ut(Rr.encode({Type:qe.RSA,Data:e}));t=Wn(e0,s)}return new Yo(n,t)}function a0(r){if(ux(r)>Zm)throw new N("Key size is too large");let e=cx(r),t=Ut(Rr.encode({Type:qe.RSA,Data:n0(e.publicKey)})),n=Wn(e0,t);return new mc(e.privateKey,new Yo(e.publicKey,n))}async function c0(r){if(r>Zm)throw new N("Key size is too large");let e=await lx(r),t=Ut(Rr.encode({Type:qe.RSA,Data:n0(e.publicKey)})),n=Wn(e0,t);return new mc(e.privateKey,new Yo(e.publicKey,n))}function cx(r){if(r==null)throw new N("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var YD=(0,hx.promisify)(vh.default.generateKeyPair);async function lx(r,e){let t=await YD("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function ox(r,e,t){t?.signal?.throwIfAborted();let n=vh.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)n.update(e);else for(let s of e)n.update(s);return n.sign({format:"jwk",key:r})}function ix(r,e,t,n){n?.signal?.throwIfAborted();let s=vh.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)s.update(t);else for(let o of t)s.update(o);return s.verify({format:"jwk",key:r},e)}function ux(r){if(r.kty!=="RSA")throw new N("Invalid key type");if(r.n==null)throw new N("Invalid key modulus");return P(r.n,"base64url").length*8}var T0=ne(Z("node:crypto"),1);var u0=BigInt(0),l0=BigInt(1);function yc(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function dx(r){if(typeof r=="bigint"){if(!Eh(r))throw new Error("positive bigint expected, got "+r)}else ar(r);return r}function bc(r){let e=dx(r).toString(16);return e.length&1?"0"+e:e}function fx(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?u0:BigInt("0x"+r)}function Xo(r){return fx(Ms(r))}function Qo(r){return fx(Ms(Ih(de(r)).reverse()))}function Sh(r,e){ar(e),r=dx(r);let t=Os(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function wc(r,e){return Sh(r,e).reverse()}function Ih(r){return Uint8Array.from(r)}var Eh=r=>typeof r=="bigint"&&u0<=r;function XD(r,e,t){return Eh(r)&&Eh(e)&&Eh(t)&&e<=r&&r<t}function xc(r,e,t,n){if(!XD(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function h0(r){let e;for(e=0;r>u0;r>>=l0,e+=1);return e}var vc=r=>(l0<<BigInt(r))-l0;function px(r,e,t){if(ar(r,"hashLen"),ar(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=g=>new Uint8Array(g),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},p=(...g)=>t(l,vr(c,...g)),f=(g=s)=>{l=p(o,g),c=p(),g.length!==0&&(l=p(i,g),c=p())},h=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,y=[];for(;g<e;){c=p();let b=c.slice();y.push(b),g+=c.length}return vr(...y)};return(g,y)=>{d(),f(g);let b;for(;!(b=y(h()));)f();return d(),b}}function Rs(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,i,a){let c=r[o];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}let s=(o,i)=>Object.entries(o).forEach(([a,c])=>n(a,c,i));s(e,!1),s(t,!0)}function d0(r){let e=new WeakMap;return(t,...n)=>{let s=e.get(t);if(s!==void 0)return s;let o=r(t,...n);return e.set(t,o),o}}var _t=BigInt(0),bt=BigInt(1),Ns=BigInt(2),yx=BigInt(3),bx=BigInt(4),wx=BigInt(5),QD=BigInt(7),xx=BigInt(8),JD=BigInt(9),vx=BigInt(16);function Tt(r,e){let t=r%e;return t>=_t?t:e+t}function _e(r,e,t){let n=r;for(;e-- >_t;)n*=n,n%=t;return n}function mx(r,e){if(r===_t)throw new Error("invert: expected non-zero number");if(e<=_t)throw new Error("invert: expected positive modulus, got "+e);let t=Tt(r,e),n=e,s=_t,o=bt,i=bt,a=_t;for(;t!==_t;){let l=n/t,u=n%t,d=s-i*l,p=o-a*l;n=t,t=u,s=i,o=a,i=d,a=p}if(n!==bt)throw new Error("invert: does not exist");return Tt(s,e)}function p0(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Ex(r,e){let t=(r.ORDER+bt)/bx,n=r.pow(e,t);return p0(r,n,e),n}function ZD(r,e){let t=(r.ORDER-wx)/xx,n=r.mul(e,Ns),s=r.pow(n,t),o=r.mul(e,s),i=r.mul(r.mul(o,Ns),s),a=r.mul(o,r.sub(i,r.ONE));return p0(r,a,e),a}function ek(r){let e=Jo(r),t=Sx(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+QD)/vx;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),d=a.mul(l,s),p=a.mul(l,o),f=a.eql(a.sqr(u),c),h=a.eql(a.sqr(d),c);l=a.cmov(l,u,f),u=a.cmov(p,d,h);let m=a.eql(a.sqr(u),c),g=a.cmov(l,u,m);return p0(a,g,c),g}}function Sx(r){if(r<yx)throw new Error("sqrt is not defined for small field");let e=r-bt,t=0;for(;e%Ns===_t;)e/=Ns,t++;let n=Ns,s=Jo(r);for(;gx(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Ex;let o=s.pow(n,e),i=(e+bt)/Ns;return function(c,l){if(c.is0(l))return l;if(gx(c,l)!==1)throw new Error("Cannot find square root");let u=t,d=c.mul(c.ONE,o),p=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let h=1,m=c.sqr(p);for(;!c.eql(m,c.ONE);)if(h++,m=c.sqr(m),h===u)throw new Error("Cannot find square root");let g=bt<<BigInt(u-h-1),y=c.pow(d,g);u=h,d=c.sqr(y),p=c.mul(p,d),f=c.mul(f,y)}return f}}function tk(r){return r%bx===yx?Ex:r%xx===wx?ZD:r%vx===JD?ek(r):Sx(r)}var rk=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function m0(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=rk.reduce((n,s)=>(n[s]="function",n),e);return Rs(r,t),r}function nk(r,e,t){if(t<_t)throw new Error("invalid exponent, negatives unsupported");if(t===_t)return r.ONE;if(t===bt)return e;let n=r.ONE,s=e;for(;t>_t;)t&bt&&(n=r.mul(n,s)),s=r.sqr(s),t>>=bt;return n}function Ec(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),s=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),o=r.inv(s);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),o),n}function gx(r,e){let t=(r.ORDER-bt)/Ns,n=r.pow(e,t),s=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function sk(r,e){e!==void 0&&ar(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var f0=class{ORDER;BITS;BYTES;isLE;ZERO=_t;ONE=bt;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=_t)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=sk(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Tt(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return _t<=e&&e<this.ORDER}is0(e){return e===_t}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&bt)===bt}neg(e){return Tt(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Tt(e*e,this.ORDER)}add(e,t){return Tt(e+t,this.ORDER)}sub(e,t){return Tt(e-t,this.ORDER)}mul(e,t){return Tt(e*t,this.ORDER)}pow(e,t){return nk(this,e,t)}div(e,t){return Tt(e*mx(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return mx(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=tk(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?wc(e,this.BYTES):Sh(e,this.BYTES)}fromBytes(e,t=!1){de(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?Qo(e):Xo(e);if(a&&(c=Tt(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ec(this,e)}cmov(e,t,n){return n?t:e}};function Jo(r,e={}){return new f0(r,e)}function Ix(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function g0(r){let e=Ix(r);return e+Math.ceil(e/2)}function y0(r,e,t=!1){de(r);let n=r.length,s=Ix(e),o=g0(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?Qo(r):Xo(r),a=Tt(i,e-bt)+bt;return t?wc(a,s):Sh(a,s)}var Zo=BigInt(0),Bs=BigInt(1);function Sc(r,e){let t=e.negate();return r?t:e}function v0(r,e){let t=Ec(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function _x(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function b0(r,e){_x(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),s=2**r,o=vc(r),i=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:s,shiftBy:i}}function Ax(r,e,t){let{windowSize:n,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(r&s),c=r>>i;a>n&&(a-=o,c+=Bs);let l=e*n,u=l+Math.abs(a)-1,d=a===0,p=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:p,isNegF:f,offsetF:l}}var w0=new WeakMap,Px=new WeakMap;function x0(r){return Px.get(r)||1}function Cx(r){if(r!==Zo)throw new Error("invalid wNAF")}var Ah=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let s=e;for(;t>Zo;)t&Bs&&(n=n.add(s)),s=s.double(),t>>=Bs;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=b0(t,this.bits),o=[],i=e,a=i;for(let c=0;c<n;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=b0(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:f}=Ax(n,a,i);n=c,u?o=o.add(Sc(p,t[f])):s=s.add(Sc(d,t[l]))}return Cx(n),{p:s,f:o}}wNAFUnsafe(e,t,n,s=this.ZERO){let o=b0(e,this.bits);for(let i=0;i<o.windows&&n!==Zo;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Ax(n,i,o);if(n=a,!l){let d=t[c];s=s.add(u?d.negate():d)}}return Cx(n),s}getPrecomputes(e,t,n){let s=w0.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(s=n(s)),w0.set(t,s))),s}cached(e,t,n){let s=x0(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){let o=x0(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,s)}createCache(e,t){_x(t,this.bits),Px.set(e,t),w0.delete(e)}hasCache(e){return x0(e)!==1}};function Dx(r,e,t,n){let s=e,o=r.ZERO,i=r.ZERO;for(;t>Zo||n>Zo;)t&Bs&&(o=o.add(s)),n&Bs&&(i=i.add(s)),s=s.double(),t>>=Bs,n>>=Bs;return{p1:o,p2:i}}function Tx(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return m0(e),e}else return Jo(r,{isLE:t})}function kx(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Zo))throw new Error(`CURVE.${c} must be positive bigint`)}let s=Tx(e.p,t.Fp,n),o=Tx(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function Ch(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var Th=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Ls(e),de(t,void 0,"key"),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 n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),pn(s)}update(e){return jo(this),this.iHash.update(e),this}digestInto(e){jo(this),de(e,this.outputLen,"output"),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||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ei=(r,e,t)=>new Th(r,e).update(t).digest();ei.create=(r,e)=>new Th(r,e);var Lx=(r,e)=>(r+(r>=0?e:-e)/Mx)/e;function ok(r,e,t){let[[n,s],[o,i]]=e,a=Lx(i*r,t),c=Lx(-s*r,t),l=r-a*n-c*o,u=-a*s-c*i,d=l<gn,p=u<gn;d&&(l=-l),p&&(u=-u);let f=vc(Math.ceil(h0(t)/2))+ti;if(l<gn||l>=f||u<gn||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:d,k1:l,k2neg:p,k2:u}}function S0(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function E0(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return yc(t.lowS,"lowS"),yc(t.prehash,"prehash"),t.format!==void 0&&S0(t.format),t}var I0=class extends Error{constructor(e=""){super(e)}},Jn={Err:I0,_tlv:{encode:(r,e)=>{let{Err:t}=Jn;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=bc(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?bc(s.length/2|128):"";return bc(r)+o+s+e},decode(r,e){let{Err:t}=Jn,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Jn;if(r<gn)throw new e("integer: negative integers are not allowed");let t=bc(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Jn;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Xo(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Jn,s=de(r,void 0,"signature"),{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Jn,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},gn=BigInt(0),ti=BigInt(1),Mx=BigInt(2),_h=BigInt(3),ik=BigInt(4);function Ox(r,e={}){let t=kx("weierstrass",r,e),{Fp:n,Fn:s}=t,o=t.CURVE,{h:i,n:a}=o;Rs(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Nx(n,s);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d($,k,_){let{x:T,y:L}=k.toAffine(),M=n.toBytes(T);if(yc(_,"isCompressed"),_){u();let O=!n.isOdd(L);return vr(Rx(O),M)}else return vr(Uint8Array.of(4),M,n.toBytes(L))}function p($){de($,void 0,"Point");let{publicKey:k,publicKeyUncompressed:_}=l,T=$.length,L=$[0],M=$.subarray(1);if(T===k&&(L===2||L===3)){let O=n.fromBytes(M);if(!n.isValid(O))throw new Error("bad point: is not on curve, wrong x");let D=m(O),R;try{R=n.sqrt(D)}catch(ye){let ae=ye instanceof Error?": "+ye.message:"";throw new Error("bad point: is not on curve, sqrt error"+ae)}u();let U=n.isOdd(R);return(L&1)===1!==U&&(R=n.neg(R)),{x:O,y:R}}else if(T===_&&L===4){let O=n.BYTES,D=n.fromBytes(M.subarray(0,O)),R=n.fromBytes(M.subarray(O,O*2));if(!g(D,R))throw new Error("bad point: is not on curve");return{x:D,y:R}}else throw new Error(`bad point: got length ${T}, expected compressed=${k} or uncompressed=${_}`)}let f=e.toBytes||d,h=e.fromBytes||p;function m($){let k=n.sqr($),_=n.mul(k,$);return n.add(n.add(_,n.mul($,o.a)),o.b)}function g($,k){let _=n.sqr(k),T=m($);return n.eql(_,T)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(o.a,_h),ik),b=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(y,b)))throw new Error("bad curve params: a or b");function E($,k,_=!1){if(!n.isValid(k)||_&&n.is0(k))throw new Error(`bad point coordinate ${$}`);return k}function x($){if(!($ instanceof A))throw new Error("Weierstrass Point expected")}function v($){if(!c||!c.basises)throw new Error("no endo");return ok($,c.basises,s.ORDER)}let S=d0(($,k)=>{let{X:_,Y:T,Z:L}=$;if(n.eql(L,n.ONE))return{x:_,y:T};let M=$.is0();k==null&&(k=M?n.ONE:n.inv(L));let O=n.mul(_,k),D=n.mul(T,k),R=n.mul(L,k);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(R,n.ONE))throw new Error("invZ was invalid");return{x:O,y:D}}),w=d0($=>{if($.is0()){if(e.allowInfinityPoint&&!n.is0($.Y))return;throw new Error("bad point: ZERO")}let{x:k,y:_}=$.toAffine();if(!n.isValid(k)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!g(k,_))throw new Error("bad point: equation left != right");if(!$.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function I($,k,_,T,L){return _=new A(n.mul(_.X,$),_.Y,_.Z),k=Sc(T,k),_=Sc(L,_),k.add(_)}class A{static BASE=new A(o.Gx,o.Gy,n.ONE);static ZERO=new A(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(k,_,T){this.X=E("x",k),this.Y=E("y",_,!0),this.Z=E("z",T),Object.freeze(this)}static CURVE(){return o}static fromAffine(k){let{x:_,y:T}=k||{};if(!k||!n.isValid(_)||!n.isValid(T))throw new Error("invalid affine point");if(k instanceof A)throw new Error("projective point not allowed");return n.is0(_)&&n.is0(T)?A.ZERO:new A(_,T,n.ONE)}static fromBytes(k){let _=A.fromAffine(h(de(k,void 0,"point")));return _.assertValidity(),_}static fromHex(k){return A.fromBytes(Os(k))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(k=8,_=!0){return J.createCache(this,k),_||this.multiply(_h),this}assertValidity(){w(this)}hasEvenY(){let{y:k}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(k)}equals(k){x(k);let{X:_,Y:T,Z:L}=this,{X:M,Y:O,Z:D}=k,R=n.eql(n.mul(_,D),n.mul(M,L)),U=n.eql(n.mul(T,D),n.mul(O,L));return R&&U}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){let{a:k,b:_}=o,T=n.mul(_,_h),{X:L,Y:M,Z:O}=this,D=n.ZERO,R=n.ZERO,U=n.ZERO,K=n.mul(L,L),ye=n.mul(M,M),ae=n.mul(O,O),te=n.mul(L,M);return te=n.add(te,te),U=n.mul(L,O),U=n.add(U,U),D=n.mul(k,U),R=n.mul(T,ae),R=n.add(D,R),D=n.sub(ye,R),R=n.add(ye,R),R=n.mul(D,R),D=n.mul(te,D),U=n.mul(T,U),ae=n.mul(k,ae),te=n.sub(K,ae),te=n.mul(k,te),te=n.add(te,U),U=n.add(K,K),K=n.add(U,K),K=n.add(K,ae),K=n.mul(K,te),R=n.add(R,K),ae=n.mul(M,O),ae=n.add(ae,ae),K=n.mul(ae,te),D=n.sub(D,K),U=n.mul(ae,ye),U=n.add(U,U),U=n.add(U,U),new A(D,R,U)}add(k){x(k);let{X:_,Y:T,Z:L}=this,{X:M,Y:O,Z:D}=k,R=n.ZERO,U=n.ZERO,K=n.ZERO,ye=o.a,ae=n.mul(o.b,_h),te=n.mul(_,M),ue=n.mul(T,O),Se=n.mul(L,D),He=n.add(_,T),pe=n.add(M,O);He=n.mul(He,pe),pe=n.add(te,ue),He=n.sub(He,pe),pe=n.add(_,L);let Ge=n.add(M,D);return pe=n.mul(pe,Ge),Ge=n.add(te,Se),pe=n.sub(pe,Ge),Ge=n.add(T,L),R=n.add(O,D),Ge=n.mul(Ge,R),R=n.add(ue,Se),Ge=n.sub(Ge,R),K=n.mul(ye,pe),R=n.mul(ae,Se),K=n.add(R,K),R=n.sub(ue,K),K=n.add(ue,K),U=n.mul(R,K),ue=n.add(te,te),ue=n.add(ue,te),Se=n.mul(ye,Se),pe=n.mul(ae,pe),ue=n.add(ue,Se),Se=n.sub(te,Se),Se=n.mul(ye,Se),pe=n.add(pe,Se),te=n.mul(ue,pe),U=n.add(U,te),te=n.mul(Ge,pe),R=n.mul(He,R),R=n.sub(R,te),te=n.mul(He,ue),K=n.mul(Ge,K),K=n.add(K,te),new A(R,U,K)}subtract(k){return this.add(k.negate())}is0(){return this.equals(A.ZERO)}multiply(k){let{endo:_}=e;if(!s.isValidNot0(k))throw new Error("invalid scalar: out of range");let T,L,M=O=>J.cached(this,O,D=>v0(A,D));if(_){let{k1neg:O,k1:D,k2neg:R,k2:U}=v(k),{p:K,f:ye}=M(D),{p:ae,f:te}=M(U);L=ye.add(te),T=I(_.beta,K,ae,O,R)}else{let{p:O,f:D}=M(k);T=O,L=D}return v0(A,[T,L])[0]}multiplyUnsafe(k){let{endo:_}=e,T=this;if(!s.isValid(k))throw new Error("invalid scalar: out of range");if(k===gn||T.is0())return A.ZERO;if(k===ti)return T;if(J.hasCache(this))return this.multiply(k);if(_){let{k1neg:L,k1:M,k2neg:O,k2:D}=v(k),{p1:R,p2:U}=Dx(A,T,M,D);return I(_.beta,R,U,L,O)}else return J.unsafe(T,k)}toAffine(k){return S(this,k)}isTorsionFree(){let{isTorsionFree:k}=e;return i===ti?!0:k?k(A,this):J.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:k}=e;return i===ti?this:k?k(A,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(k=!0){return yc(k,"isCompressed"),this.assertValidity(),f(A,this,k)}toHex(k=!0){return Ms(this.toBytes(k))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let G=s.BITS,J=new Ah(A,e.endo?Math.ceil(G/2):G);return A.BASE.precompute(8),A}function Rx(r){return Uint8Array.of(r?2:3)}function Nx(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ak(r,e={}){let{Fn:t}=r,n=e.randomBytes||Nr,s=Object.assign(Nx(r.Fp,t),{seed:g0(t.ORDER)});function o(f){try{let h=t.fromBytes(f);return t.isValidNot0(h)}catch{return!1}}function i(f,h){let{publicKey:m,publicKeyUncompressed:g}=s;try{let y=f.length;return h===!0&&y!==m||h===!1&&y!==g?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=n(s.seed)){return y0(de(f,s.seed,"seed"),t.ORDER)}function c(f,h=!0){return r.BASE.multiply(t.fromBytes(f)).toBytes(h)}function l(f){let{secretKey:h,publicKey:m,publicKeyUncompressed:g}=s;if(!pc(f)||"_lengths"in t&&t._lengths||h===m)return;let y=de(f,void 0,"key").length;return y===m||y===g}function u(f,h,m=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(h)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(f);return r.fromBytes(h).multiply(g).toBytes(m)}let d={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},p=Ch(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:r,utils:d,lengths:s})}function Bx(r,e,t={}){Ls(e),Rs(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Nr,s=t.hmac||((_,T)=>ei(e,_,T)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:p,lengths:f}=ak(r,t),h={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Mx<o.ORDER;function g(_){let T=a>>ti;return _>T}function y(_,T){if(!i.isValidNot0(T))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return T}function b(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function E(_,T){S0(T);let L=f.signature,M=T==="compact"?L:T==="recovered"?L+1:void 0;return de(_,M)}class x{r;s;recovery;constructor(T,L,M){if(this.r=y("r",T),this.s=y("s",L),M!=null){if(b(),![0,1,2,3].includes(M))throw new Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(T,L=h.format){E(T,L);let M;if(L==="der"){let{r:U,s:K}=Jn.toSig(de(T));return new x(U,K)}L==="recovered"&&(M=T[0],L="compact",T=T.subarray(1));let O=f.signature/2,D=T.subarray(0,O),R=T.subarray(O,O*2);return new x(i.fromBytes(D),i.fromBytes(R),M)}static fromHex(T,L){return this.fromBytes(Os(T),L)}assertRecovery(){let{recovery:T}=this;if(T==null)throw new Error("invalid recovery id: must be present");return T}addRecoveryBit(T){return new x(this.r,this.s,T)}recoverPublicKey(T){let{r:L,s:M}=this,O=this.assertRecovery(),D=O===2||O===3?L+a:L;if(!o.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let R=o.toBytes(D),U=r.fromBytes(vr(Rx((O&1)===0),R)),K=i.inv(D),ye=S(de(T,void 0,"msgHash")),ae=i.create(-ye*K),te=i.create(M*K),ue=r.BASE.multiplyUnsafe(ae).add(U.multiplyUnsafe(te));if(ue.is0())throw new Error("invalid recovery: point at infinify");return ue.assertValidity(),ue}hasHighS(){return g(this.s)}toBytes(T=h.format){if(S0(T),T==="der")return Os(Jn.hexFromSig(this));let{r:L,s:M}=this,O=i.toBytes(L),D=i.toBytes(M);return T==="recovered"?(b(),vr(Uint8Array.of(this.assertRecovery()),O,D)):vr(O,D)}toHex(T){return Ms(this.toBytes(T))}}let v=t.bits2int||function(T){if(T.length>8192)throw new Error("input is too large");let L=Xo(T),M=T.length*8-c;return M>0?L>>BigInt(M):L},S=t.bits2int_modN||function(T){return i.create(v(T))},w=vc(c);function I(_){return xc("num < 2^"+c,_,gn,w),i.toBytes(_)}function A(_,T){return de(_,void 0,"message"),T?de(e(_),void 0,"prehashed message"):_}function G(_,T,L){let{lowS:M,prehash:O,extraEntropy:D}=E0(L,h);_=A(_,O);let R=S(_),U=i.fromBytes(T);if(!i.isValidNot0(U))throw new Error("invalid private key");let K=[I(U),I(R)];if(D!=null&&D!==!1){let ue=D===!0?n(f.secretKey):D;K.push(de(ue,void 0,"extraEntropy"))}let ye=vr(...K),ae=R;function te(ue){let Se=v(ue);if(!i.isValidNot0(Se))return;let He=i.inv(Se),pe=r.BASE.multiply(Se).toAffine(),Ge=i.create(pe.x);if(Ge===gn)return;let Do=i.create(He*i.create(ae+Ge*U));if(Do===gn)return;let Mu=(pe.x===Ge?0:2)|Number(pe.y&ti),za=Do;return M&&g(Do)&&(za=i.neg(Do),Mu^=1),new x(Ge,za,m?void 0:Mu)}return{seed:ye,k2sig:te}}function J(_,T,L={}){let{seed:M,k2sig:O}=G(_,T,L);return px(e.outputLen,i.BYTES,s)(M,O).toBytes(L.format)}function $(_,T,L,M={}){let{lowS:O,prehash:D,format:R}=E0(M,h);if(L=de(L,void 0,"publicKey"),T=A(T,D),!pc(_)){let U=_ instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}E(_,R);try{let U=x.fromBytes(_,R),K=r.fromBytes(L);if(O&&U.hasHighS())return!1;let{r:ye,s:ae}=U,te=S(T),ue=i.inv(ae),Se=i.create(te*ue),He=i.create(ye*ue),pe=r.BASE.multiplyUnsafe(Se).add(K.multiplyUnsafe(He));return pe.is0()?!1:i.create(pe.x)===ye}catch{return!1}}function k(_,T,L={}){let{prehash:M}=E0(L,h);return T=A(T,M),x.fromBytes(_,"recovered").recoverPublicKey(T).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:p,lengths:f,Point:r,sign:J,verify:$,recoverPublicKey:k,Signature:x,hash:e})}var C0={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ck={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ux=BigInt(2);function lk(r){let e=C0.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=_e(u,t,e)*u%e,p=_e(d,t,e)*u%e,f=_e(p,Ux,e)*l%e,h=_e(f,s,e)*f%e,m=_e(h,o,e)*h%e,g=_e(m,a,e)*m%e,y=_e(g,c,e)*g%e,b=_e(y,a,e)*m%e,E=_e(b,t,e)*u%e,x=_e(E,i,e)*h%e,v=_e(x,n,e)*l%e,S=_e(v,Ux,e);if(!A0.eql(A0.sqr(S),r))throw new Error("Cannot find square root");return S}var A0=Jo(C0.p,{sqrt:lk}),uk=Ox(C0,{Fp:A0,endo:ck}),Ye=Bx(uk,Ut);var Ph=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Dh=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function Kx(r,e,t){t?.signal?.throwIfAborted();let n=T0.default.createHash("sha256");if(e instanceof Uint8Array)n.update(e);else for(let o of e)n.update(o);let s=n.digest();try{return Ye.sign(s,r,{prehash:!1,format:"der"})}catch(o){throw new Ph(String(o))}}function Fx(r,e,t,n){n?.signal?.throwIfAborted();let s=T0.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return Ye.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new Dh(String(i))}}var Ic=class{type="secp256k1";raw;_key;constructor(e){this._key=Hx(e),this.raw=zx(this._key)}toMultihash(){return Fo.digest(nt(this))}toCID(){return Mr.createV1(114,this.toMultihash())}toString(){return lt.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}verify(e,t,n){return Fx(this._key,t,e,n)}},kh=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=$x(e),this.publicKey=new Ic(t??qx(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}sign(e,t){return Kx(this.raw,e,t)}};function _0(r){return new Ic(r)}async function Vx(){let r=hk();return new kh(r)}function zx(r){return Ye.Point.fromBytes(r).toBytes()}function $x(r){try{return Ye.getPublicKey(r,!0),r}catch(e){throw new qa(String(e))}}function Hx(r){try{return Ye.Point.fromBytes(r),r}catch(e){throw new Mo(String(e))}}function qx(r){try{return Ye.getPublicKey(r,!0)}catch(e){throw new qa(String(e))}}function hk(){return Ye.utils.randomSecretKey()}async function Gx(r,e){if(r==="Ed25519")return $5();if(r==="secp256k1")return Vx();if(r==="RSA")return c0(dk(e));if(r==="ECDSA")return B5(fk(e));throw new Hn}function Pt(r,e){let{Type:t,Data:n}=Rr.decode(r),s=n??new Uint8Array;switch(t){case qe.RSA:return o0(s,e);case qe.Ed25519:return Bm(s);case qe.secp256k1:return _0(s);case qe.ECDSA:return Rm(s);default:throw new Hn}}function Wx(r){let{Type:e,Data:t}=Rr.decode(r.digest),n=t??new Uint8Array;switch(e){case qe.Ed25519:return Bm(n);case qe.secp256k1:return _0(n);case qe.ECDSA:return Rm(n);default:throw new Hn}}function nt(r){return Rr.encode({Type:qe[r.type],Data:r.raw})}function dk(r){return r==null?2048:parseInt(r,10)}function fk(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new N("Unsupported curve, should be P-256, P-384 or P-521")}var aJ=new Uint8Array(0);function jx(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Er(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function pk(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var mk=pk,gk=mk,Yx=gk;var P0=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},D0=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 Xx(this,e)}},k0=class{decoders;constructor(e){this.decoders=e}or(e){return Xx(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Xx(r,e){return new k0({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var L0=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new P0(e,t,n),this.decoder=new D0(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Qx({name:r,prefix:e,encode:t,decode:n}){return new L0(r,e,t,n)}function ri({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Yx(t,r);return Qx({prefix:e,name:r,encode:n,decode:o=>Er(s(o))})}function yk(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function bk(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function wk(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Br({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=wk(n);return Qx({prefix:e,name:r,encode(o){return bk(o,n,t)},decode(o){return yk(o,s,t,r)}})}var jt=ri({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pJ=ri({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ac=Br({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yJ=Br({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),bJ=Br({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),wJ=Br({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),xJ=Br({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vJ=Br({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),EJ=Br({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),SJ=Br({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),IJ=Br({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Lh=ri({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),TJ=ri({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var xk=e4,Jx=128,vk=127,Ek=~vk,Sk=Math.pow(2,31);function e4(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Sk;)e[t++]=r&255|Jx,r/=128;for(;r&Ek;)e[t++]=r&255|Jx,r>>>=7;return e[t]=r|0,e4.bytes=t-n+1,e}var Ik=M0,Ak=128,Zx=127;function M0(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw M0.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Zx)<<s:(i&Zx)*Math.pow(2,s),s+=7}while(i>=Ak);return M0.bytes=o-n,t}var Ck=Math.pow(2,7),Tk=Math.pow(2,14),_k=Math.pow(2,21),Pk=Math.pow(2,28),Dk=Math.pow(2,35),kk=Math.pow(2,42),Lk=Math.pow(2,49),Mk=Math.pow(2,56),Ok=Math.pow(2,63),Rk=function(r){return r<Ck?1:r<Tk?2:r<_k?3:r<Pk?4:r<Dk?5:r<kk?6:r<Lk?7:r<Mk?8:r<Ok?9:10},Nk={encode:xk,decode:Ik,encodingLength:Rk},Bk=Nk,Cc=Bk;function Tc(r,e=0){return[Cc.decode(r,e),Cc.decode.bytes]}function ni(r,e,t=0){return Cc.encode(r,e,t),e}function si(r){return Cc.encodingLength(r)}function ii(r,e){let t=e.byteLength,n=si(r),s=n+si(t),o=new Uint8Array(s+t);return ni(r,o,0),ni(t,o,n),o.set(e,s),new oi(r,t,e,o)}function _c(r){let e=Er(r),[t,n]=Tc(e),[s,o]=Tc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new oi(t,s,i,e)}function r4(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&jx(r.bytes,t.bytes)}}var oi=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function n4(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Kk(t,O0(r),e??jt.encoder);default:return Fk(t,O0(r),e??Ac.encoder)}}var s4=new WeakMap;function O0(r){let e=s4.get(r);if(e==null){let t=new Map;return s4.set(r,t),t}return e}var Us=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Pc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==zk)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ii(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&r4(e.multihash,n.multihash)}toString(e){return n4(this,e)}toJSON(){return{"/":n4(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??o4(n,s,o.bytes))}else if(t[$k]===!0){let{version:n,multihash:s,code:o}=t,i=_c(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Pc)throw new Error(`Version 0 CID must use dag-pb (code: ${Pc}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=o4(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pc,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Er(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new oi(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=Tc(e.subarray(t));return t+=p,d},s=n(),o=Pc;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Uk(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return O0(o).set(n,e),o}};function Uk(r,e){switch(r[0]){case"Q":{let t=e??jt;return[jt.prefix,t.decode(`${jt.prefix}${r}`)]}case jt.prefix:{let t=e??jt;return[jt.prefix,t.decode(r)]}case Ac.prefix:{let t=e??Ac;return[Ac.prefix,t.decode(r)]}case Lh.prefix:{let t=e??Lh;return[Lh.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Kk(r,e,t){let{prefix:n}=t;if(n!==jt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function Fk(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Pc=112,zk=18;function o4(r,e,t){let n=si(r),s=n+si(e),o=new Uint8Array(s+t.byteLength);return ni(r,o,0),ni(e,o,n),o.set(t,s),o}var $k=Symbol.for("@ipld/js-cid/CID");var i4=0,Hk="identity",a4=Er;function qk(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ii(i4,a4(r))}var Oh={code:i4,name:Hk,encode:a4,digest:qk};var B0=ne(Z("crypto"),1);var Vk=20;function N0({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new R0(r,e,t,n,s)}var R0=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??Vk,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?c4(n,this.code,t?.truncate):n.then(s=>c4(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function c4(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ii(e,r)}var l4=N0({name:"sha2-256",code:18,encode:r=>Er(B0.default.createHash("sha256").update(r).digest())}),HJ=N0({name:"sha2-512",code:19,encode:r=>Er(B0.default.createHash("sha512").update(r).digest())});var u4=Symbol.for("nodejs.util.inspect.custom"),Gk=114,Dc=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[rh]=!0;toString(){return this.string==null&&(this.string=jt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Us.createV1(Gk,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return V(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return V(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[u4](){return`PeerId(${this.toString()})`}},kc=class extends Dc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Lc=class extends Dc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Mc=class extends Dc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Wk=2336,Oc=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Oh.digest(P(this.url))}[u4](){return`PeerId(${this.url})`}[rh]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Us.createV1(Wk,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=C(e)),e.toString()===this.toString())}};var jk=114,h4=2336;function oe(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=_c(jt.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return yn(Us.parse(r));if(e==null)throw new N('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=_c(e.decode(r))}return Ur(t)}function Zn(r){if(r.type==="Ed25519")return new Lc({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Mc({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new kc({multihash:r.toCID().multihash,publicKey:r});throw new Hn}function d4(r){return Zn(r.publicKey)}function Ur(r){if(Xk(r))return new kc({multihash:r});if(Yk(r))try{let e=Wx(r);if(e.type==="Ed25519")return new Lc({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Mc({multihash:r,publicKey:e})}catch{let t=C(r.digest);return new Oc(new URL(t))}throw new ju("Supplied PeerID Multihash is invalid")}function yn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==jk&&r.code!==h4)throw new Wu("Supplied PeerID CID is invalid");if(r.code===h4){let e=C(r.multihash.digest);return new Oc(new URL(e))}return Ur(r.multihash)}function Yk(r){return r.code===Oh.code}function Xk(r){return r.code===l4.code}var Ks=class r extends un{protocolPrefix;constructor(e,t,n){super(e,t),this.protocolPrefix=n}static create(e,t,n){return new r(e,t,n)}async update(e,t=0){let n={operation:"update",record:e},s=(this.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",o;try{o=await this.processMessage(n,s)}catch(i){if(s!=="/db-p2p/cluster/1.0.0")o=await this.processMessage(n,"/db-p2p/cluster/1.0.0");else throw i}if(o?.redirect?.peers?.length){if(t>=2)throw new Error("Redirect loop detected in ClusterClient (max hops reached)");let i=this.peerId.toString(),a=o.redirect.peers.find(u=>u.id!==i)??o.redirect.peers[0],c=oe(a.id);if(a.id===i)throw new Error("Redirect loop detected in ClusterClient (same peer)");return this.recordCoordinatorForRecordIfSupported(e,c),await r.create(c,this.peerNetwork,this.protocolPrefix).update(e,t+1)}return o}recordCoordinatorForRecordIfSupported(e,t){let n=e?.message,s;if(n?.commit?.tailId)s=n.commit.tailId;else if(n?.pend?.transforms){let o=Object.keys(n.pend.transforms);o.length>0&&(s=o[0])}if(s){let o=new TextEncoder().encode(s),i=this.peerNetwork;typeof i?.recordCoordinator=="function"&&i.recordCoordinator(o,t)}}};var U0=new Map;function Kr(r,e){if(U0.has(r))throw new Error(`Block type ${r} (${e}) already registered (${U0.get(r)})`);return U0.set(r,e),r}function Rh(r,[e,t,n,s]){Array.isArray(s)?r[e].splice(t,n,...structuredClone(s)):r[e]=structuredClone(s)}function Qk(r,e){for(let t of e)Rh(r,t)}function es(r){if(!r)return[];let e=Object.keys(r.inserts??{}),t=Object.keys(r.updates??{}),n=r.deletes??[];return[...new Set([...e,...t,...n])]}function K0(){return{inserts:{},updates:{},deletes:[]}}function Nh(r,e){return{...r.inserts&&e in r.inserts?{insert:r.inserts[e]}:{},...r.updates&&e in r.updates?{updates:structuredClone(r.updates[e])}:{},...r.deletes?.includes(e)?{delete:!0}:{}}}function F0(r,e){return{inserts:r.insert?{[e]:r.insert}:{},updates:r.updates?{[e]:r.updates}:{},deletes:r.delete?[e]:[]}}function Rc(r,e){if(e.insert&&(r=e.insert),r&&e.updates&&Qk(r,e.updates),!e.delete)return r}function z0(r,e,t){return{inserts:{...r.inserts,...t.insert?{[e]:t.insert}:{}},updates:{...r.updates,...t.updates?{[e]:t.updates}:{}},deletes:[...r.deletes??[],...t.delete?[e]:[]]}}function Kt(r,e){return e??r}var Jk=Kr("TL","TreeLeaf"),Zk=Kr("TB","TreeBranch"),e7=Kt("entries"),t7=Kt("partitions"),r7=Kt("nodes");var o7=Kt("entries"),i7=Kt("priorId"),a7=Kt("nextId"),c7=Kr("CHD","ChainDataBlock"),l7=Kt("headId"),u7=Kt("tailId"),h7=Kr("CHH","ChainHeaderBlock");var G0={};z(G0,{base10:()=>w7});var QZ=new Uint8Array(0);function p4(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function cr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function m4(r){return new TextEncoder().encode(r)}function g4(r){return new TextDecoder().decode(r)}function f7(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var p7=f7,m7=p7,b4=m7;var $0=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},H0=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 w4(this,e)}},q0=class{decoders;constructor(e){this.decoders=e}or(e){return w4(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function w4(r,e){return new q0({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var V0=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new $0(e,t,n),this.decoder=new H0(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ai({name:r,prefix:e,encode:t,decode:n}){return new V0(r,e,t,n)}function ts({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=b4(t,r);return ai({prefix:e,name:r,encode:n,decode:o=>cr(s(o))})}function g7(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function y7(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function b7(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Re({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=b7(n);return ai({prefix:e,name:r,encode(o){return y7(o,n,t)},decode(o){return g7(o,s,t,r)}})}var w7=ts({prefix:"9",name:"base10",alphabet:"0123456789"});var W0={};z(W0,{base16:()=>x7,base16upper:()=>v7});var x7=Re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),v7=Re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var j0={};z(j0,{base2:()=>E7});var E7=Re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Y0={};z(Y0,{base256emoji:()=>T7});var x4=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}"),S7=x4.reduce((r,e,t)=>(r[t]=e,r),[]),I7=x4.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function A7(r){return r.reduce((e,t)=>(e+=S7[t],e),"")}function C7(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=I7[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var T7=ai({prefix:"\u{1F680}",name:"base256emoji",encode:A7,decode:C7});var X0={};z(X0,{base32:()=>ci,base32hex:()=>k7,base32hexpad:()=>M7,base32hexpadupper:()=>O7,base32hexupper:()=>L7,base32pad:()=>P7,base32padupper:()=>D7,base32upper:()=>_7,base32z:()=>R7});var ci=Re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),_7=Re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),P7=Re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),D7=Re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),k7=Re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),L7=Re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),M7=Re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),O7=Re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),R7=Re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Q0={};z(Q0,{base36:()=>Nc,base36upper:()=>N7});var Nc=ts({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),N7=ts({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var J0={};z(J0,{base58btc:()=>Fr,base58flickr:()=>B7});var Fr=ts({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),B7=ts({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Z0={};z(Z0,{base64:()=>U7,base64pad:()=>K7,base64url:()=>F7,base64urlpad:()=>z7});var U7=Re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),K7=Re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),F7=Re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),z7=Re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var e2={};z(e2,{base8:()=>$7});var $7=Re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var t2={};z(t2,{identity:()=>H7});var H7=ai({prefix:"\0",name:"identity",encode:r=>g4(r),decode:r=>m4(r)});var fee=new TextEncoder,pee=new TextDecoder;var n2={};z(n2,{identity:()=>dL});var G7=S4,v4=128,W7=127,j7=~W7,Y7=Math.pow(2,31);function S4(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Y7;)e[t++]=r&255|v4,r/=128;for(;r&j7;)e[t++]=r&255|v4,r>>>=7;return e[t]=r|0,S4.bytes=t-n+1,e}var X7=r2,Q7=128,E4=127;function r2(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw r2.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&E4)<<s:(i&E4)*Math.pow(2,s),s+=7}while(i>=Q7);return r2.bytes=o-n,t}var J7=Math.pow(2,7),Z7=Math.pow(2,14),eL=Math.pow(2,21),tL=Math.pow(2,28),rL=Math.pow(2,35),nL=Math.pow(2,42),sL=Math.pow(2,49),oL=Math.pow(2,56),iL=Math.pow(2,63),aL=function(r){return r<J7?1:r<Z7?2:r<eL?3:r<tL?4:r<rL?5:r<nL?6:r<sL?7:r<oL?8:r<iL?9:10},cL={encode:G7,decode:X7,encodingLength:aL},lL=cL,Bc=lL;function Uc(r,e=0){return[Bc.decode(r,e),Bc.decode.bytes]}function li(r,e,t=0){return Bc.encode(r,e,t),e}function ui(r){return Bc.encodingLength(r)}function di(r,e){let t=e.byteLength,n=ui(r),s=n+ui(t),o=new Uint8Array(s+t);return li(r,o,0),li(t,o,n),o.set(e,s),new hi(r,t,e,o)}function I4(r){let e=cr(r),[t,n]=Uc(e),[s,o]=Uc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new hi(t,s,i,e)}function A4(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&p4(r.bytes,t.bytes)}}var hi=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var C4=0,uL="identity",T4=cr;function hL(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return di(C4,T4(r))}var dL={code:C4,name:uL,encode:T4,digest:hL};var a2={};z(a2,{sha256:()=>pL,sha512:()=>mL});var i2=ne(Z("crypto"),1);var fL=20;function o2({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new s2(r,e,t,n,s)}var s2=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??fL,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?_4(n,this.code,t?.truncate):n.then(s=>_4(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _4(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return di(e,r)}var pL=o2({name:"sha2-256",code:18,encode:r=>cr(i2.default.createHash("sha256").update(r).digest())}),mL=o2({name:"sha2-512",code:19,encode:r=>cr(i2.default.createHash("sha512").update(r).digest())});function D4(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return yL(t,c2(r),e??Fr.encoder);default:return bL(t,c2(r),e??ci.encoder)}}var k4=new WeakMap;function c2(r){let e=k4.get(r);if(e==null){let t=new Map;return k4.set(r,t),t}return e}var Uh=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Fc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==wL)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=di(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&A4(e.multihash,n.multihash)}toString(e){return D4(this,e)}toJSON(){return{"/":D4(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??L4(n,s,o.bytes))}else if(t[xL]===!0){let{version:n,multihash:s,code:o}=t,i=I4(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Fc)throw new Error(`Version 0 CID must use dag-pb (code: ${Fc}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=L4(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Fc,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=cr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new hi(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=Uc(e.subarray(t));return t+=p,d},s=n(),o=Fc;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=gL(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return c2(o).set(n,e),o}};function gL(r,e){switch(r[0]){case"Q":{let t=e??Fr;return[Fr.prefix,t.decode(`${Fr.prefix}${r}`)]}case Fr.prefix:{let t=e??Fr;return[Fr.prefix,t.decode(r)]}case ci.prefix:{let t=e??ci;return[ci.prefix,t.decode(r)]}case Nc.prefix:{let t=e??Nc;return[Nc.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function yL(r,e,t){let{prefix:n}=t;if(n!==Fr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function bL(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Fc=112,wL=18;function L4(r,e,t){let n=ui(r),s=n+ui(e),o=new Uint8Array(s+t.byteLength);return li(r,o,0),li(e,o,n),o.set(t,s),o}var xL=Symbol.for("@ipld/js-cid/CID");var l2={...t2,...j0,...e2,...G0,...W0,...X0,...Q0,...J0,...Z0,...Y0},Bee={...a2,...n2};var O4=Z("node:buffer");function M4(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function R4(r=0){return M4(O4.Buffer.allocUnsafe(r))}function B4(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var N4=B4("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),u2=B4("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=R4(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),qee={utf8:N4,"utf-8":N4,hex:l2.base16,latin1:u2,ascii:u2,binary:u2,...l2};var Fs=class{static lockQueues=new Map;static async acquire(e){let t=this.lockQueues.get(e)??Promise.resolve(),n,s=new Promise(i=>{n=i});return this.lockQueues.set(e,s),await t,()=>{n(),this.lockQueues.get(e)===s&&this.lockQueues.delete(e)}}};var IL=Kr("DIH","DiaryHeaderBlock");var AL=Kr("TRE","TreeHeaderBlock"),CL=Kt("rootId");var b2=ne(Z("crypto"),1);var Ote=new Uint8Array(0);function Kh(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var TL=z4,K4=128,_L=127,PL=~_L,DL=Math.pow(2,31);function z4(r,e,t){e=e||[],t=t||0;for(var n=t;r>=DL;)e[t++]=r&255|K4,r/=128;for(;r&PL;)e[t++]=r&255|K4,r>>>=7;return e[t]=r|0,z4.bytes=t-n+1,e}var kL=h2,LL=128,F4=127;function h2(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw h2.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&F4)<<s:(i&F4)*Math.pow(2,s),s+=7}while(i>=LL);return h2.bytes=o-n,t}var ML=Math.pow(2,7),OL=Math.pow(2,14),RL=Math.pow(2,21),NL=Math.pow(2,28),BL=Math.pow(2,35),UL=Math.pow(2,42),KL=Math.pow(2,49),FL=Math.pow(2,56),zL=Math.pow(2,63),$L=function(r){return r<ML?1:r<OL?2:r<RL?3:r<NL?4:r<BL?5:r<UL?6:r<KL?7:r<FL?8:r<zL?9:10},HL={encode:TL,decode:kL,encodingLength:$L},qL=HL,d2=qL;function f2(r,e,t=0){return d2.encode(r,e,t),e}function p2(r){return d2.encodingLength(r)}function $4(r,e){let t=e.byteLength,n=p2(r),s=n+p2(t),o=new Uint8Array(s+t);return f2(r,o,0),f2(t,o,n),o.set(e,s),new m2(r,t,e,o)}var m2=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var WL=20;function y2({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new g2(r,e,t,n,s)}var g2=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??WL,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?H4(n,this.code,t?.truncate):n.then(s=>H4(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function H4(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return $4(e,r)}var q4=y2({name:"sha2-256",code:18,encode:r=>Kh(b2.default.createHash("sha256").update(r).digest())}),qte=y2({name:"sha2-512",code:19,encode:r=>Kh(b2.default.createHash("sha512").update(r).digest())});var Zte=Kt("priorHash");var zs=class{promise;response;error;t1=Date.now();duration;get isResponse(){return this.response!==void 0}get isError(){return this.error!==void 0}get isComplete(){return this.isResponse||this.isError}async result(){if(this.isResponse)return this.response;if(this.isError)throw this.error;return await this.promise}constructor(e){this.promise=e,e.then(t=>(this.duration=Date.now()-this.t1,this.response=t,t),t=>{this.duration=Date.now()-this.t1,this.error=t})}};function w2(r,e){return r.reduce((t,n)=>{let s=e(n);return(t[s]??=[]).push(n),t},{})}var T2=ne(Z("crypto"),1);var Qne=new Uint8Array(0);function fi(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var XL=X4,j4=128,QL=127,JL=~QL,ZL=Math.pow(2,31);function X4(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ZL;)e[t++]=r&255|j4,r/=128;for(;r&JL;)e[t++]=r&255|j4,r>>>=7;return e[t]=r|0,X4.bytes=t-n+1,e}var eM=x2,tM=128,Y4=127;function x2(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw x2.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Y4)<<s:(i&Y4)*Math.pow(2,s),s+=7}while(i>=tM);return x2.bytes=o-n,t}var rM=Math.pow(2,7),nM=Math.pow(2,14),sM=Math.pow(2,21),oM=Math.pow(2,28),iM=Math.pow(2,35),aM=Math.pow(2,42),cM=Math.pow(2,49),lM=Math.pow(2,56),uM=Math.pow(2,63),hM=function(r){return r<rM?1:r<nM?2:r<sM?3:r<oM?4:r<iM?5:r<aM?6:r<cM?7:r<lM?8:r<uM?9:10},dM={encode:XL,decode:eM,encodingLength:hM},fM=dM,v2=fM;function E2(r,e,t=0){return v2.encode(r,e,t),e}function S2(r){return v2.encodingLength(r)}function Q4(r,e){let t=e.byteLength,n=S2(r),s=n+S2(t),o=new Uint8Array(s+t);return E2(r,o,0),E2(t,o,n),o.set(e,s),new I2(r,t,e,o)}var I2=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var gM=20;function C2({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new A2(r,e,t,n,s)}var A2=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??gM,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?J4(n,this.code,t?.truncate):n.then(s=>J4(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function J4(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Q4(e,r)}var zr=C2({name:"sha2-256",code:18,encode:r=>fi(T2.default.createHash("sha256").update(r).digest())}),ase=C2({name:"sha2-512",code:19,encode:r=>fi(T2.default.createHash("sha512").update(r).digest())});function yM(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var bM=yM,wM=bM,Z4=wM;var _2=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},P2=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 ev(this,e)}},D2=class{decoders;constructor(e){this.decoders=e}or(e){return ev(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ev(r,e){return new D2({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var k2=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new _2(e,t,n),this.decoder=new P2(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function xM({name:r,prefix:e,encode:t,decode:n}){return new k2(r,e,t,n)}function L2({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Z4(t,r);return xM({prefix:e,name:r,encode:n,decode:o=>fi(s(o))})}var Fh=L2({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pse=L2({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lv=ne(U2(),1),VM="optimystic:db-p2p";function ur(r){return(0,lv.default)(`${VM}:${r}`)}var fe=ur("cluster-member"),ut;(function(r){r[r.Promising=0]="Promising",r[r.OurPromiseNeeded=1]="OurPromiseNeeded",r[r.OurCommitNeeded=2]="OurCommitNeeded",r[r.Consensus=3]="Consensus",r[r.Rejected=4]="Rejected",r[r.Propagating=5]="Propagating"})(ut||(ut={}));function K2(r){return new Wh(r.storageRepo,r.peerNetwork,r.peerId,r.protocolPrefix,r.partitionDetector,r.fretService,r.validator)}var GM=600*1e3,Wh=class{storageRepo;peerNetwork;peerId;protocolPrefix;partitionDetector;fretService;validator;activeTransactions=new Map;executedTransactions=new Map;cleanupQueue=[];pendingUpdates=new Map;constructor(e,t,n,s,o,i,a){this.storageRepo=e,this.peerNetwork=t,this.peerId=n,this.protocolPrefix=s,this.partitionDetector=o,this.fretService=i,this.validator=a,setInterval(()=>this.queueExpiredTransactions(),6e4),setInterval(()=>this.processCleanupQueue(),1e3)}wasTransactionExecuted(e){return this.executedTransactions.has(e)}async update(e){let t=this.pendingUpdates.get(e.messageHash);t&&(fe("cluster-member:concurrent-update-wait",{messageHash:e.messageHash}),await t);let n=this.processUpdate(e);this.pendingUpdates.set(e.messageHash,n);try{return await n}finally{setTimeout(()=>{this.pendingUpdates.delete(e.messageHash)},100)}}async processUpdate(e){let t=this.peerId.toString(),n=e.commits[t]?"commit":e.promises[t]?"promise":"initial";if(fe("cluster-member:incoming",{messageHash:e.messageHash,phase:n,peerCount:Object.keys(e.peers).length,promiseCount:Object.keys(e.promises).length,commitCount:Object.keys(e.commits).length,existingTransaction:this.activeTransactions.has(e.messageHash)}),this.fretService&&e.networkSizeHint&&e.networkSizeConfidence)try{this.fretService.reportNetworkSize(e.networkSizeHint,e.networkSizeConfidence,"cluster")}catch{}await this.validateRecord(e);let s=this.activeTransactions.get(e.messageHash),o=s?.record||e;s&&fe("cluster-member:merge-start",{messageHash:e.messageHash,existingPromises:Object.keys(s.record.promises??{}),existingCommits:Object.keys(s.record.commits??{}),incomingPromises:Object.keys(e.promises??{}),incomingCommits:Object.keys(e.commits??{})}),s&&(o=await this.mergeRecords(s.record,e),fe("cluster-member:merge-complete",{messageHash:e.messageHash,mergedPromises:Object.keys(o.promises??{}),mergedCommits:Object.keys(o.commits??{})}));let i=await this.getTransactionPhase(o);fe("cluster-member:phase",{messageHash:e.messageHash,phase:i,promises:Object.keys(o.promises??{}),commits:Object.keys(o.commits??{})});let a=!0;switch(i){case ut.OurPromiseNeeded:fe("cluster-member:action-promise",{messageHash:e.messageHash}),o=await this.handlePromiseNeeded(o),fe("cluster-member:action-promise-complete",{messageHash:e.messageHash,promises:Object.keys(o.promises??{})});break;case ut.OurCommitNeeded:fe("cluster-member:action-commit",{messageHash:e.messageHash}),o=await this.handleCommitNeeded(o),fe("cluster-member:action-commit-complete",{messageHash:e.messageHash,commits:Object.keys(o.commits??{})}),await this.getTransactionPhase(o)===ut.Consensus&&(fe("cluster-member:action-consensus-after-commit",{messageHash:e.messageHash}),await this.handleConsensus(o)),a=!1;break;case ut.Consensus:fe("cluster-member:action-consensus",{messageHash:e.messageHash}),n!=="commit"?await this.handleConsensus(o):fe("cluster-member:consensus-skip-already-committed",{messageHash:e.messageHash}),a=!1;break;case ut.Rejected:fe("cluster-member:action-rejected",{messageHash:e.messageHash}),await this.handleRejection(o),a=!1;break;case ut.Propagating:fe("cluster-member:phase-propagating",{messageHash:e.messageHash}),a=!1;break;case ut.Promising:fe("cluster-member:phase-promising-blocked",{messageHash:e.messageHash});break}if(a){let c=this.setupTimeouts(o);this.activeTransactions.set(e.messageHash,{record:o,lastUpdate:Date.now(),promiseTimeout:c.promiseTimeout,resolutionTimeout:c.resolutionTimeout}),fe("cluster-member:state-persist",{messageHash:e.messageHash,storedPromises:Object.keys(o.promises??{}),storedCommits:Object.keys(o.commits??{})})}else fe("cluster-member:state-clear",{messageHash:e.messageHash}),this.clearTransaction(e.messageHash);return fe("cluster-member:update-complete",{messageHash:e.messageHash,promiseCount:Object.keys(o.promises).length,commitCount:Object.keys(o.commits).length}),o}async mergeRecords(e,t){if(fe("cluster-member:merge-records",{messageHash:e.messageHash,existingPromises:Object.keys(e.promises??{}),existingCommits:Object.keys(e.commits??{}),incomingPromises:Object.keys(t.promises??{}),incomingCommits:Object.keys(t.commits??{})}),e.messageHash!==t.messageHash)throw new Error("Message hash mismatch");if(JSON.stringify(e.message)!==JSON.stringify(t.message))throw new Error("Message content mismatch");if(JSON.stringify(e.peers)!==JSON.stringify(t.peers))throw new Error("Peers mismatch");return{...e,promises:{...e.promises,...t.promises},commits:{...e.commits,...t.commits}}}async validateRecord(e){let t=await this.computeMessageHash(e.message);if(t!==e.messageHash)throw new Error(`Message hash mismatch: expected=${t}, received=${e.messageHash}`);if(await this.validateSignatures(e),e.message.expiration&&e.message.expiration<Date.now())throw new Error("Transaction expired")}async computeMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),n=await zr.digest(t);return Fh.encode(n.digest)}async validateSignatures(e){let t=await this.computePromiseHash(e);for(let[s,o]of Object.entries(e.promises))if(!await this.verifySignature(s,t,o))throw new Error(`Invalid promise signature from ${s}`);let n=await this.computeCommitHash(e);for(let[s,o]of Object.entries(e.commits))if(!await this.verifySignature(s,n,o))throw new Error(`Invalid commit signature from ${s}`)}async computePromiseHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)),n=await zr.digest(t);return C(n.digest,"base64url")}async computeCommitHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)+JSON.stringify(e.promises)),n=await zr.digest(t);return C(n.digest,"base64url")}async verifySignature(e,t,n){return!0}async getTransactionPhase(e){let t=Object.keys(e.peers).length,n=Object.keys(e.promises).length,s=Object.keys(e.commits).length,o=this.peerId.toString(),i=Object.values(e.promises).filter(l=>l.type==="reject"),a=Object.values(e.commits).filter(l=>l.type==="reject");if(i.length>0||this.hasMajority(a.length,t))return ut.Rejected;if(!e.promises[o]&&!this.hasConflict(e))return ut.OurPromiseNeeded;if(n<t)return ut.Promising;if(n===t&&!e.commits[o])return ut.OurCommitNeeded;let c=Object.values(e.commits).filter(l=>l.type==="approve");return this.hasMajority(c.length,t)?ut.Consensus:ut.Propagating}hasMajority(e,t){return e>t/2}async handlePromiseNeeded(e){let t=await this.validatePendOperations(e),n=t.valid?{type:"approve",signature:"approved"}:{type:"reject",signature:"rejected",rejectReason:t.reason};return t.valid||fe("cluster-member:validation-rejected",{messageHash:e.messageHash,reason:t.reason}),{...e,promises:{...e.promises,[this.peerId.toString()]:n}}}async validatePendOperations(e){for(let t of e.message.operations)if("pend"in t){let n=t.pend;if(n.rev!==void 0){let s=es(n.transforms),o=await this.storageRepo.get({blockIds:s});for(let i of s){let c=o[i]?.state?.latest?.rev;if(c!==void 0&&c>=n.rev)return fe("cluster-member:validation-stale-revision",{messageHash:e.messageHash,blockId:i,requestedRev:n.rev,latestRev:c}),{valid:!1,reason:`stale revision: block ${i} at rev ${c}, requested rev ${n.rev}`}}}if(this.validator&&n.transaction&&n.operationsHash){let s=await this.validator.validate(n.transaction,n.operationsHash);if(!s.valid)return{valid:!1,reason:s.reason}}}return{valid:!0}}async handleCommitNeeded(e){if(this.hasLocalCommit(e))return e;let t={type:"approve",signature:"committed"};return{...e,commits:{...e.commits,[this.peerId.toString()]:t}}}async handleConsensus(e){if(this.executedTransactions.has(e.messageHash)){fe("cluster-member:consensus-already-executed",{messageHash:e.messageHash});return}this.executedTransactions.set(e.messageHash,Date.now());try{for(let t of e.message.operations)if("get"in t)await this.storageRepo.get(t.get);else if("pend"in t){let n=await this.storageRepo.pend(t.pend);if(!n.success)throw fe("cluster-member:consensus-pend-failed",{messageHash:e.messageHash,actionId:t.pend.actionId,reason:n.reason,hasMissing:!!n.missing?.length,hasPending:!!n.pending?.length}),new Error(`Consensus pend failed for action ${t.pend.actionId}: ${n.reason??"stale revision"}`)}else if("commit"in t){let n=await this.storageRepo.commit(t.commit);if(!n.success)throw fe("cluster-member:consensus-commit-failed",{messageHash:e.messageHash,actionId:t.commit.actionId,reason:n.reason,hasMissing:!!n.missing?.length}),new Error(`Consensus commit failed for action ${t.commit.actionId}: ${n.reason??"stale revision"}`)}else"cancel"in t&&await this.storageRepo.cancel(t.cancel.actionRef)}catch(t){throw this.executedTransactions.delete(e.messageHash),t}}async handleRejection(e){}setupTimeouts(e){return e.message.expiration?{promiseTimeout:setTimeout(()=>this.handleExpiration(e.messageHash),e.message.expiration-Date.now()),resolutionTimeout:setTimeout(()=>this.resolveWithPeers(e.messageHash),e.message.expiration+5e3-Date.now())}:{}}hasConflict(e){let t=Date.now(),n=2e3,s=this.getAffectedBlockIds(e.message.operations);fe("cluster-member:hasConflict-check",{messageHash:e.messageHash,activeCount:this.activeTransactions.size,incomingBlockIds:s});for(let[o,i]of Array.from(this.activeTransactions.entries())){if(o===e.messageHash)continue;let a=this.getAffectedBlockIds(i.record.message.operations);if(fe("cluster-member:hasConflict-compare",{existing:o,incoming:e.messageHash,existingBlockIds:a,incomingBlockIds:s}),t-i.lastUpdate>n){fe("cluster-member:stale-cleanup",{messageHash:o,age:t-i.lastUpdate}),this.clearTransaction(o);continue}if(this.operationsConflict(i.record.message.operations,e.message.operations)){if(this.resolveRace(i.record,e)==="keep-existing")return fe("cluster-member:race-keep-existing",{existing:o,incoming:e.messageHash}),!0;fe("cluster-member:race-accept-incoming",{existing:o,incoming:e.messageHash}),this.clearTransaction(o);continue}}return!1}resolveRace(e,t){let n=Object.keys(e.promises).length,s=Object.keys(t.promises).length;return n>s?"keep-existing":s>n?"accept-incoming":e.messageHash>t.messageHash?"keep-existing":"accept-incoming"}operationsConflict(e,t){let n=this.getActionId(e),s=this.getActionId(t);if(n&&s&&n===s)return!1;let o=new Set(this.getAffectedBlockIds(e)),i=new Set(this.getAffectedBlockIds(t));for(let a of Array.from(o))if(i.has(a))return fe("cluster-member:conflict-detected",{blocks1:Array.from(o),blocks2:Array.from(i),conflictingBlock:a}),!0;return!1}getActionId(e){for(let t of e){if("pend"in t)return t.pend.actionId;if("commit"in t)return t.commit.actionId;if("cancel"in t)return t.cancel.actionRef.actionId}}getAffectedBlockIds(e){let t=new Set;for(let n of e)"get"in n?n.get.blockIds.forEach(s=>t.add(s)):"pend"in n?es(n.pend.transforms).forEach(s=>t.add(s)):"commit"in n?n.commit.blockIds.forEach(s=>t.add(s)):"cancel"in n&&n.cancel.actionRef.blockIds.forEach(s=>t.add(s));return Array.from(t)}async propagateIfNeeded(e){let t=[];for(let[n,s]of Object.entries(e.peers))if(n!==this.peerId.toString())try{let o=Ks.create(oe(n),this.peerNetwork,this.protocolPrefix);t.push(o.update(e))}catch(o){console.error(`Failed to propagate to peer ${n}:`,o)}await Promise.allSettled(t)}async handleExpiration(e){let t=this.activeTransactions.get(e);if(t&&!t.record.promises[this.peerId.toString()]){let n={type:"reject",signature:"rejected",rejectReason:"Transaction expired"},s={...t.record,promises:{...t.record.promises,[this.peerId.toString()]:n}};this.activeTransactions.set(e,{...t,record:s}),await this.propagateIfNeeded(s)}}async resolveWithPeers(e){fe("cluster-member:resolve-skipped",{messageHash:e,reason:"coordinator-handles-retry"})}queueExpiredTransactions(){let e=Date.now();for(let[n,s]of Array.from(this.activeTransactions.entries()))s.record.message.expiration&&s.record.message.expiration<e&&this.cleanupQueue.push(n);let t=e-GM;for(let[n,s]of Array.from(this.executedTransactions.entries()))s<t&&this.executedTransactions.delete(n)}async processCleanupQueue(){for(;this.cleanupQueue.length>0;){let e=this.cleanupQueue.shift();if(!e)continue;let t=this.activeTransactions.get(e);if(!t)continue;let n=await this.getTransactionPhase(t.record);n!==ut.Consensus&&n!==ut.Rejected&&this.activeTransactions.delete(e)}}hasLocalCommit(e){let t=this.peerId.toString();return!!e.commits[t]}clearTransaction(e){let t=this.activeTransactions.get(e);if(!t){fe("cluster-member:clear-miss",{messageHash:e});return}t.promiseTimeout&&clearTimeout(t.promiseTimeout),t.resolutionTimeout&&clearTimeout(t.resolutionTimeout),this.activeTransactions.delete(e),fe("cluster-member:clear-done",{messageHash:e,remaining:Array.from(this.activeTransactions.keys())})}};function F2(r={}){return e=>new jh(e,r)}var jh=class{protocol;maxInboundStreams;maxOutboundStreams;log;cluster;components;running;k;configuredClusterSize;allowDownsize;sizeTolerance;responsibilityK;constructor(e,t={}){this.components=e,this.protocol=t.protocol??(t.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.log=e.logger.forComponent(t.logPrefix??"db-p2p:cluster"),this.cluster=e.cluster,this.running=!1,this.k=t.kBucketSize??10,this.configuredClusterSize=t.configuredClusterSize??10,this.allowDownsize=t.allowClusterDownsize??!0,this.sizeTolerance=t.clusterSizeTolerance??.5,this.responsibilityK=t.responsibilityK??1}[Symbol.toStringTag]="@libp2p/cluster";async start(){this.running||(await this.components.registrar.handle(this.protocol,this.handleIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.running=!0)}async stop(){this.running&&(await this.components.registrar.unhandle(this.protocol),this.running=!1)}handleIncomingStream(e,t){let n=t.remotePeer,s=async function*(o){for await(let i of o){let a=new TextDecoder().decode(i.subarray()),c=JSON.parse(a),l;if(c.operation==="update"){let d=c.record?.message?.commit?.tailId??c.record?.message?.pend?Object.keys(c.record.message.pend.transforms)[0]:void 0;l=await this.cluster.update(c.record)}else throw new Error(`Unknown operation: ${c.operation}`);if(c.operation==="update"){let d=l;this.log("cluster-service:pre-serialize",{messageHash:d?.messageHash,responseType:typeof l,hasPromises:"promises"in(d??{}),hasCommits:"commits"in(d??{}),promiseKeys:Object.keys(d?.promises??{}),commitKeys:Object.keys(d?.commits??{}),promiseValues:d?.promises,commitValues:d?.commits})}let u=JSON.stringify(l);if(c.operation==="update"){let d=JSON.parse(u);this.log("cluster-service:post-serialize",{messageHash:d?.messageHash,promiseKeys:Object.keys(d?.promises??{}),commitKeys:Object.keys(d?.commits??{})})}yield new TextEncoder().encode(u)}};(async()=>{try{let o=rt(e,i=>gr(i),s.bind(this),i=>or(i));for await(let i of o)e.send(i);await e.close()}catch(o){this.log.error("error handling cluster protocol message from %p - %e",n,o),e.abort(o instanceof Error?o:new Error(String(o)))}})()}};var z2=class r extends un{protocolPrefix;constructor(e,t,n){super(e,t),this.protocolPrefix=n}static create(e,t,n){return new r(e,t,n)}async get(e,t){return this.processRepoMessage([{get:e}],t)}async pend(e,t){return this.processRepoMessage([{pend:e}],t)}async cancel(e,t){return this.processRepoMessage([{cancel:{actionRef:e}}],t)}async commit(e,t){return this.processRepoMessage([{commit:e}],t)}async processRepoMessage(e,t,n=0){let s={operations:e,expiration:t.expiration},o=t.expiration??Date.now()+3e4,i=Math.max(1,o-Date.now()),a=async u=>await Promise.race([u(),new Promise((d,p)=>setTimeout(()=>p(new Error("RepoClient timeout")),i))]),c,l=(this.protocolPrefix??"/db-p2p")+"/repo/1.0.0";if(c=await a(()=>super.processMessage(s,l,{signal:t?.signal})),c?.redirect?.peers?.length){if(n>=2)throw new Error("Redirect loop detected in RepoClient (max hops reached)");let u=this.peerId.toString(),d=c.redirect.peers.find(h=>h.id!==u)??c.redirect.peers[0],p=oe(d.id);if(d.id===u)throw new Error("Redirect loop detected in RepoClient (same peer)");return this.recordCoordinatorForOpsIfSupported(e,p),await r.create(p,this.peerNetwork,this.protocolPrefix).processRepoMessage(e,t,n+1)}return c}extractKeyFromOperations(e){let t=e[0];if("get"in t){let n=t.get.blockIds[0];return n?new TextEncoder().encode(n):void 0}if("pend"in t){let n=Object.keys(t.pend.transforms)[0];return n?new TextEncoder().encode(n):void 0}if("commit"in t)return new TextEncoder().encode(t.commit.tailId)}recordCoordinatorForOpsIfSupported(e,t){let n=this.extractKeyFromOperations(e),s=this.peerNetwork;n!=null&&typeof s?.recordCoordinator=="function"&&s.recordCoordinator(n,t)}};var ee=ur("cluster"),$c=class{keyNetwork;createClusterClient;cfg;localCluster;fretService;transactions=new Map;retryInitialIntervalMs=2e3;retryBackoffFactor=2;retryMaxIntervalMs=3e4;retryMaxAttempts=5;constructor(e,t,n,s,o){this.keyNetwork=e,this.createClusterClient=t,this.cfg=n,this.localCluster=s,this.fretService=o}async createMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),n=await zr.digest(t);return Fh.encode(n.digest)}async getClusterForBlock(e){let t=new TextEncoder().encode(e);try{let n=await this.keyNetwork.findCluster(t),s=Object.keys(n??{});return ee("cluster-tx:cluster-members",{blockId:e,peerIds:s}),n}catch(n){return ee("WARN findCluster failed for %s: %o",e,n),{}}}makeRecord(e,t,n){let s=Object.keys(e??{}).length,o={messageHash:t,peers:e,message:n,coordinatingBlockIds:n.coordinatingBlockIds,promises:{},commits:{},suggestedClusterSize:s||void 0,minRequiredSize:this.cfg.allowClusterDownsize?void 0:this.cfg.clusterSize};if(this.fretService)try{let i=this.fretService.getNetworkSizeEstimate();i.size_estimate>0&&(o.networkSizeHint=i.size_estimate,o.networkSizeConfidence=i.confidence)}catch{}return o}async executeClusterTransaction(e,t,n){let s=await this.getClusterForBlock(e),o=await this.createMessageHash(t),i=this.makeRecord(s,o,t);ee("cluster-tx:start",{messageHash:o,blockId:e,peerCount:Object.keys(s??{}).length,allowDownsize:this.cfg.allowClusterDownsize,configuredSize:this.cfg.clusterSize,suggestedSize:i.suggestedClusterSize,minRequiredSize:i.minRequiredSize});let a=this.executeTransaction(s,i),c=new zs(a),l={messageHash:o,record:i,pending:c,lastUpdate:Date.now()};this.transactions.set(o,l),ee("cluster-tx:transaction-store",{messageHash:o,transactionKeys:Array.from(this.transactions.keys())});try{let u=await c.result(),d=this.localCluster?.wasTransactionExecuted?.(o)??!1;return{record:u,localExecuted:d}}finally{let u=this.transactions.get(o),d=u?.retry?{attempt:u.retry.attempt,pending:Array.from(u.retry.pendingPeers??[])}:void 0;ee("cluster-tx:complete",{messageHash:o,finalPromises:u?Object.keys(u.record.promises??{}):void 0,finalCommits:u?Object.keys(u.record.commits??{}):void 0,retry:d}),u?.retry||setTimeout(()=>{this.transactions.delete(o),ee("cluster-tx:transaction-remove",{messageHash:o,remaining:Array.from(this.transactions.keys())})},100)}}async executeTransaction(e,t){let n=Object.keys(e).length;if(n<this.cfg.minAbsoluteClusterSize){if(!await this.validateSmallCluster(n,e))throw ee("cluster-tx:reject-too-small",{peerCount:n,minRequired:this.cfg.minAbsoluteClusterSize}),new Error(`Cluster size ${n} below minimum ${this.cfg.minAbsoluteClusterSize} and not validated`);ee("cluster-tx:small-cluster-validated",{peerCount:n})}if(!this.cfg.allowClusterDownsize&&n<this.cfg.clusterSize)throw ee("cluster-tx:reject-downsize",{peerCount:n,required:this.cfg.clusterSize}),new Error(`Cluster size ${n} below configured minimum ${this.cfg.clusterSize}`);let s=await this.collectPromises(e,t),o=Math.ceil(n*this.cfg.superMajorityThreshold),i=s.record.promises,a=Object.values(i).filter(u=>u.type==="approve").length,c=Object.values(i).filter(u=>u.type==="reject").length,l=n-o;if(c>l){let u=Object.entries(i).filter(([d,p])=>p.type==="reject").map(([d,p])=>`${d}: ${p.rejectReason??"unknown"}`).join("; ");throw ee("cluster-tx:rejected-by-validators",{messageHash:t.messageHash,peerCount:n,rejections:c,maxAllowed:l,reasons:u}),this.updateTransactionRecord(s.record,"rejected-by-validators"),new Error(`Transaction rejected by validators (${c}/${n} rejected): ${u}`)}if(n>1&&a<o)throw ee("cluster-tx:supermajority-failed",{messageHash:t.messageHash,peerCount:n,approvals:a,rejections:c,superMajority:o,threshold:this.cfg.superMajorityThreshold}),this.updateTransactionRecord(s.record,"supermajority-failed"),new Error(`Failed to get super-majority: ${a}/${n} approvals (needed ${o}, ${c} rejections)`);return await this.commitTransaction(s.record)}async getClusterSize(e){let t=await this.getClusterForBlock(e);return Object.keys(t??{}).length}async validateSmallCluster(e,t){if(this.fretService)try{let n=this.fretService.getNetworkSizeEstimate();if(n.confidence>.5){let s=Math.floor(Math.log10(n.size_estimate+1)),o=Math.floor(Math.log10(e+1));if(Math.abs(s-o)<=1)return ee("cluster-tx:small-cluster-validated-by-fret",{localSize:e,fretEstimate:n.size_estimate,confidence:n.confidence,sources:n.sources}),!0}}catch{}return ee("cluster-tx:small-cluster-accepted-without-validation",{localSize:e,reason:"no-confident-network-size-estimate"}),!0}async collectPromises(e,t){let n=Object.keys(e),s=[],o=n.map(l=>{let u=this.localCluster&&l===this.localCluster.peerId.toString();ee("cluster-tx:promise-request",{messageHash:t.messageHash,peerId:l,isLocal:u});let d=u?this.localCluster.update(t):this.createClusterClient(oe(l)).update(t);return new zs(d)}),i=await Promise.all(o.map((l,u)=>l.result().then(d=>{let p=n[u];return ee("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:p,success:!0,returnedPromises:Object.keys(d.promises??{}),returnedCommits:Object.keys(d.commits??{})}),s.push({peerId:p,success:!0}),d}).catch(d=>{let p=n[u];return ee("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:p,success:!1,error:d}),s.push({peerId:p,success:!1,error:d instanceof Error?d.message:String(d)}),null}))),a=s.filter(l=>l.success).map(l=>l.peerId),c=s.filter(l=>!l.success);ee("cluster-tx:promise-summary",{messageHash:t.messageHash,successes:a,failures:c}),ee("cluster-tx:promise-merge-begin",{messageHash:t.messageHash,initialPromises:Object.keys(t.promises??{}),transactionsKeys:Array.from(this.transactions.keys()),hasTransaction:this.transactions.has(t.messageHash)});for(let l of i.filter(Boolean)){ee("cluster-tx:promise-merge-input",{messageHash:t.messageHash,resultFrom:Object.keys(l.promises??{}),recordBefore:Object.keys(t.promises??{})});let u=Object.keys(l.promises??{});if(ee("cluster-tx:promise-merge-result",{messageHash:t.messageHash,peerPromises:u}),typeof t.suggestedClusterSize=="number"&&typeof l.suggestedClusterSize=="number"){let d=l.suggestedClusterSize,p=Object.keys(e).length,f=Math.ceil(Math.max(1,d*this.cfg.clusterSizeTolerance));Math.abs(p-d)>f&&ee("cluster-tx:size-variance",{expected:d,actual:p,tolerance:this.cfg.clusterSizeTolerance})}t.promises={...t.promises,...l.promises},ee("cluster-tx:promise-merge-after",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})})}return ee("cluster-tx:promise-merge",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})}),ee("cluster-tx:promise-merge-end",{messageHash:t.messageHash,finalPromises:Object.keys(t.promises??{}),transactionsEntry:this.transactions.get(t.messageHash)}),this.updateTransactionRecord(t,"after-promises"),{record:t}}async commitTransaction(e){let t=Object.keys(e.peers),n=[],s={...e},o=t.map(f=>{let h=this.localCluster&&f===this.localCluster.peerId.toString();ee("cluster-tx:commit-request",{messageHash:e.messageHash,peerId:f,isLocal:h});let m=h?this.localCluster.update(s):this.createClusterClient(oe(f)).update(s);return new zs(m)}),i=await Promise.all(o.map((f,h)=>f.result().then(m=>{let g=t[h];return ee("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!0}),n.push({peerId:g,success:!0}),m}).catch(m=>{let g=t[h];return ee("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!1,error:m}),n.push({peerId:g,success:!1,error:m instanceof Error?m.message:String(m)}),null}))),a=n.filter(f=>f.success).map(f=>f.peerId),c=n.filter(f=>!f.success);ee("cluster-tx:commit-summary",{messageHash:e.messageHash,successes:a,failures:c}),ee("cluster-tx:commit-merge-begin",{messageHash:e.messageHash,initialCommits:Object.keys(e.commits??{}),transactionsEntry:this.transactions.get(e.messageHash)});for(let f of i.filter(Boolean))ee("cluster-tx:commit-merge-input",{messageHash:e.messageHash,resultFrom:Object.keys(f.commits??{}),recordBefore:Object.keys(e.commits??{})}),ee("cluster-tx:commit-merge-result",{messageHash:e.messageHash,peerCommits:Object.keys(f.commits??{})}),e.commits={...e.commits,...f.commits},ee("cluster-tx:commit-merge-after",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})});ee("cluster-tx:commit-merge",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})}),ee("cluster-tx:commit-merge-end",{messageHash:e.messageHash,finalCommits:Object.keys(e.commits??{}),transactionsEntry:this.transactions.get(e.messageHash)}),this.updateTransactionRecord(e,"after-commit");let l=Object.keys(e.peers).length,u=Math.floor(l*this.cfg.simpleMajorityThreshold)+1,d=Object.keys(e.commits).length;if(d>=u&&(ee("cluster-tx:commit-majority-reached",{messageHash:e.messageHash,commitCount:d,simpleMajority:u,peerCount:l,threshold:this.cfg.simpleMajorityThreshold}),this.localCluster))try{await this.localCluster.update(e)}catch(f){ee("cluster-tx:local-execution-error",{messageHash:e.messageHash,error:f instanceof Error?f.message:String(f)})}let p=c.map(f=>f.peerId);return p.length>0?this.scheduleCommitRetry(e.messageHash,e,p):this.clearRetry(e.messageHash),e}updateTransactionRecord(e,t){let n=this.transactions.get(e.messageHash);if(!n){ee("cluster-tx:transaction-update-miss",{messageHash:e.messageHash,stage:t});return}n.record={...e},n.lastUpdate=Date.now(),ee("cluster-tx:transaction-update",{messageHash:e.messageHash,stage:t,promises:Object.keys(e.promises??{}),commits:Object.keys(e.commits??{})})}scheduleCommitRetry(e,t,n){let s=this.transactions.get(e);if(!s)return;let o=s.retry,i=(o?.attempt??0)+1;if(i>this.retryMaxAttempts){ee("cluster-tx:retry-abort",{messageHash:e,missingPeers:n});return}if(n.length===0){this.clearRetry(e);return}let a=new Set(n),c=o?Math.min(o.intervalMs*this.retryBackoffFactor,this.retryMaxIntervalMs):this.retryInitialIntervalMs;o?.timer&&clearTimeout(o.timer);let l=setTimeout(()=>{this.retryCommits(e)},c);s.retry={pendingPeers:a,attempt:i,intervalMs:c,timer:l},ee("cluster-tx:retry-scheduled",{messageHash:e,attempt:i,missingPeers:n,delayMs:c})}async retryCommits(e){let t=this.transactions.get(e);if(!t?.retry)return;let{pendingPeers:n,attempt:s}=t.retry;if(n.size===0){this.clearRetry(e);return}let o=Array.from(n),i=t.record;ee("cluster-tx:retry-start",{messageHash:e,attempt:s,peerIds:o});let a=await Promise.all(o.map(async u=>{let d=this.localCluster&&u===this.localCluster.peerId.toString(),p={...i,commits:i.commits};try{let f=d?await this.localCluster.update(p):await this.createClusterClient(oe(u)).update(p);return t.record.commits={...t.record.commits,...f.commits},{peerId:u,success:!0}}catch(f){return{peerId:u,success:!1,error:f instanceof Error?f.message:String(f)}}})),c=a.filter(u=>u.success).map(u=>u.peerId),l=a.filter(u=>!u.success);for(let u of c)n.delete(u);if(ee("cluster-tx:retry-complete",{messageHash:e,attempt:s,successes:c,failures:l}),n.size===0){ee("cluster-tx:retry-finished",{messageHash:e}),this.clearRetry(e);return}this.transactions.has(e)&&this.scheduleCommitRetry(e,t.record,Array.from(n))}clearRetry(e){let t=this.transactions.get(e);t?.retry&&(t.retry.timer&&clearTimeout(t.retry.timer),t.retry=void 0,setTimeout(()=>{this.transactions.delete(e),ee("cluster-tx:transaction-remove",{messageHash:e,remaining:Array.from(this.transactions.keys())})},100))}};var Hs=ur("coordinator-repo");function $2(r,e,t,n){return s=>new Yh(r,e,s.storageRepo,t,s.localCluster,s.localPeerId,n,s.clusterLatestCallback)}var Yh=class{keyNetwork;createClusterClient;storageRepo;clusterLatestCallback;coordinator;DEFAULT_TIMEOUT=3e4;constructor(e,t,n,s,o,i,a,c){this.keyNetwork=e,this.createClusterClient=t,this.storageRepo=n,this.clusterLatestCallback=c;let l={clusterSize:s?.clusterSize??10,superMajorityThreshold:s?.superMajorityThreshold??.75,simpleMajorityThreshold:s?.simpleMajorityThreshold??.51,minAbsoluteClusterSize:s?.minAbsoluteClusterSize??3,allowClusterDownsize:s?.allowClusterDownsize??!0,clusterSizeTolerance:s?.clusterSizeTolerance??.5,partitionDetectionWindow:s?.partitionDetectionWindow??6e4},u=o&&i?{update:o.update.bind(o),peerId:i,wasTransactionExecuted:o.wasTransactionExecuted?.bind(o)}:void 0;this.coordinator=new $c(e,t,l,u,a)}async get(e,t){let n=await this.storageRepo.get(e,t),s=t?.skipClusterFetch;if(this.clusterLatestCallback&&!s){for(let o of e.blockIds)if(!n[o]?.state?.latest)try{await this.fetchBlockFromCluster(o);let a=await this.storageRepo.get({blockIds:[o],context:e.context},t);a[o]&&(n[o]=a[o])}catch(a){Hs("cluster-fetch:error",{blockId:o,error:a.message})}}return n}async fetchBlockFromCluster(e){if(!this.clusterLatestCallback)return;let t=await this.queryClusterForLatest(e);t&&(await this.storageRepo.get({blockIds:[e],context:{committed:[t],rev:t.rev}}),Hs("cluster-fetch:synced",{blockId:e,rev:t.rev}))}async queryClusterForLatest(e){let t=new TextEncoder().encode(e),n=await this.keyNetwork.findCluster(t);if(!n||Object.keys(n).length===0)return;let s=Object.keys(n),o,i=(c,l)=>Promise.race([c,new Promise(u=>setTimeout(()=>u(void 0),l))]),a=await Promise.allSettled(s.map(c=>{let l=oe(c);return i(this.clusterLatestCallback(l,e),3e3)}));for(let c of a)if(c.status==="fulfilled"&&c.value){let l=c.value;(!o||l.rev>o.rev)&&(o=l)}return o}async pend(e,t){let n=Object.keys(e.transforms),s=t?.coordinatingBlockIds??n;if(await this.coordinator.getClusterSize(s[0])<=1)return await this.storageRepo.pend(e,t);let i={operations:[{pend:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT,coordinatingBlockIds:s};try{let{localExecuted:a}=await this.coordinator.executeClusterTransaction(s[0],i,t);if(Hs("coordinator-repo:pend-cluster-complete",{actionId:e.actionId,localExecuted:a}),!a){let c=await this.storageRepo.pend(e,t);return Hs("coordinator-repo:pend-fallback-result",{actionId:e.actionId,success:c.success,hasMissing:!!c.missing?.length,hasPending:!!c.pending?.length}),c}return{success:!0,pending:[],blockIds:Object.keys(e.transforms)}}catch(a){throw Hs("coordinator-repo:pend-error",{actionId:e.actionId,error:a.message}),a}}async cancel(e,t){let n=e.blockIds,s={operations:[{cancel:{actionRef:e}}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let o=n.map(c=>this.coordinator.executeClusterTransaction(c,s,t));(await Promise.all(o)).some(c=>c.localExecuted)||await this.storageRepo.cancel(e,t)}catch(o){throw Hs("coordinator-repo:cancel-error",{actionId:e.actionId,error:o.message}),o}}async commit(e,t){let n=e.blockIds;if(await this.coordinator.getClusterSize(n[0])<=1)return await this.storageRepo.commit(e,t);let o={operations:[{commit:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let{localExecuted:i}=await this.coordinator.executeClusterTransaction(n[0],o,t);return i?{success:!0}:await this.storageRepo.commit(e,t)}catch(i){throw Hs("coordinator-repo:commit-error",{actionId:e.actionId,error:i.message}),i}}};function uv(r){try{if(r==null)return null;if(typeof r?.toString=="function")return r.toString();let e=r.id;return e&&typeof e.toString=="function"?e.toString():typeof e=="string"?e:typeof r=="string"?r:null}catch{return null}}function qs(r,e){let t=uv(r),n=uv(e);return t!=null&&n!=null&&t===n}function Xh(r){return{redirect:{peers:r,reason:"not_in_cluster"}}}function H2(r={}){return e=>new Qh(e,r)}var Qh=class{protocol;maxInboundStreams;maxOutboundStreams;log;repo;components;running;k;responsibilityK;constructor(e,t={}){this.components=e;let n=t.protocol??(t.protocolPrefix??"/db-p2p")+"/repo/1.0.0";this.protocol=n,this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.log=e.logger.forComponent(t.logPrefix??"db-p2p:repo-service"),this.repo=e.repo,this.running=!1,this.k=t.kBucketSize??10,this.responsibilityK=t.responsibilityK??1}[Symbol.toStringTag]="@libp2p/repo-service";async start(){this.running||(await this.components.registrar.handle(this.protocol,this.handleIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.running=!0)}async stop(){this.running&&(await this.components.registrar.unhandle(this.protocol),this.running=!1)}handleIncomingStream(e,t){let n=t.remotePeer,s=async function*(o){for await(let i of o){let a=new TextDecoder().decode(i.subarray()),c=JSON.parse(a),l=c.operations[0],u;if("get"in l){let p=(await zr.digest(new TextEncoder().encode(l.get.blockIds[0]))).digest,f=this.components.libp2p?.services?.networkManager;if(f?.getCluster){let h=await f.getCluster(p);c.cluster=h.map(b=>b.toString?.()??String(b));let m=this.components.libp2p.peerId,g=h.some(b=>qs(b,m));if(!(h.length<this.responsibilityK)&&!g){let b=h.filter(E=>!qs(E,m));console.debug("repo-service:redirect",{peerId:m.toString(),reason:"not-cluster-member",operation:"get",blockId:l.get.blockIds[0],cluster:h.map(E=>E.toString?.()??String(E))}),u=Xh(b.map(E=>({id:E.toString(),addrs:[]})))}else u=await this.repo.get(l.get,{expiration:c.expiration,skipClusterFetch:!0})}else u=await this.repo.get(l.get,{expiration:c.expiration,skipClusterFetch:!0})}else if("pend"in l){let d=Object.keys(l.pend.transforms)[0],f=(await zr.digest(new TextEncoder().encode(d))).digest,h=this.components.libp2p?.services?.networkManager;if(h?.getCluster){let m=await h.getCluster(f);c.cluster=m.map(E=>E.toString?.()??String(E));let g=this.components.libp2p.peerId,y=m.some(E=>qs(E,g));if(!(m.length<this.responsibilityK)&&!y){let E=m.filter(x=>!qs(x,g));console.debug("repo-service:redirect",{peerId:g.toString(),reason:"not-cluster-member",operation:"pend",blockId:d,cluster:m.map(x=>x.toString?.()??String(x))}),u=Xh(E.map(x=>({id:x.toString(),addrs:[]})))}else u=await this.repo.pend(l.pend,{expiration:c.expiration})}else u=await this.repo.pend(l.pend,{expiration:c.expiration})}else if("cancel"in l)u=await this.repo.cancel(l.cancel.actionRef,{expiration:c.expiration});else if("commit"in l){let p=(await zr.digest(new TextEncoder().encode(l.commit.tailId))).digest,f=this.components.libp2p?.services?.networkManager;if(f?.getCluster){let h=await f.getCluster(p);c.cluster=h.map(b=>b.toString?.()??String(b));let m=this.components.libp2p.peerId,g=h.some(b=>qs(b,m));if(!(h.length<this.responsibilityK)&&!g){let b=h.filter(E=>!qs(E,m));console.debug("repo-service:redirect",{peerId:m.toString(),reason:"not-cluster-member",operation:"commit",tailId:l.commit.tailId,cluster:h.map(E=>E.toString?.()??String(E))}),u=Xh(b.map(E=>({id:E.toString(),addrs:[]})))}else u=await this.repo.commit(l.commit,{expiration:c.expiration})}else u=await this.repo.commit(l.commit,{expiration:c.expiration})}yield new TextEncoder().encode(JSON.stringify(u))}};(async()=>{try{let o=rt(e,i=>gr(i),s.bind(this),i=>or(i));for await(let i of o)e.send(i);await e.close()}catch(o){this.log.error("error handling repo protocol message from %p - %e",n,o),e.abort(o instanceof Error?o:new Error(String(o)))}})()}};function hv(r){if(r.length<=1)return r;r.sort((t,n)=>t[0]-n[0]);let e=[r[0]];for(let t of r.slice(1)){let n=e[e.length-1];n[1]!==void 0&&(t[0]<=n[1]?t[1]===void 0?n[1]=void 0:n[1]=Math.max(n[1],t[1]):e.push(t))}return e}var yi=class{blockId;storage;restoreCallback;constructor(e,t,n){this.blockId=e,this.storage=t,this.restoreCallback=n}async getLatest(){return(await this.storage.getMetadata(this.blockId))?.latest}async getBlock(e){let t=await this.storage.getMetadata(this.blockId);if(!t)return;let n=e??t.latest?.rev;if(n===void 0)throw new Error(`No revision specified and no latest revision exists for block ${this.blockId}`);return await this.ensureRevision(t,n),await this.materializeBlock(t,n)}async getTransaction(e){return await this.storage.getTransaction(this.blockId,e)}async getPendingTransaction(e){return await this.storage.getPendingTransaction(this.blockId,e)}async*listPendingTransactions(){yield*this.storage.listPendingTransactions(this.blockId)}async savePendingTransaction(e,t){let n=await this.storage.getMetadata(this.blockId);n||(n={latest:void 0,ranges:[[0]]},await this.storage.saveMetadata(this.blockId,n)),await this.storage.savePendingTransaction(this.blockId,e,t)}async deletePendingTransaction(e){await this.storage.deletePendingTransaction(this.blockId,e)}async*listRevisions(e,t){yield*this.storage.listRevisions(this.blockId,e,t)}async saveMaterializedBlock(e,t){await this.storage.saveMaterializedBlock(this.blockId,e,t)}async saveRevision(e,t){await this.storage.saveRevision(this.blockId,e,t)}async promotePendingTransaction(e){await this.storage.promotePendingTransaction(this.blockId,e)}async setLatest(e){let t=await this.storage.getMetadata(this.blockId);if(!t)throw new Error(`Block ${this.blockId} not found`);t.latest=e,await this.storage.saveMetadata(this.blockId,t)}async ensureRevision(e,t){if(this.inRanges(t,e.ranges))return;let n=`BlockStorage.ensureRevision:${this.blockId}`,s=await Fs.acquire(n);try{let o=await this.storage.getMetadata(this.blockId);if(!o)throw new Error(`Block ${this.blockId} metadata disappeared unexpectedly.`);if(this.inRanges(t,o.ranges))return;let i=await this.restoreBlock(t);if(!i)throw new Error(`Block ${this.blockId} revision ${t} not found during restore attempt.`);await this.saveRestored(i),o.ranges.unshift(i.range),o.ranges=hv(o.ranges),await this.storage.saveMetadata(this.blockId,o)}finally{s()}}async materializeBlock(e,t){let n,s,o=[];for await(let i of this.storage.listRevisions(this.blockId,t,1)){let a=await this.storage.getMaterializedBlock(this.blockId,i.actionId);if(a){n=a,s=i;break}else o.push(i)}if(!n||!s)throw new Error(`Failed to find materialized block ${this.blockId} for revision ${t}`);for(let i=o.length-1;i>=0;--i){let{actionId:a}=o[i],c=await this.storage.getTransaction(this.blockId,a);if(!c)throw new Error(`Missing action ${a} for block ${this.blockId}`);n=Rc(n,c)}if(!n)throw new Error(`Block ${this.blockId} has been deleted`);return o.length?(await this.storage.saveMaterializedBlock(this.blockId,o[0].actionId,n),{block:n,actionRev:o[0]}):{block:n,actionRev:s}}async restoreBlock(e){if(this.restoreCallback)return await this.restoreCallback(this.blockId,e)}async saveRestored(e){let t=Object.entries(e.revisions).map(([n,s])=>({rev:Number(n),data:s}));for(let{rev:n,data:{action:s,block:o}}of t)await Promise.all([this.storage.saveRevision(this.blockId,n,s.actionId),this.storage.saveTransaction(this.blockId,s.actionId,s.transform),o?this.storage.saveMaterializedBlock(this.blockId,s.actionId,o):Promise.resolve()])}inRanges(e,t){return t.some(n=>e>=n[0]&&(n[1]===void 0||e<n[1]))}};var Hc=class{metadata=new Map;revisions=new Map;pendingActions=new Map;actions=new Map;materializedBlocks=new Map;getRevisionKey(e,t){return`${e}:${t}`}getActionKey(e,t){return`${e}:${t}`}async getMetadata(e){return this.metadata.get(e)}async saveMetadata(e,t){this.metadata.set(e,t)}async getRevision(e,t){return this.revisions.get(this.getRevisionKey(e,t))}async saveRevision(e,t,n){this.revisions.set(this.getRevisionKey(e,t),n)}async*listRevisions(e,t,n){let s=t<=n,o=s?t:n,i=s?n:t,a=[];for(let c=o;c<=i;c++){let l=this.revisions.get(this.getRevisionKey(e,c));l&&a.push({rev:c,actionId:l})}s||a.reverse();for(let c of a)yield c}async getPendingTransaction(e,t){return this.pendingActions.get(this.getActionKey(e,t))}async savePendingTransaction(e,t,n){this.pendingActions.set(this.getActionKey(e,t),structuredClone(n))}async deletePendingTransaction(e,t){this.pendingActions.delete(this.getActionKey(e,t))}async*listPendingTransactions(e){let t=`${e}:`;for(let[n]of Array.from(this.pendingActions.entries()))n.startsWith(t)&&(yield n.substring(t.length))}async getTransaction(e,t){return this.actions.get(this.getActionKey(e,t))}async saveTransaction(e,t,n){this.actions.set(this.getActionKey(e,t),n)}async getMaterializedBlock(e,t){let n=this.materializedBlocks.get(this.getActionKey(e,t));return n?structuredClone(n):void 0}async saveMaterializedBlock(e,t,n){let s=this.getActionKey(e,t);n?this.materializedBlocks.set(s,structuredClone(n)):this.materializedBlocks.delete(s)}async promotePendingTransaction(e,t){let n=this.getActionKey(e,t),s=this.pendingActions.get(n);s&&(this.actions.set(n,s),this.pendingActions.delete(n))}};var qc=class{createBlockStorage;validatePend;constructor(e,t){this.createBlockStorage=e,this.validatePend=t?.validatePend}async get({blockIds:e,context:t},n){let s=Array.from(new Set(e)),o=await Promise.all(s.map(async i=>{let a=this.createBlockStorage(i);if(t){let u=await a.getLatest(),d=u?t.committed.filter(p=>p.rev>u.rev):t.committed;for(let{actionId:p,rev:f}of d.sort((h,m)=>h.rev-m.rev))await a.getPendingTransaction(p)&&await this.internalCommit(i,p,f,a)}let c=await a.getBlock(t?.rev);if(!c)return[i,{state:{}}];if(t?.actionId!==void 0){let u=await a.getPendingTransaction(t.actionId);if(!u)throw new Error(`Pending action ${t.actionId} not found`);let d=Rc(c.block,u);return[i,{block:d,state:{latest:await a.getLatest(),pendings:[t.actionId]}}]}let l=await Ha(a.listPendingTransactions());return[i,{block:c.block,state:{latest:await a.getLatest(),pendings:l}}]}));return Object.fromEntries(o)}async pend(e,t){if(this.validatePend&&e.transaction&&e.operationsHash){let i=await this.validatePend(e.transaction,e.operationsHash);if(!i.valid)return{success:!1,reason:i.reason??"Transaction validation failed"}}let n=es(e.transforms),s=[],o=[];for(let i of n){let a=this.createBlockStorage(i),c=Nh(e.transforms,i),l=await Ha(a.listPendingTransactions());if(s.push(...l.map(u=>({blockId:i,actionId:u}))),e.rev!==void 0||c.insert){let u=await a.getLatest();if(u&&u.rev>=(e.rev??0)){let d=await Ha(a.listRevisions(e.rev??0,u.rev));for(let p of d){let f=await a.getTransaction(p.actionId);if(!f)throw new Error(`Missing action ${p.actionId} for block ${i}`);o.push({actionId:p.actionId,rev:p.rev,transforms:F0(f,i)})}}}}if(o.length)return{success:!1,missing:o};if(s.length>0){if(e.policy==="f")return{success:!1,pending:s};if(e.policy==="r")return{success:!1,pending:await Promise.all(s.map(async i=>{let a=this.createBlockStorage(i.blockId);return{blockId:i.blockId,actionId:i.actionId,transform:await a.getPendingTransaction(i.actionId)??await a.getTransaction(i.actionId)}}))}}return await Promise.all(n.map(i=>{let a=this.createBlockStorage(i),c=Nh(e.transforms,i);return a.savePendingTransaction(e.actionId,c)})),{success:!0,pending:s,blockIds:n}}async cancel(e,t){await Promise.all(e.blockIds.map(n=>this.createBlockStorage(n).deletePendingTransaction(e.actionId)))}async commit(e,t){let n=Array.from(new Set(e.blockIds)).sort(),s=[];try{for(let c of n){let l=`StorageRepo.commit:${c}`,u=await Fs.acquire(l);s.push(u)}let o=e.blockIds.map(c=>({blockId:c,storage:this.createBlockStorage(c)})),i=[];for(let{blockId:c,storage:l}of o){let u=await l.getLatest();if(u&&u.rev>=e.rev){let d=[];for await(let p of l.listRevisions(e.rev,u.rev)){let f=await l.getTransaction(p.actionId);if(!f)throw new Error(`Missing action ${p.actionId} for block ${c}`);d.push({actionId:p.actionId,rev:p.rev,transform:f})}i.push({blockId:c,transforms:d})}}if(i.length)return{success:!1,missing:WM(i)};let a=[];for(let{blockId:c,storage:l}of o)await l.getPendingTransaction(e.actionId)||a.push({blockId:c,actionId:e.actionId});if(a.length)throw new Error(`Pending action ${e.actionId} not found for block(s): ${a.map(c=>c.blockId).join(", ")}`);for(let{blockId:c,storage:l}of o)try{await this.internalCommit(c,e.actionId,e.rev,l)}catch(u){return{success:!1,reason:u instanceof Error?u.message:"Unknown error during commit"}}}finally{s.reverse().forEach(o=>o())}return{success:!0}}async internalCommit(e,t,n,s){let o=await s.getPendingTransaction(t);if(!o)throw new Error(`Consistency Error: Pending action ${t} disappeared for block ${e} within critical section.`);let i=await s.getLatest(),a=i?(await s.getBlock(i.rev))?.block:void 0,c=Rc(a,o);c&&await s.saveMaterializedBlock(t,c),await s.saveRevision(n,t),await s.promotePendingTransaction(t),await s.setLatest({actionId:t,rev:n})}};function WM(r){let e=r.flatMap(({blockId:n,transforms:s})=>s.map(o=>({blockId:n,transform:o}))),t=w2(e,({transform:n})=>n.actionId);return Object.entries(t).map(([n,s])=>s.reduce((o,{blockId:i,transform:a})=>(z0(o.transforms,i,a.transform),o),{actionId:n,rev:s[0].transform.rev,transforms:K0()}))}var $r=class{entries;constructor(e){this.entries=e}},Vc=class{partitions;nodes;constructor(e,t){this.partitions=e,this.nodes=t}};var bn=class r{node;index;constructor(e,t){this.node=e,this.index=t}clone(){return new r(this.node,this.index)}},bi=class r{branches;leafNode;leafIndex;on;version;constructor(e,t,n,s,o){this.branches=e,this.leafNode=t,this.leafIndex=n,this.on=s,this.version=o}isEqual(e){return this.leafNode===e.leafNode&&this.leafIndex===e.leafIndex&&this.on===e.on&&this.version===e.version}clone(){return new r(this.branches.map(e=>e.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var hr=64,Jh=class{keyFromEntry;compare;_root;_version=0;constructor(e=n=>n,t=(n,s)=>n<s?-1:n>s?1:0){this.keyFromEntry=e,this.compare=t,this._root=new $r([])}first(){return this.getFirst(this._root)}last(){return this.getLast(this._root)}find(e){return this.getPath(this._root,e)}get(e){return this.at(this.find(e))}at(e){return this.validatePath(e),e.on?e.leafNode.entries[e.leafIndex]:void 0}*range(e){let t=e.first?this.findFirst(e):e.isAscending?this.first():this.last(),n=e.last?this.findLast(e):e.isAscending?this.last():this.first(),s=this.keyFromEntry(n.leafNode.entries[n.leafIndex]),o=e.isAscending?this.internalAscending(t):this.internalDescending(t),i=e.isAscending?1:-1;for(let a of o){if(!a.on||!n.on||this.compareKeys(this.keyFromEntry(a.leafNode.entries[a.leafIndex]),s)*i>0)break;yield a}}isValid(e){return e.version===this._version}insert(e){Object.freeze(e);let t=this.internalInsert(e);return t.on&&(t.version=++this._version),t}updateAt(e,t){this.validatePath(e),e.on&&Object.freeze(t);let n=this.internalUpdate(e,t);return n[0].on&&(n[0].version=++this._version),n}upsert(e){let t=this.find(this.keyFromEntry(e));return Object.freeze(e),t.on?t.leafNode.entries[t.leafIndex]=e:this.internalInsertAt(t,e),t.version=++this._version,t}merge(e,t){let n=this.keyFromEntry(e),s=this.find(n);if(s.on){let o=this.updateAt(s,t(s.leafNode.entries[s.leafIndex]));return o[0].on&&(o[0].version=++this._version),o}else return this.internalInsertAt(s,Object.freeze(e)),s.on=!0,s.version=++this._version,[s,!1]}deleteAt(e){this.validatePath(e);let t=this.internalDelete(e);return t&&++this._version,t}ascending(e){return this.validatePath(e),this.internalAscending(e.clone())}descending(e){return this.validatePath(e),this.internalDescending(e.clone())}getCount(e){let t=0,n=e?e.path.clone():this.first();if(e?.ascending??!0)for(;n.on;)t+=n.leafNode.entries.length-n.leafIndex,n.leafIndex=n.leafNode.entries.length-1,this.internalNext(n);else for(;n.on;)t+=n.leafIndex+1,n.leafIndex=0,this.internalPrior(n);return t}next(e){let t=e.clone();return this.moveNext(t),t}moveNext(e){this.validatePath(e),this.internalNext(e)}prior(e){let t=e.clone();return this.movePrior(t),t}movePrior(e){this.validatePath(e),this.internalPrior(e)}compareKeys(e,t){let n=this.compare(e,t);if(n!==0&&n===this.compare(t,e))throw new Error("Inconsistent comparison function for given values");return n}*internalAscending(e){for(this.validatePath(e);e.on;)yield e,this.moveNext(e)}*internalDescending(e){for(this.validatePath(e);e.on;)yield e,this.movePrior(e)}findFirst(e){let t=this.find(e.first.key);return(!t.on||e.first&&!e.first.inclusive)&&(e.isAscending?this.internalNext(t):this.internalPrior(t)),t}findLast(e){let t=this.find(e.last.key);return(!t.on||e.last&&!e.last.inclusive)&&(e.isAscending?this.internalPrior(t):this.internalNext(t)),t}getPath(e,t){if(e instanceof $r){let n=e,[s,o]=this.indexOfEntry(n.entries,t);return new bi([],n,o,s,this._version)}else{let n=e,s=this.indexOfKey(n.partitions,t),o=this.getPath(n.nodes[s],t);return o.branches.unshift(new bn(n,s)),o}}indexOfEntry(e,t){let n=0,s=e.length-1,o=0,i=-1;for(;n<=s;){if(o=n+s>>>1,i=this.compareKeys(t,this.keyFromEntry(e[o])),i===0)return[!0,o];i<0?s=o-1:n=o+1}return[!1,n]}indexOfKey(e,t){let n=0,s=e.length-1,o=0,i=-1;for(;n<=s;){if(o=n+s>>>1,i=this.compareKeys(t,e[o]),i===0)return o+1;i<0?s=o-1:n=o+1}return n}internalNext(e){if(e.on)if(e.leafIndex>=e.leafNode.entries.length-1){let t=0,n=!1,s=e.branches.length-1;for(;t<=s&&!n;){let o=e.branches[s-t];o.index===o.node.partitions.length?++t:n=!0}if(!n)e.leafIndex=e.leafNode.entries.length,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);++o.index,this.moveToFirst(o.node.nodes[o.index],e)}}else++e.leafIndex,e.on=!0;else if(e.on=e.branches.every(t=>t.index>=0&&t.index<t.node.nodes.length)&&e.leafIndex>=0&&e.leafIndex<e.leafNode.entries.length,e.on)return}internalPrior(e){if(this.validatePath(e),e.leafIndex<=0){let t=0,n=!1,s=e.branches.length-1;for(;t<=s&&!n;)e.branches[s-t].index===0?++t:n=!0;if(!n)e.leafIndex=0,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);--o.index,this.moveToLast(o.node.nodes[o.index],e)}}else--e.leafIndex,e.on=!0}internalUpdate(e,t){if(e.on){let n=this.keyFromEntry(e.leafNode.entries[e.leafIndex]),s=this.keyFromEntry(t);if(this.compareKeys(n,s)!==0){let o=this.internalInsert(t);return o.on&&(this.internalDelete(this.find(n)),o=this.find(s)),[o,!1]}else e.leafNode.entries[e.leafIndex]=t}return[e,!0]}internalDelete(e){if(e.on){if(e.leafNode.entries.splice(e.leafIndex,1),e.branches.length>0){if(e.leafIndex===0){let n=e.branches.at(-1);this.updatePartition(n.index,e,e.branches.length-1,this.keyFromEntry(e.leafNode.entries[e.leafIndex]))}let t=this.rebalanceLeaf(e);t&&(this._root=t)}return e.on=!1,!0}else return!1}internalInsert(e){let t=this.find(this.keyFromEntry(e));return t.on?(t.on=!1,t):(this.internalInsertAt(t,e),t.on=!0,t)}internalInsertAt(e,t){let n=this.leafInsert(e,t),s=e.branches.length-1;for(;n&&s>=0;)n=this.branchInsert(e,s,n),--s;if(n){let o=new Vc([n.key],[this._root,n.right]);this._root=o,e.branches.unshift(new bn(o,n.indexDelta))}}moveToFirst(e,t){if(e instanceof $r){let n=e;t.leafNode=n,t.leafIndex=0,t.on=n.entries.length>0}else t.branches.push(new bn(e,0)),this.moveToFirst(e.nodes[0],t)}moveToLast(e,t){if(e instanceof $r){let n=e,s=n.entries.length;t.leafNode=n,t.on=s>0,t.leafIndex=s>0?s-1:0}else{let n=e,s=new bn(n,n.partitions.length);t.branches.push(s),this.moveToLast(n.nodes[s.index],t)}}getFirst(e){if(e instanceof $r){let t=e;return new bi([],t,0,t.entries.length>0,this._version)}else{let t=e,n=this.getFirst(t.nodes[0]);return n.branches.unshift(new bn(t,0)),n}}getLast(e){if(e instanceof $r){let t=e,n=t.entries.length;return new bi([],t,n>0?n-1:0,n>0,this._version)}else{let t=e,n=t.nodes.length-1,s=this.getLast(t.nodes[n]);return s.branches.unshift(new bn(t,n)),s}}leafInsert(e,t){let{leafNode:n,leafIndex:s}=e;if(n.entries.length<hr){n.entries.splice(s,0,t);return}let o=n.entries.length+1>>>1,i=n.entries.splice(o),a=new $r(i),c=s<o?0:1;return c?(e.leafNode=a,e.leafIndex-=n.entries.length,a.entries.splice(e.leafIndex,0,t)):n.entries.splice(s,0,t),new Zh(this.keyFromEntry(i[0]),a,c)}branchInsert(e,t,n){let s=e.branches[t],{index:o,node:i}=s;if(s.index+=n.indexDelta,i.partitions.splice(o,0,n.key),i.nodes.splice(o+1,0,n.right),i.nodes.length<=hr)return;let a=i.nodes.length>>>1,c=i.partitions.splice(a),l=i.partitions.pop(),u=i.nodes.splice(a),d=new Vc(c,u),p=s.index<a?0:1;return p&&(s.index-=a,s.node=d),new Zh(l,d,p)}rebalanceLeaf(e){if(e.leafNode.entries.length>=hr>>>1)return;let t=e.leafNode,n=e.branches.at(-1),s=e.branches.length-1,o=n.index,i=n.node,a=i.nodes[o+1];if(a&&a.entries.length>hr>>>1){let l=a.entries.shift();t.entries.push(l),this.updatePartition(o+1,e,s,this.keyFromEntry(a.entries[0]));return}let c=i.nodes[o-1];if(c&&c.entries.length>hr>>>1){let l=c.entries.pop();t.entries.unshift(l),this.updatePartition(o,e,s,this.keyFromEntry(l)),e.leafIndex+=1;return}if(a&&a.entries.length+t.entries.length<=hr)return t.entries.push(...a.entries),i.partitions.splice(o,1),i.nodes.splice(o+1,1),o===0&&this.updatePartition(o,e,s,this.keyFromEntry(t.entries[0])),this.rebalanceBranch(e,s);if(c&&c.entries.length+t.entries.length<=hr)return e.leafNode=c,e.leafIndex+=c.entries.length,c.entries.push(...t.entries),i.partitions.splice(o-1,1),i.nodes.splice(o,1),this.rebalanceBranch(e,s)}rebalanceBranch(e,t){let n=e.branches[t],s=n.node;if(t===0&&s.partitions.length===0)return e.branches[t+1]?.node??e.leafNode;if(t===0||s.nodes.length>=hr<<1)return;let o=e.branches.at(t-1),i=o.index,a=o.node,c=a.nodes[i+1];if(c&&c.nodes.length>hr>>>1){s.partitions.push(a.partitions[i]);let u=c.nodes.shift();s.nodes.push(u);let d=c.partitions.shift();this.updatePartition(i+1,e,t-1,d);return}let l=a.nodes[i-1];if(l&&l.nodes.length>hr>>>1){s.partitions.unshift(a.partitions[i-1]);let u=l.nodes.pop();s.nodes.unshift(u);let d=l.partitions.pop();n.index+=1,this.updatePartition(i,e,t-1,d);return}if(c&&c.nodes.length+s.nodes.length<=hr){let u=a.partitions.splice(i,1)[0];return s.partitions.push(u),s.partitions.push(...c.partitions),s.nodes.push(...c.nodes),a.nodes.splice(i+1,1),i===0&&a.partitions.length>0&&this.updatePartition(i,e,t-1,a.partitions[0]),this.rebalanceBranch(e,t-1)}if(l&&l.nodes.length+s.nodes.length<=hr){n.node=l,n.index+=l.nodes.length;let u=a.partitions.splice(i-1,1)[0];return l.partitions.push(u),l.partitions.push(...s.partitions),l.nodes.push(...s.nodes),a.nodes.splice(i,1),this.rebalanceBranch(e,t-1)}}updatePartition(e,t,n,s){let o=t.branches[n];e>0?o.node.partitions[e-1]=s:n!==0&&this.updatePartition(t.branches[n-1].index,t,n-1,s)}validatePath(e){if(!this.isValid(e))throw new Error("Path is invalid due to mutation of the tree")}},Zh=class{key;right;indexDelta;constructor(e,t,n){this.key=e,this.right=t,this.indexDelta=n}};function Gc(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function ed(r){return`${Gc(r.coord)}|${r.id}`}var td=class{byKey;byId;constructor(){this.byKey=new Jh(e=>ed(e)),this.byId=new Map}insert(e){let t=ed(e);this.byKey.insert(e),this.byId.set(e.id,t)}upsert(e,t){let n=Date.now(),s=this.byId.get(e);if(s){let i=this.byKey.find(s);i.on&&this.byKey.deleteAt(i),this.byId.delete(e)}let o={id:e,coord:t,relevance:0,lastAccess:n,state:"disconnected",accessCount:0,successCount:0,failureCount:0,avgLatencyMs:0};return this.insert(o),o}update(e,t){let n=this.byId.get(e);if(!n)return;let s=this.byKey.find(n),o=this.byKey.at(s);if(!o)return;let i={...o,...t};this.byKey.updateAt(s,i),ed(o)!==ed(i)&&(this.byKey.deleteAt(s),this.insert(i))}getById(e){let t=this.byId.get(e);if(!t)return;let n=this.byKey.find(t);return n.on?this.byKey.at(n):void 0}remove(e){let t=this.byId.get(e);if(!t)return;let n=this.byKey.find(t);n.on&&this.byKey.deleteAt(n),this.byId.delete(e)}list(){let e=[];for(let t of this.byKey.ascending(this.byKey.first()))e.push(this.byKey.at(t));return e}size(){return this.byId.size}setState(e,t){this.update(e,{state:t})}protectedIdsAround(e,t){let n=new Set;for(let s of this.neighborsRight(e,t))n.add(s);for(let s of this.neighborsLeft(e,t))n.add(s);return n}ceilPath(e){let t=`${e}|\0`,n=this.byKey.find(t);return n.on||(n=this.byKey.next(n)),n}floorPath(e){let t=`${e}|\uFFFF`,n=this.byKey.find(t);return n.on||(n=this.byKey.prior(n)),n}successorOfCoord(e){let t=Gc(e),n=this.ceilPath(t);if(n.on)return this.byKey.at(n);let s=this.byKey.first();return s.on?this.byKey.at(s):void 0}predecessorOfCoord(e){let t=Gc(e),n=this.floorPath(t);if(n.on)return this.byKey.at(n);let s=this.byKey.last();return s.on?this.byKey.at(s):void 0}neighborsRight(e,t){let n=[],s=Gc(e),o=this.ceilPath(s);o=o.on?o:this.byKey.first();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.first(),!o.on));)n.push(this.byKey.at(o).id),o=this.byKey.next(o),i++;return Array.from(new Set(n))}neighborsLeft(e,t){let n=[],s=Gc(e),o=this.floorPath(s);o=o.on?o:this.byKey.last();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.last(),!o.on));)n.push(this.byKey.at(o).id),o=this.byKey.prior(o),i++;return Array.from(new Set(n))}};var j2={};z(j2,{sha256:()=>Ii,sha512:()=>fO});var W2=ne(Z("crypto"),1);var boe=new Uint8Array(0);function dv(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function dr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function fv(r){return new TextEncoder().encode(r)}function pv(r){return new TextDecoder().decode(r)}var jM=bv,gv=128,YM=127,XM=~YM,QM=Math.pow(2,31);function bv(r,e,t){e=e||[],t=t||0;for(var n=t;r>=QM;)e[t++]=r&255|gv,r/=128;for(;r&XM;)e[t++]=r&255|gv,r>>>=7;return e[t]=r|0,bv.bytes=t-n+1,e}var JM=q2,ZM=128,yv=127;function q2(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw q2.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&yv)<<s:(i&yv)*Math.pow(2,s),s+=7}while(i>=ZM);return q2.bytes=o-n,t}var eO=Math.pow(2,7),tO=Math.pow(2,14),rO=Math.pow(2,21),nO=Math.pow(2,28),sO=Math.pow(2,35),oO=Math.pow(2,42),iO=Math.pow(2,49),aO=Math.pow(2,56),cO=Math.pow(2,63),lO=function(r){return r<eO?1:r<tO?2:r<rO?3:r<nO?4:r<sO?5:r<oO?6:r<iO?7:r<aO?8:r<cO?9:10},uO={encode:jM,decode:JM,encodingLength:lO},hO=uO,Wc=hO;function jc(r,e=0){return[Wc.decode(r,e),Wc.decode.bytes]}function wi(r,e,t=0){return Wc.encode(r,e,t),e}function xi(r){return Wc.encodingLength(r)}function Ei(r,e){let t=e.byteLength,n=xi(r),s=n+xi(t),o=new Uint8Array(s+t);return wi(r,o,0),wi(t,o,n),o.set(e,s),new vi(r,t,e,o)}function Yc(r){let e=dr(r),[t,n]=jc(e),[s,o]=jc(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new vi(t,s,i,e)}function wv(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&dv(r.bytes,t.bytes)}}var vi=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var dO=20;function G2({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new V2(r,e,t,n,s)}var V2=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??dO,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?xv(n,this.code,t?.truncate):n.then(s=>xv(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function xv(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ei(e,r)}var Ii=G2({name:"sha2-256",code:18,encode:r=>dr(W2.default.createHash("sha256").update(r).digest())}),fO=G2({name:"sha2-512",code:19,encode:r=>dr(W2.default.createHash("sha512").update(r).digest())});async function Ne(r){let e=r.toMultihash().bytes;return await Ii.encode(e)}async function Yt(r){return await Ii.encode(r)}function Ev(r){return C(r,"base64url")}function Sv(r="default"){let e=`/optimystic/${r}/fret/1.0.0`;return{PROTOCOL_NEIGHBORS:`${e}/neighbors`,PROTOCOL_NEIGHBORS_ANNOUNCE:`${e}/neighbors/announce`,PROTOCOL_MAYBE_ACT:`${e}/maybeAct`,PROTOCOL_LEAVE:`${e}/leave`,PROTOCOL_PING:`${e}/ping`}}var Y2="/optimystic/default/fret/1.0.0/neighbors",X2="/optimystic/default/fret/1.0.0/neighbors/announce",Q2="/optimystic/default/fret/1.0.0/maybeAct",J2="/optimystic/default/fret/1.0.0/leave",Z2="/optimystic/default/fret/1.0.0/ping";async function fr(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)}async function Hr(r){if(r.byteLength===0)throw new Error("empty response");let e=0,t=r.byteLength;for(;e<t&&(r[e]===0||r[e]===9||r[e]===10||r[e]===13||r[e]===32);)e++;for(;t>e&&(r[t-1]===0||r[t-1]===9||r[t-1]===10||r[t-1]===13||r[t-1]===32);)t--;if(t<=e)throw new Error("whitespace response");let n=new TextDecoder().decode(r.subarray(e,t));return JSON.parse(n)}var rs=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},nd=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var sd=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var sg={};z(sg,{base58btc:()=>Ue,base58flickr:()=>xO});function pO(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var mO=pO,gO=mO,Iv=gO;var eg=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},tg=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 Av(this,e)}},rg=class{decoders;constructor(e){this.decoders=e}or(e){return Av(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Av(r,e){return new rg({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ng=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new eg(e,t,n),this.decoder=new tg(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ai({name:r,prefix:e,encode:t,decode:n}){return new ng(r,e,t,n)}function ns({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Iv(t,r);return Ai({prefix:e,name:r,encode:n,decode:o=>dr(s(o))})}function yO(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function bO(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function wO(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Be({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=wO(n);return Ai({prefix:e,name:r,encode(o){return bO(o,n,t)},decode(o){return yO(o,s,t,r)}})}var Ue=ns({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xO=ns({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var og={};z(og,{base32:()=>ss,base32hex:()=>IO,base32hexpad:()=>CO,base32hexpadupper:()=>TO,base32hexupper:()=>AO,base32pad:()=>EO,base32padupper:()=>SO,base32upper:()=>vO,base32z:()=>_O});var ss=Be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),vO=Be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),EO=Be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),SO=Be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),IO=Be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),AO=Be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),CO=Be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),TO=Be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),_O=Be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ig={};z(ig,{base36:()=>Xc,base36upper:()=>PO});var Xc=ns({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),PO=ns({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});function Cv(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return kO(t,ag(r),e??Ue.encoder);default:return LO(t,ag(r),e??ss.encoder)}}var Tv=new WeakMap;function ag(r){let e=Tv.get(r);if(e==null){let t=new Map;return Tv.set(r,t),t}return e}var Xe=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Qc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==MO)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ei(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&wv(e.multihash,n.multihash)}toString(e){return Cv(this,e)}toJSON(){return{"/":Cv(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??_v(n,s,o.bytes))}else if(t[OO]===!0){let{version:n,multihash:s,code:o}=t,i=Yc(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Qc)throw new Error(`Version 0 CID must use dag-pb (code: ${Qc}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=_v(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Qc,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=dr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new vi(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=jc(e.subarray(t));return t+=p,d},s=n(),o=Qc;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=DO(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ag(o).set(n,e),o}};function DO(r,e){switch(r[0]){case"Q":{let t=e??Ue;return[Ue.prefix,t.decode(`${Ue.prefix}${r}`)]}case Ue.prefix:{let t=e??Ue;return[Ue.prefix,t.decode(r)]}case ss.prefix:{let t=e??ss;return[ss.prefix,t.decode(r)]}case Xc.prefix:{let t=e??Xc;return[Xc.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function kO(r,e,t){let{prefix:n}=t;if(n!==Ue.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function LO(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Qc=112,MO=18;function _v(r,e,t){let n=xi(r),s=n+xi(e),o=new Uint8Array(s+t.byteLength);return wi(r,o,0),wi(e,o,n),o.set(t,s),o}var OO=Symbol.for("@ipld/js-cid/CID");var cg={};z(cg,{identity:()=>Sr});var Pv=0,RO="identity",Dv=dr;function NO(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ei(Pv,Dv(r))}var Sr={code:Pv,name:RO,encode:Dv,digest:NO};var BO=parseInt("11111",2),lg=parseInt("10000000",2),UO=parseInt("01111111",2),kv={0:Jc,1:Jc,2:KO,3:$O,4:HO,5:zO,6:FO,16:Jc,22:Jc,48:Jc};function ug(r,e={offset:0}){let t=r[e.offset]&BO;if(e.offset++,kv[t]!=null)return kv[t](r,e);throw new Error("No decoder for tag "+t)}function Zc(r,e){let t=0;if((r[e.offset]&lg)===lg){let n=r[e.offset]&UO,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Jc(r,e){Zc(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=ug(r,e);if(n===null)break;t.push(n)}return t}function KO(r,e){let t=Zc(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function FO(r,e){let t=Zc(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function zO(r,e){return e.offset++,null}function $O(r,e){let t=Zc(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function HO(r,e){let t=Zc(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function qO(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new B;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function hg(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=qO(r.byteLength);return new B(Uint8Array.from([e.byteLength|lg]),e)}function Lv(r){let e=new B,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new B(Uint8Array.from([2]),hg(e),e)}function Mv(r){let e=Uint8Array.from([0]),t=new B(e,r);return new B(Uint8Array.from([3]),hg(t),t)}function od(r,e=48){let t=new B;for(let n of r)t.append(n);return new B(Uint8Array.from([e]),hg(t),t)}async function Ov(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var VO=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),GO=Uint8Array.from([6,5,43,129,4,0,34]),WO=Uint8Array.from([6,5,43,129,4,0,35]),jO={ext:!0,kty:"EC",crv:"P-256"},YO={ext:!0,kty:"EC",crv:"P-384"},XO={ext:!0,kty:"EC",crv:"P-521"},dg=32,fg=48,pg=66;function Rv(r){let e=ug(r);return Nv(e)}function Nv(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===dg*2+1)return n=C(e.subarray(t,t+dg),"base64url"),s=C(e.subarray(t+dg),"base64url"),new Ci({...jO,key_ops:["verify"],x:n,y:s});if(e.byteLength===fg*2+1)return n=C(e.subarray(t,t+fg),"base64url"),s=C(e.subarray(t+fg),"base64url"),new Ci({...YO,key_ops:["verify"],x:n,y:s});if(e.byteLength===pg*2+1)return n=C(e.subarray(t,t+pg),"base64url"),s=C(e.subarray(t+pg),"base64url"),new Ci({...XO,key_ops:["verify"],x:n,y:s});throw new rs(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Bv(r){return od([Lv(Uint8Array.from([1])),od([QO(r.crv)],160),od([Mv(new B(Uint8Array.from([4]),P(r.x??"","base64url"),P(r.y??"","base64url")))],161)]).subarray()}function QO(r){if(r==="P-256")return VO;if(r==="P-384")return GO;if(r==="P-521")return WO;throw new rs(`Invalid curve ${r}`)}var Ci=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Bv(this.jwk)),this._raw}toMultihash(){return Sr.digest(Ti(this))}toCID(){return Xe.createV1(114,this.toMultihash())}toString(){return Ue.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}async verify(e,t,n){return Ov(this.jwk,t,e,n)}};var id=ne(Z("crypto"),1);var mie=id.default.generateKeyPairSync,el=32;var JO=64;function Uv(r,e,t){if(r.byteLength!==el)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==JO)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=id.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:C(r,"base64url"),kty:"OKP"}});return id.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}function Fv(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ad=class{type="Ed25519";raw;constructor(e){this.raw=mg(e,el)}toMultihash(){return Sr.digest(Ti(this))}toCID(){return Xe.createV1(114,this.toMultihash())}toString(){return Ue.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=Uv(this.raw,t,e);return Fv(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function zv(r){return r=mg(r,el),new ad(r)}function mg(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new rs(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Xt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Xt||(Xt={}));var gg;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(gg||(gg={}));(function(r){r.codec=()=>Wt(gg)})(Xt||(Xt={}));var tl;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Xt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Xt.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(tl||(tl={}));var yg;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Xt.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Xt.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(yg||(yg={}));var $v=ne(Z("node:crypto"),1);var cd=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function Hv(r,e,t,n){n?.signal?.throwIfAborted();let s=$v.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return Ye.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new cd(String(i))}}var ld=class{type="secp256k1";raw;_key;constructor(e){this._key=Vv(e),this.raw=qv(this._key)}toMultihash(){return Sr.digest(Ti(this))}toCID(){return Xe.createV1(114,this.toMultihash())}toString(){return Ue.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}verify(e,t,n){return Hv(this._key,t,e,n)}};function Gv(r){return new ld(r)}function qv(r){return Ye.Point.fromBytes(r).toBytes()}function Vv(r){try{return Ye.Point.fromBytes(r),r}catch(e){throw new nd(String(e))}}function Wv(r){let{Type:e,Data:t}=tl.decode(r.digest),n=t??new Uint8Array;switch(e){case Xt.Ed25519:return zv(n);case Xt.secp256k1:return Gv(n);case Xt.ECDSA:return Rv(n);default:throw new sd}}function Ti(r){return tl.encode({Type:Xt[r.type],Data:r.raw})}var bg=Symbol.for("@libp2p/peer-id");var ud=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var hd=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},dd=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var jv=Symbol.for("nodejs.util.inspect.custom"),tR=114,rl=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[bg]=!0;toString(){return this.string==null&&(this.string=Ue.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Xe.createV1(tR,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return V(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return V(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[jv](){return`PeerId(${this.toString()})`}},fd=class extends rl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},pd=class extends rl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},md=class extends rl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},rR=2336,nl=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Sr.digest(P(this.url))}[jv](){return`PeerId(${this.url})`}[bg]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Xe.createV1(rR,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=C(e)),e.toString()===this.toString())}};var nR=114,Yv=2336;function Pe(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Yc(Ue.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return sR(Xe.parse(r));if(e==null)throw new ud('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Yc(e.decode(r))}return Xv(t)}function Xv(r){if(iR(r))return new fd({multihash:r});if(oR(r))try{let e=Wv(r);if(e.type==="Ed25519")return new pd({multihash:r,publicKey:e});if(e.type==="secp256k1")return new md({multihash:r,publicKey:e})}catch{let t=C(r.digest);return new nl(new URL(t))}throw new dd("Supplied PeerID Multihash is invalid")}function sR(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==nR&&r.code!==Yv)throw new hd("Supplied PeerID CID is invalid");if(r.code===Yv){let e=C(r.multihash.digest);return new nl(new URL(e))}return Xv(r.multihash)}function oR(r){return r.code===Sr.code}function iR(r){return r.code===Ii.code}var Qv=ne(U2(),1),aR="optimystic:fret";function os(r){return(0,Qv.default)(`${aR}:${r}`)}var wg=os("rpc:neighbors");function Jv(r,e,t,n={PROTOCOL_NEIGHBORS:Y2,PROTOCOL_NEIGHBORS_ANNOUNCE:X2}){r.handle(n.PROTOCOL_NEIGHBORS,async({stream:s})=>{try{let o=await e();await s.sink((async function*(){yield await fr(o)})());try{s.close?.()}catch{}}catch(o){console.error("neighbors handler error:",o)}}),t&&r.handle(n.PROTOCOL_NEIGHBORS_ANNOUNCE,async({stream:s})=>{try{let o=await eE(s),i=await Hr(o);t(i.from,i),await s.sink((async function*(){yield await fr({ok:!0})})());try{s.close?.()}catch{}}catch(o){console.error("neighbors announce handler error:",o)}})}async function Zv(r,e,t=Y2){let n=Pe(e),s=r.getConnections?.(n)??[];if(!Array.isArray(s)||s.length===0||typeof s[0]?.newStream!="function")return{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""};let o;try{o=await s[0].newStream([t]);let i=await eE(o);return await Hr(i)}catch(i){return wg("fetchNeighbors decode failed for %s - %o",e,i),{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""}}finally{if(o)try{await o.close()}catch{}}}async function xg(r,e,t,n=X2){let s=Pe(e),o=r.getConnections?.(s)??[];if(!Array.isArray(o)||o.length===0||typeof o[0]?.newStream!="function")return;let i;try{i=await o[0].newStream([n]),await i.sink((async function*(){yield await fr(t)})())}catch(a){wg("announceNeighbors failed to %s - %o",e,a)}finally{if(i)try{await i.close()}catch{}}}function cR(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")try{return e.subarray(0)}catch(t){wg("toBytes subarray failed - %o",t)}if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unsupported chunk type in neighbors read")}async function eE(r){let e=[];for await(let o of r.source)e.push(cR(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}function tE(r,e,t=Q2){r.handle(t,async({stream:n})=>{try{let s=await nE(n),o=await Hr(s),i=await e(o);await n.sink((async function*(){yield await fr(i)})())}catch(s){console.error("maybeAct handler error:",s)}})}async function rE(r,e,t,n=Q2){let s=Pe(e),o=r.getConnections?.(s)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([n]):i=await r.dialProtocol(s,[n]),await i.sink((async function*(){yield await fr(t)})());let a=await nE(i);return await Hr(a)}finally{if(i)try{await i.close()}catch{}}}function lR(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")return e.subarray(0);throw new Error("Unsupported chunk type in maybeAct read")}async function nE(r){let e=[];for await(let o of r.source)e.push(lR(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}function sE(r,e,t=J2){r.handle(t,async({stream:n})=>{try{let s=await hR(n),o=await Hr(s);await e(o),await n.sink((async function*(){yield await fr({ok:!0})})())}catch(s){console.error("leave handler error:",s)}})}async function oE(r,e,t,n=J2){let s=Pe(e),o=r.getConnections?.(s)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([n]):i=await r.dialProtocol(s,[n]),await i.sink((async function*(){yield await fr(t)})())}finally{if(i)try{await i.close()}catch{}}}function uR(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")return e.subarray(0);throw new Error("Unsupported chunk type in leave read")}async function hR(r){let e=[];for await(let o of r.source)e.push(uR(o));let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),s=0;for(let o of e)n.set(o,s),s+=o.length;return n}var vg=os("rpc:ping");function iE(r,e=Z2,t){r.handle(e,async({stream:n})=>{let s={ok:!0,ts:Date.now()};if(t)try{let o=await t();o.size_estimate!==void 0&&(s.size_estimate=o.size_estimate,s.confidence=o.confidence)}catch(o){vg("getSizeEstimate failed - %o",o)}await n.sink((async function*(){yield await fr(s)})())})}async function sl(r,e,t=Z2){let n=Date.now(),s=Pe(e),o;try{try{let l=r.getConnections?.(s)??[];if(Array.isArray(l)&&l.length>0&&typeof l[0]?.newStream=="function")o=await l[0].newStream([t]);else{let u=await r.dialProtocol(s,[t]);o=u.stream??u}}catch{let u=await r.dialProtocol(s,[t]);o=u.stream??u}let i=null;for await(let l of o.source)if(l!=null)try{if(l instanceof Uint8Array){i=l;break}if(typeof l.subarray=="function"){let u=l.subarray();if(u instanceof Uint8Array){i=u;break}if(ArrayBuffer.isView(u)){i=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);break}}if(ArrayBuffer.isView(l)){i=new Uint8Array(l.buffer,l.byteOffset,l.byteLength);break}}catch(u){vg("sendPing chunk handling failed - %o",u)}let a=Math.max(0,Date.now()-n);if(!i||i.length===0)return{ok:!1,rttMs:a};let c=new TextDecoder().decode(i).trim();if(!c||c[0]!=="{"||!c.endsWith("}"))return{ok:!1,rttMs:a};try{let l=await Hr(i);return{ok:!!l.ok,rttMs:a,size_estimate:l.size_estimate,confidence:l.confidence}}catch(l){return vg("sendPing decode failed - %o",l),{ok:!1,rttMs:a}}}finally{if(o)try{await o.close()}catch{}}}function dR(r){let e=0n;for(let t=0;t<r.length;t++)e=e<<8n|BigInt(r[t]);return e}function fR(r){if(r.length===0)return 0n;let e=[...r].sort((n,s)=>n<s?-1:n>s?1:0),t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2n:e[t]}function gd(r,e){let t=r.list(),n=t.length;if(n===0)return{n:0,confidence:0};if(n===1)return{n:1,confidence:.2};let s=1n<<256n,o=t.map(g=>dR(g.coord)).sort((g,y)=>g<y?-1:g>y?1:0),i=[];for(let g=1;g<o.length;g++)i.push(o[g]-o[g-1]);i.push(o[0]+s-o[o.length-1]);let a=fR(i),c=a>0n?a:s/BigInt(Math.max(1,n)),l=s/c,u=Math.max(1,Math.min(Number(l),1e9)),d=i[0],p=i[0];for(let g of i)g<d&&(d=g),g>p&&(p=g);let f=Math.min(1,n/Math.max(1,e*2)),h=p===0n?0:Number(d)/Number(p),m=Math.max(.05,Math.min(1,.5*f+.5*h));return{n:u,confidence:m}}var _i=class{capacity;refillPerSec;tokens;last;constructor(e,t){this.capacity=e,this.refillPerSec=t,this.tokens=e,this.last=Date.now()}tryTake(e=1){return this.refill(),this.tokens>=e?(this.tokens-=e,!0):!1}retryAfterMs(e=1){if(this.refill(),this.tokens>=e)return 0;let n=(e-this.tokens)/this.refillPerSec;return Math.ceil(n*1e3)}refill(){let e=Date.now(),t=(e-this.last)/1e3;t>0&&(this.tokens=Math.min(this.capacity,this.tokens+t*this.refillPerSec),this.last=e)}};var ht=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},wn=class extends Error{static name="ValidationError";name="ValidationError"},ol=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},yd=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var le=Z("node:net");var Sg={};z(Sg,{base64:()=>pR,base64pad:()=>mR,base64url:()=>Eg,base64urlpad:()=>gR});var pR=Be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),mR=Be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Eg=Be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gR=Be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ig={};z(Ig,{base10:()=>yR});var yR=ns({prefix:"9",name:"base10",alphabet:"0123456789"});var Ag={};z(Ag,{base16:()=>bR,base16upper:()=>wR});var bR=Be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),wR=Be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Cg={};z(Cg,{base2:()=>xR});var xR=Be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Tg={};z(Tg,{base256emoji:()=>AR});var aE=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}"),vR=aE.reduce((r,e,t)=>(r[t]=e,r),[]),ER=aE.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function SR(r){return r.reduce((e,t)=>(e+=vR[t],e),"")}function IR(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=ER[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var AR=Ai({prefix:"\u{1F680}",name:"base256emoji",encode:SR,decode:IR});var _g={};z(_g,{base8:()=>CR});var CR=Be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Pg={};z(Pg,{identity:()=>TR});var TR=Ai({prefix:"\0",name:"identity",encode:r=>pv(r),decode:r=>fv(r)});var bce=new TextEncoder,wce=new TextDecoder;var cE={...Pg,...Cg,..._g,...Ig,...Ag,...og,...ig,...sg,...Sg,...Tg},Ece={...j2,...cg};function kg(r){return e=>C(e,r)}function Lg(r){return e=>P(e,r)}function Pi(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Vs(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function lE(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=P(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Vs(n);return be([t,s],t.length+s.length)}function uE(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ss.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 s=Vs(n);return be([t,s],t.length+s.length)}function Mg(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=C(e,"base32"),s=Pi(t);return`${n}:${s}`}var Og=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new ht("Invalid byte value in IP address");e[n]=s}),e},hE=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,le.isIPv4)(t[n]),i;o&&(i=Og(t[n]),t[n]=C(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,C(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new ht("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},dE=function(r){if(r.byteLength!==4)throw new ht("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},fE=function(r){if(r.byteLength!==16)throw new ht("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new ht(`Invalid IPv6 address "${t}"`)}};function pE(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new ht(`Invalid IPv6 address "${r}"`)}}var Dg=Object.values(cE).map(r=>r.decoder),DR=(function(){let r=Dg[0].or(Dg[1]);return Dg.slice(2).forEach(e=>r=r.or(e)),r})();function mE(r){return DR.decode(r)}function gE(r){return e=>r.encoder.encode(e)}function kR(r){if(parseInt(r).toString()!==r)throw new wn("Value must be an integer")}function LR(r){if(r<0)throw new wn("Value must be a positive integer, or zero")}function MR(r){return e=>{if(e>r)throw new wn(`Value must be smaller than or equal to ${r}`)}}function OR(...r){return e=>{for(let t of r)t(e)}}var il=OR(kR,LR,MR(65535));var ot=-1,Rg=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new yd(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Qt=new Rg,u9=[{code:4,name:"ip4",size:32,valueToBytes:Og,bytesToValue:dE,validate:r=>{if(!(0,le.isIPv4)(r))throw new wn(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Vs,bytesToValue:Pi,validate:il},{code:273,name:"udp",size:16,valueToBytes:Vs,bytesToValue:Pi,validate:il},{code:33,name:"dccp",size:16,valueToBytes:Vs,bytesToValue:Pi,validate:il},{code:41,name:"ip6",size:128,valueToBytes:hE,bytesToValue:fE,stringToValue:pE,validate:r=>{if(!(0,le.isIPv6)(r))throw new wn(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ot},{code:43,name:"ipcidr",size:8,bytesToValue:kg("base10"),valueToBytes:Lg("base10")},{code:53,name:"dns",size:ot,resolvable:!0},{code:54,name:"dns4",size:ot,resolvable:!0},{code:55,name:"dns6",size:ot,resolvable:!0},{code:56,name:"dnsaddr",size:ot,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Vs,bytesToValue:Pi,validate:il},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ot,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ot,bytesToValue:kg("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Lg("base58btc")(r):Xe.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Mg,valueToBytes:lE},{code:445,name:"onion3",size:296,bytesToValue:Mg,valueToBytes:uE},{code:446,name:"garlic64",size:ot},{code:447,name:"garlic32",size:ot},{code:448,name:"tls"},{code:449,name:"sni",size:ot},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ot,bytesToValue:gE(Eg),valueToBytes:mE},{code:480,name:"http"},{code:481,name:"http-path",size:ot,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ot}];u9.forEach(r=>{Qt.addProtocol(r)});function yE(r){let e=[],t=0;for(;t<r.length;){let n=Bt(r,t),s=Qt.getProtocol(n),o=ve(n),i=h9(s,r,t+o),a=0;i>0&&s.size===ot&&(a=ve(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,d=r.subarray(u,u+i);l.value=s.bytesToValue?.(d)??C(d)}e.push(l),t+=c}return e}function bE(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=Qt.getProtocol(n.code),o=ve(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??P(n.value),a=i.byteLength,s.size===ot&&(c=ve(a)));let l=new Uint8Array(o+c+a),u=0;cn(n.code,l,u),u+=o,i!=null&&(s.size===ot&&(cn(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return be(t,e)}function wE(r){if(r.charAt(0)!=="/")throw new ht('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=Qt.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new ht(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new ht(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new ht("Incomplete multiaddr");return e}function xE(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Qt.getProtocol(e.code);if(t==null)throw new ht(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function h9(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Bt(e,t)}var d9=Symbol.for("nodejs.util.inspect.custom"),Hg=Symbol.for("@multiformats/multiaddr"),f9=[53,54,55,56],$g=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function p9(r){if(r==null&&(r="/"),EE(r))return r.getComponents();if(r instanceof Uint8Array)return yE(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),wE(r);if(Array.isArray(r))return r;throw new ht("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ed=class r{[Hg]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=p9(e),t.validate!==!1&&m9(this)}get bytes(){return this.#r==null&&(this.#r=bE(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=xE(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,n,s,o="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(o=`%${l??""}`),f9.includes(a)&&(t="tcp",s=443,n=`${l??""}${o}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",s=parseInt(l??"")),(a===4||a===41)&&(t="tcp",n=`${l??""}${o}`,e=a===41?6:4);if(e==null||t==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:s}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let n=Qt.getProtocol(e);return{code:e,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(t==null)return[e];let n=Qt.getProtocol(e),s=[e];return t!=null&&s.push(n.valueToBytes?.(t)??P(t)),s})}stringTuples(){return this.#e.map(({code:e,value:t})=>t==null?[e]:[e,t])}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new ol(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:n,value:s})=>{n===421&&e.push([n,s]),n===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?C(Ue.decode(`z${n}`),"base58btc"):C(Xe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(Qt.getProtocol(e.code).path)return e.value??null;return null}equals(e){return V(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=vE.get(t.name);if(n==null)throw new $g(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>cl(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(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[d9](){return`Multiaddr(${this.toString()})`}};function m9(r){r.getComponents().forEach(e=>{let t=Qt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}var Sd=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let p=Number.parseInt(d,e);if(!Number.isNaN(p))return p});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var SE=45,g9=15,Di=new Sd;function IE(r){if(!(r.length>g9))return Di.new(r).parseWith(()=>Di.readIPv4Addr())}function AE(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>SE))return Di.new(r).parseWith(()=>Di.readIPv6Addr())}function ll(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>SE)return;let t=Di.new(r).parseWith(()=>Di.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function CE(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function TE(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function qg(r){switch(r.length){case Gs:return r.join(".");case Ws:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function _E(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function PE(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Gs=4,Ws=16,dle=parseInt("0xFFFF",16),y9=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ul(r,e){e.length===Ws&&r.length===Gs&&CE(e,0,11)&&(e=e.slice(12)),e.length===Gs&&r.length===Ws&&TE(r,y9,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function DE(r,e){if(typeof e=="string"&&(e=ll(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function Vg(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Gs,s=IE(e);if(s==null&&(n=Ws,s=AE(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Gg(o,8*n);return{network:ul(s,i),mask:i}}function Gg(r,e){if(e!==8*Gs&&e!==8*Ws)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var xn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Vg(e));else{let n=ll(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=ll(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=Gg(s,8*n.length);this.network=ul(n,this.mask)}}contains(e){return DE({network:this.network,mask:this.mask},e)}toString(){let e=_E(this.mask),t=e!==-1?String(e):PE(this.mask);return qg(this.network)+"/"+t}};function kE(r,e){return new xn(r).contains(e)}var vE=new Map;function EE(r){return!!r?.[Hg]}function cl(r){return new Ed(r)}function Id(r,e){let t=Math.max(r.length,e.length),n=new Uint8Array(t);for(let s=0;s<t;s++){let o=r[r.length-1-s]??0,i=e[e.length-1-s]??0;n[t-1-s]=o^i}return n}function Wg(r,e){let t=Math.max(r.length,e.length);for(let n=0;n<t;n++){let s=r[n]??0,o=e[n]??0;if(s<o)return!0;if(s>o)return!1}return!1}function LE(r){for(let e=0;e<r.length;e++)if(r[e]!==0)return e;return Number.POSITIVE_INFINITY}function b9(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function ME(r,e,t,n){return Wg(e,n)?!0:Wg(n,e)?!1:r<t}function Ad(r,e,t,n,s,o=1){let i,a=[];for(let u of t){let d=r.getById(u);if(!d)continue;let p=Id(d.coord,e),f=n(u),h=(f?1:0)+.25*s(u);a.push({id:u,dist:p,connected:f,score:h}),(!i||ME(u,p,i.id,i.dist))&&(i={id:u,dist:p})}if(!i)return;let c=LE(i.dist),l;for(let u of a){if(!u.connected)continue;if(LE(u.dist)<=c+o){if(!l){l={id:u.id,dist:u.dist,score:u.score};continue}ME(u.id,u.dist,l.id,l.dist)?l={id:u.id,dist:u.dist,score:u.score}:b9(u.dist,l.dist)&&(u.score>l.score||u.score===l.score&&u.id<l.id)&&(l={id:u.id,dist:u.dist,score:u.score})}}return l?.id??i.id}function OE(r=12,e=.08,t=.03,n=.6,s=.7,o=1.8,i=1e-6){let a=[];for(let c=0;c<r;c++)a.push((c+.5)/r);return{centers:a,occupancy:new Float64Array(r),alpha:t,sigma:e,beta:n,sMin:s,sMax:o,eps:i}}function Cd(r,e){let t=Id(r,e),n=0;for(let o=0;o<t.length;o++){let i=t[o]??0;if(i===0){n+=8;continue}let a=7-Math.floor(Math.log2(i));n+=a;break}return 1-Math.min(256,n)/256}function RE(r,e){let t=r/Math.max(1e-9,e);return Math.exp(-.5*t*t)}function jg(r,e){for(let t=0;t<r.centers.length;t++){let n=RE(Math.abs(e-r.centers[t]),r.sigma);r.occupancy[t]=(1-r.alpha)*r.occupancy[t]+r.alpha*n}}function Yg(r,e){let t=0,n=0;for(let i=0;i<r.centers.length;i++){let a=RE(Math.abs(e-r.centers[i]),r.sigma);t+=r.occupancy[i]*a,n+=1*a}let s=(n+r.eps)/(t+r.eps),o=Math.pow(s,r.beta);return Math.max(r.sMin,Math.min(r.sMax,o))}function w9(r,e){let t=Math.max(0,e-r.lastAccess),s=Math.log(2)/Math.max(1,6e4);return Math.exp(-s*t)}function x9(r){return Math.log1p(r.accessCount)/5}function v9(r){let e=r.successCount+r.failureCount,t=e>0?r.successCount/e:.5,n=r.avgLatencyMs>0?Math.min(1,r.avgLatencyMs/1e3):.5,s=.5*t+.5*(1-n);return Math.max(0,s)}function Xg(r,e){return .4*w9(r,e)+.2*x9(r)+.4*v9(r)}function Qg(r,e){return{...r,...e}}function NE(r,e,t,n=Date.now()){jg(t,e);let s=Xg(r,n),o=Yg(t,e),i=s*o;return Qg(r,{lastAccess:n,relevance:i,accessCount:r.accessCount+1})}function BE(r,e,t,n,s=Date.now()){jg(n,t);let o=.2,i=r.avgLatencyMs>0?(1-o)*r.avgLatencyMs+o*e:e,a=Xg({...r,avgLatencyMs:i,successCount:r.successCount+1},s),c=Yg(n,t),l=a*c;return Qg(r,{lastAccess:s,relevance:l,successCount:r.successCount+1,avgLatencyMs:i})}function UE(r,e,t,n=Date.now()){jg(t,e);let s=Xg({...r,failureCount:r.failureCount+1},n)*.7,o=Yg(t,e),i=s*o;return Qg(r,{lastAccess:n,relevance:i,failureCount:r.failureCount+1})}var Ir=os("service:fret"),ki=class{mode="passive";store=new td;cfg;node;stabilizing=!1;inflightAct=0;bucketNeighbors;bucketMaybeAct;bucketDiscovery;announcedIds=new Map;postBootstrapAnnounced=!1;sparsity=OE();cachedSelfCoord=null;preconnectRunning=!1;protocols;metadata;diag={peersDiscovered:0,snapshotsFetched:0,announcementsSent:0,pingsSent:0,pingsOk:0,pingsFail:0,maybeActForwarded:0,evictions:0};networkObservations=[];maxObservations=100;observationWindowMs=3e5;constructor(e,t){this.node=e,this.cfg={k:t?.k??15,m:t?.m??Math.ceil((t?.k??15)/2),capacity:t?.capacity??2048,profile:t?.profile??"core",bootstraps:t?.bootstraps??[],networkName:t?.networkName??"default"},this.protocols=Sv(this.cfg.networkName),this.bucketDiscovery=new _i(this.cfg.profile==="core"?50:10,this.cfg.profile==="core"?25:3),this.bucketNeighbors=new _i(this.cfg.profile==="core"?20:8,this.cfg.profile==="core"?10:4),this.bucketMaybeAct=new _i(this.cfg.profile==="core"?32:8,this.cfg.profile==="core"?16:4)}getDiagnostics(){return this.diag}async selfCoord(){return this.cachedSelfCoord?this.cachedSelfCoord:(this.cachedSelfCoord=await Ne(this.node.peerId),this.cachedSelfCoord)}enforceCapacity(){let e=Math.max(1,this.cfg.capacity);if(this.store.size()<=e)return;let t=this.cachedSelfCoord;if(!t)return;let n=this.store.protectedIdsAround(t,Math.max(2,this.cfg.m)),s=this.store.list();s.sort((o,i)=>o.relevance-i.relevance);for(let o of s){if(this.store.size()<=e)break;n.has(o.id)||this.store.remove(o.id)}}async applyTouch(e,t){let n=this.store.getById(e)??this.store.upsert(e,t),s=Cd(await this.selfCoord(),t),o=NE(n,s,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,accessCount:o.accessCount})}async applySuccess(e,t,n){let s=this.store.getById(e)??this.store.upsert(e,t),o=Cd(await this.selfCoord(),t),i=BE(s,n,o,this.sparsity);this.store.update(e,{lastAccess:i.lastAccess,relevance:i.relevance,successCount:i.successCount,avgLatencyMs:i.avgLatencyMs})}async applyFailure(e,t){let n=this.store.getById(e)??this.store.upsert(e,t),s=Cd(await this.selfCoord(),t),o=UE(n,s,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,failureCount:o.failureCount})}async start(){await this.seedFromPeerStore(),this.registerRpcHandlers(),await this.proactiveAnnounceOnStart(),this.startStabilizationLoop(),this.mode==="active"&&this.preconnectNeighbors(),this.node.addEventListener("peer:connect",async e=>{if(!this.postBootstrapAnnounced){this.postBootstrapAnnounced=!0;try{await this.announceNeighborsBounded(8)}catch(t){Ir("postBootstrap announce failed - %o",t)}}}),this.node.addEventListener("peer:connect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let n=this.store.getById(t)?.coord??await Ne(Pe(t));this.store.setState(t,"connected"),await this.applyTouch(t,n)}catch(t){Ir("peer:connect handler failed - %o",t)}}),this.node.addEventListener("peer:disconnect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let n=this.store.getById(t)?.coord??await Ne(Pe(t));this.store.setState(t,"disconnected"),await this.applyFailure(t,n)}catch(t){Ir("peer:disconnect handler failed - %o",t)}})}async stop(){this.stabilizing=!1;try{await this.sendLeaveToNeighbors()}catch(e){console.warn("sendLeaveToNeighbors failed",e)}}setMode(e){this.mode=e,e==="active"&&!this.preconnectRunning&&this.startActivePreconnectLoop()}async ready(){}registerRpcHandlers(){Jv(this.node,async()=>this.handleNeighborsRequest(),(e,t)=>{this.mergeAnnounceSnapshot(e,t)},this.protocols),tE(this.node,async e=>this.handleMaybeAct(e),this.protocols.PROTOCOL_MAYBE_ACT),sE(this.node,async e=>this.handleLeave(e.from),this.protocols.PROTOCOL_LEAVE),iE(this.node,this.protocols.PROTOCOL_PING,()=>this.getNetworkSizeEstimate())}async handleNeighborsRequest(){return this.bucketNeighbors.tryTake()?await this.snapshot():{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:[],predecessors:[],sig:""}}async handleMaybeAct(e){if(e.ttl<=0)return await this.nearAnchorOnly(e);if(e.activity&&e.activity.length>128*1024)return await this.nearAnchorOnly(e);if(!this.bucketMaybeAct.tryTake())return await this.nearAnchorOnly(e);let t=this.cfg.profile==="core"?16:4;if(this.inflightAct>=t)return this.nearAnchorOnly(e);this.inflightAct++;try{return await this.routeAct(e)}catch(n){return console.error("routeAct failed:",n),await this.nearAnchorOnly(e)}finally{this.inflightAct--}}isConnected(e){try{return this.node.getConnections(Pe(e)).length>0}catch{return!1}}hasAddresses(e){try{let t=this.node.getMultiaddrsForPeer?.(Pe(e))??[];return Array.isArray(t)&&t.length>0}catch{return!1}}async proactiveAnnounceOnStart(){try{await this.announceNeighborsBounded(8)}catch(e){console.warn("proactiveAnnounceOnStart failed",e)}}async announceNeighborsBounded(e){let t=await Ne(this.node.peerId),n=this.node.peerId.toString(),s=Array.from(new Set([...this.getNeighbors(t,"right",this.cfg.m),...this.getNeighbors(t,"left",this.cfg.m)])).filter(i=>i!==n).slice(0,e),o=await this.snapshot();for(let i of s)if(this.isConnected(i)||this.hasAddresses(i))try{await xg(this.node,i,o,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE),this.diag.announcementsSent++}catch(a){console.warn("announce failed",i,a)}}async preconnectNeighbors(){try{let e=await Ne(this.node.peerId),t=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(e,"right",Math.min(6,this.cfg.m)),...this.getNeighbors(e,"left",Math.min(6,this.cfg.m))])).filter(s=>s!==t);for(let s of n)if(this.isConnected(s)||this.hasAddresses(s))try{await sl(this.node,s,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(o){Ir("preconnectNeighbors ping failed for %s - %o",s,o)}}catch(e){Ir("preconnectNeighbors outer failed - %o",e)}}startActivePreconnectLoop(){if(this.preconnectRunning)return;this.preconnectRunning=!0;let e=async()=>{if(!this.preconnectRunning||this.mode!=="active"){this.preconnectRunning=!1;return}try{let t=await this.selfCoord(),n=this.node.peerId.toString(),s=this.cfg.profile==="core"?6:3,o=Array.from(new Set([...this.getNeighbors(t,"right",Math.min(12,this.cfg.m)),...this.getNeighbors(t,"left",Math.min(12,this.cfg.m))])).filter(i=>i!==n).slice(0,s);for(let i of o)if(this.isConnected(i)||this.hasAddresses(i))try{await sl(this.node,i,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(a){Ir("active preconnect ping failed for %s - %o",i,a)}}catch(t){Ir("active preconnect tick failed - %o",t)}setTimeout(e,1e3)};e()}async sendLeaveToNeighbors(){try{let e=await Ne(this.node.peerId),t=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(e,"right",this.cfg.m),...this.getNeighbors(e,"left",this.cfg.m)])).filter(o=>o!==t).slice(0,8),s={v:1,from:this.node.peerId.toString(),timestamp:Date.now()};for(let o of n)try{await oE(this.node,o,s,this.protocols.PROTOCOL_LEAVE)}catch(i){Ir("sendLeave failed for %s - %o",o,i)}}catch(e){Ir("sendLeaveToNeighbors outer failed - %o",e)}}async handleLeave(e){try{let t=null,n=this.store.getById(e);if(n)t=n.coord;else try{t=await Ne(Pe(e))}catch(l){console.warn("handleLeave: could not hash departing peer id",e,l)}if(this.store.remove(e),t)try{await this.applyFailure(e,t)}catch{}if(!t)return;let s=Array.from(new Set([...this.store.neighborsRight(t,this.cfg.m),...this.store.neighborsLeft(t,this.cfg.m)])),o=this.expandCohort(s,t,Math.max(2,Math.ceil(this.cfg.m/2))),i=new Set(s),a=o.filter(l=>!i.has(l)),c=a.slice(0,Math.min(a.length,6));for(let l of c)try{if(await sl(this.node,l,this.protocols.PROTOCOL_PING),!this.isConnected(l)){let u=await this.snapshot();await xg(this.node,l,u,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE)}}catch(u){console.warn("warm/announce failed for",l,u)}await this.mergeNeighborSnapshots(c.slice(0,4))}catch(t){console.error("handleLeave failed for",e,t)}}async mergeAnnounceSnapshot(e,t){try{let n=Pe(e),s=await Ne(n),o=[];this.store.getById(e)||o.push(e),this.store.upsert(e,s),await this.applyTouch(e,s),t.metadata&&this.store.update(e,{metadata:t.metadata});for(let i of[...t.successors??[],...t.predecessors??[]])try{let a=await Ne(Pe(i));this.store.getById(i)||o.push(i),this.store.upsert(i,a),await this.applyTouch(i,a)}catch(a){console.warn("mergeAnnounceSnapshot: failed for",i,a)}for(let i of t.sample??[])try{let a=P(i.coord,"base64url");this.store.getById(i.id)||o.push(i.id),this.store.upsert(i.id,a),await this.applyTouch(i.id,a)}catch(a){Ir("mergeAnnounceSnapshot sample upsert failed for %s - %o",i.id,a)}this.enforceCapacity(),this.emitDiscovered(o)}catch(n){console.warn("mergeAnnounceSnapshot failed for",e,n)}}async seedFromPeerStore(){try{let e=this.node.peerStore?.getPeers?.()??[],t=[];for(let n of e)try{let s=await Ne(n.id),o=n.id.toString();this.store.getById(o)||t.push(o),this.store.upsert(o,s)}catch(s){console.warn("failed to add peer from peerStore",n?.id?.toString?.(),s)}try{let n=await Ne(this.node.peerId),s=this.node.peerId.toString();this.store.getById(s)||t.push(s),this.store.upsert(s,n)}catch(n){console.error("failed to add self to store",n)}this.enforceCapacity(),this.emitDiscovered(t)}catch(e){console.error("seedFromPeerStore failed:",e)}}startStabilizationLoop(){if(this.stabilizing)return;this.stabilizing=!0;let e=async()=>{if(this.stabilizing)try{await this.seedFromPeerStore(),await this.seedFromBootstraps(),await this.stabilizeOnce()}catch(t){console.error("stabilize tick failed:",t)}finally{let t=this.mode==="active"?300:1500;setTimeout(e,t)}};e()}async seedFromBootstraps(){if(!this.cfg.bootstraps||this.cfg.bootstraps.length===0)return;let e=[];for(let t of this.cfg.bootstraps.slice(0,8))try{let n=t;if(t.startsWith("/"))try{let a=cl(t).getPeerId();a&&(n=a)}catch{}let s=Pe(n),o=await Ne(s);this.store.getById(n)||e.push(n),this.store.upsert(n,o),await this.applyTouch(n,o)}catch(n){console.warn("seedFromBootstraps failed for",t,n)}this.enforceCapacity(),this.emitDiscovered(e)}async stabilizeOnce(){let e=await Ne(this.node.peerId),t=this.node.peerId.toString(),s=this.getNeighbors(e,"both",Math.max(2,this.cfg.m)).filter(o=>o!==t&&(this.isConnected(o)||this.hasAddresses(o)));await this.probeNeighborsLatency(s.slice(0,4)),await this.mergeNeighborSnapshots(s.slice(0,4))}async probeNeighborsLatency(e){for(let t of e)try{let n=await sl(this.node,t,this.protocols.PROTOCOL_PING);if(this.diag.pingsSent++,n.ok){let s=this.store.getById(t)?.coord??await Ne(Pe(t));await this.applySuccess(t,s,n.rttMs),this.diag.pingsOk++}else{let s=this.store.getById(t)?.coord??await Ne(Pe(t));await this.applyFailure(t,s),this.diag.pingsFail++}}catch{try{let s=this.store.getById(t)?.coord??await Ne(Pe(t));await this.applyFailure(t,s),this.diag.pingsFail++}catch{}}}async mergeNeighborSnapshots(e){let t=[];for(let n of e)try{let s=await Zv(this.node,n,this.protocols.PROTOCOL_NEIGHBORS);this.diag.snapshotsFetched++;let o=this.cfg.profile==="core"?16:8,i=this.cfg.profile==="core"?16:8,a=(s.successors??[]).slice(0,o),c=(s.predecessors??[]).slice(0,i);for(let u of[...a,...c])try{let d=await Ne(Pe(u));this.store.getById(u)||t.push(u),this.store.upsert(u,d),await this.applyTouch(u,d)}catch(d){console.warn("failed to merge neighbor",u,d)}let l=this.cfg.profile==="core"?8:6;for(let u of(s.sample??[]).slice(0,l))try{let d=P(u.coord,"base64url");this.store.getById(u.id)||t.push(u.id),this.store.upsert(u.id,d),await this.applyTouch(u.id,d)}catch(d){Ir("mergeNeighborSnapshots sample upsert failed for %s - %o",u.id,d)}}catch(s){console.warn("fetchNeighbors failed for",n,s)}this.enforceCapacity(),this.emitDiscovered(t)}async snapshot(){let e=await Ne(this.node.peerId),{n:t,confidence:n}=gd(this.store,this.cfg.m),s=this.cfg.profile==="core"?12:6,o=this.cfg.profile==="core"?12:6,i=this.cfg.profile==="core"?8:6,a=this.getNeighbors(e,"right",this.cfg.m),c=this.getNeighbors(e,"left",this.cfg.m),l=a.slice(0,s),u=c.slice(0,o),d=Array.from(new Set([...l.slice(0,4),...u.slice(0,4)])).slice(0,i),p=await Promise.all(d.map(async f=>{let h=this.store.getById(f);return h?{id:f,coord:Ev(h.coord),relevance:h.relevance}:{id:f,coord:"",relevance:0}}));return{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:l,predecessors:u,sample:p,size_estimate:t,confidence:n,sig:"",metadata:this.metadata}}neighborDistance(e,t,n){let s=new Set,o=Math.max(1,n),a=this.assembleCohort(t,o,s).findIndex(c=>c===e);return a>=0?a:Number.POSITIVE_INFINITY}getNeighbors(e,t,n){let s=[];return(t==="right"||t==="both")&&s.push(...this.store.neighborsRight(e,n)),(t==="left"||t==="both")&&s.push(...this.store.neighborsLeft(e,n)),Array.from(new Set(s)).slice(0,n)}nextSuccessor(e,t){let n=t.findIndex(s=>s.id===e.id);return t[(n+1)%t.length]}nextPredecessor(e,t){let n=t.findIndex(s=>s.id===e.id);return t[(n-1+t.length)%t.length]}assembleCohort(e,t,n){let s=[],o=n??new Set,i=this.store.neighborsRight(e,t*2),a=this.store.neighborsLeft(e,t*2),c=0,l=0;for(;s.length<t&&(c<i.length||l<a.length);)if(s.length%2===0){let u=i[c++];u&&!o.has(u)&&s.push(u)}else{let u=a[l++];u&&!o.has(u)&&s.push(u)}return Array.from(new Set(s)).slice(0,t)}expandCohort(e,t,n,s){let o=new Set(e),i=this.assembleCohort(t,e.length+n,s);for(let a of i)o.add(a);return Array.from(o)}async nearAnchorOnly(e){let t=P(e.key,"base64url"),n=await Yt(t),s=this.getNeighbors(n,"right",this.cfg.m),o=this.getNeighbors(n,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...s.slice(0,3),...o.slice(0,3)]),cohort_hint:Array.from(new Set([...s.slice(0,2),...o.slice(0,2)])),estimated_cluster_size:this.cfg.k,confidence:.5}}emitDiscovered(e){if(e.length===0)return;let t=Date.now(),n=this.cfg.profile==="core"?10*6e4:30*6e4,s=this.node,o=0;for(let i of Array.from(new Set(e)))if(!((this.announcedIds.get(i)??0)>t)){if(!this.bucketDiscovery.tryTake())break;try{let c=Pe(i);s.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:c,multiaddrs:[]}})),this.announcedIds.set(i,t+n),o++}catch(c){console.warn("emitDiscovered failed for",i,c)}}if(o>0&&this.announcedIds.size>4096)for(let[i,a]of this.announcedIds)a<=t&&this.announcedIds.delete(i)}pickAnchors(e){let t=Array.from(new Set(e));if(t.length===0)return[];let n=c=>.5,s=new Uint8Array(32),o=Ad(this.store,s,t,c=>this.isConnected(c),n),i=t.filter(c=>c!==o),a=Ad(this.store,s,i,c=>this.isConnected(c),n);return[o,a].filter(c=>!!c)}async routeAct(e){let t=P(e.key,"base64url"),n=await Yt(t),s=this.node.peerId.toString();if(this.neighborDistance(s,n,2)>1&&e.ttl>0){let d=new Set([...e.breadcrumbs??[],s]),p=this.assembleCohort(n,Math.max(4,this.cfg.m)).filter(m=>!d.has(m)),f=m=>.5,h=Ad(this.store,n,p,m=>this.isConnected(m),f);if(h){let m={...e,ttl:e.ttl-1,breadcrumbs:[...e.breadcrumbs??[],s]};try{return await rE(this.node,h,m,this.protocols.PROTOCOL_MAYBE_ACT)}catch(g){console.warn("forward maybeAct failed to",h,g)}}}let{n:i,confidence:a}=gd(this.store,this.cfg.m),c=this.getNeighbors(n,"right",this.cfg.m),l=this.getNeighbors(n,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...c.slice(0,4),...l.slice(0,4)]),cohort_hint:Array.from(new Set([...c.slice(0,4),...l.slice(0,4)])),estimated_cluster_size:Math.max(this.cfg.k,i),confidence:a}}report(e){}reportNetworkSize(e,t,n="external"){let s=Date.now();this.networkObservations.push({estimate:e,confidence:t,timestamp:s,source:n});let o=s-this.observationWindowMs;this.networkObservations=this.networkObservations.filter(i=>i.timestamp>o),this.networkObservations.length>this.maxObservations&&(this.networkObservations=this.networkObservations.slice(-this.maxObservations))}getNetworkSizeEstimate(){let e=gd(this.store,this.cfg.m),t=Date.now(),n=[{estimate:e.n,confidence:e.confidence,timestamp:t,source:"fret"},...this.networkObservations];if(n.length===0)return{size_estimate:0,confidence:0,sources:0};let s=0,o=0,i=0;for(let l of n){let u=t-l.timestamp,d=Math.exp(-u/(this.observationWindowMs/3)),p=d*l.confidence;o+=l.estimate*p,i+=l.confidence*d,s+=p}if(s===0)return{size_estimate:0,confidence:0,sources:0};let a=Math.round(o/s),c=i/n.length;return{size_estimate:a,confidence:Math.min(1,c),sources:n.length}}getNetworkChurn(){if(this.networkObservations.length<2)return 0;let e=Date.now(),t=this.observationWindowMs/2,n=e-t,s=this.networkObservations.filter(l=>l.timestamp>n),o=this.networkObservations.filter(l=>l.timestamp<=n);if(s.length===0||o.length===0)return 0;let i=s.reduce((l,u)=>l+u.estimate,0)/s.length,a=o.reduce((l,u)=>l+u.estimate,0)/o.length;return(i-a)/t*6e4}detectPartition(){if(this.networkObservations.length<10)return!1;let e=this.getNetworkSizeEstimate();if(e.confidence<.3)return!1;let t=Date.now()-3e4,n=this.networkObservations.filter(c=>c.timestamp<t);if(n.length<3)return!1;let s=n.slice(-5).reduce((c,l)=>c+l.estimate,0)/Math.min(5,n.length);if(e.size_estimate/s<.5)return!0;let i=Math.abs(this.getNetworkChurn()),a=e.size_estimate*.1;return i>a}setMetadata(e){this.metadata=e}getMetadata(e){return this.store.getById(e)?.metadata}listPeers(){return this.store.list().map(e=>({id:e.id,metadata:e.metadata}))}};var E9=os("service:discovery");function Jg(r,e){let t=r;for(let n of e.list())try{let s=Pe(n.id);t.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:s,multiaddrs:[]}}))}catch(s){E9("seedDiscovery failed for %s - %o",n.id,s)}}var Td=class{components;cfg;inner=null;nodeRef=null;constructor(e,t){this.components=e,this.cfg=t}get[Symbol.toStringTag](){return"@optimystic/fret"}setLibp2p(e){this.nodeRef=e}ensure(){if(!this.inner){if(!this.nodeRef)throw new Error("Libp2pFretService: libp2p node not injected");this.inner=new ki(this.nodeRef,this.cfg)}return this.inner}async start(){if(this.ensure(),!this.nodeRef)throw new Error("Libp2pFretService.start: libp2p node not injected");Jg(this.nodeRef,this.inner?.store??{}),await this.ensure().start()}async stop(){await this.inner?.stop()}async routeAct(e){return await this.ensure().routeAct(e)}getNeighborsForKey(e,t,n){return this.ensure().getNeighbors(e,t,n)}assembleCohortForKey(e,t){return this.ensure().assembleCohort(e,t)}getDiagnostics(){return this.ensure().getDiagnostics?.()}neighborDistance(e,t,n){return this.ensure().neighborDistance(e,t,n)}getNeighbors(e,t,n){return this.ensure().getNeighbors(e,t,n)}assembleCohort(e,t,n){return this.ensure().assembleCohort(e,t,n)}expandCohort(e,t,n,s){return this.ensure().expandCohort(e,t,n,s)}async ready(){await this.ensure().ready()}setMode(e){this.ensure().setMode(e)}setMetadata(e){this.ensure().setMetadata(e)}report(e){this.ensure().report(e)}getMetadata(e){return this.ensure().getMetadata(e)}listPeers(){return this.ensure().listPeers()}};function Zg(r){return e=>new Td(e,r)}var KE="/db-p2p/sync/",FE="1.0.0",hl=(r="")=>`${r}${KE}${FE}`;var js=class extends un{protocol;constructor(e,t,n=""){super(e,t),this.protocol=hl(n)}async requestBlock(e){return await this.processMessage(e,this.protocol)}getProtocol(){return this.protocol}};var dl=class{fretAdapter;peerNetwork;protocolPrefix;metrics={totalRequests:0,successByRing:new Map,failureByRing:new Map,averageDurationMs:0};constructor(e,t,n){this.fretAdapter=e,this.peerNetwork=t,this.protocolPrefix=n}log=ur("storage:restoration");async restore(e,t){let n=Date.now();this.metrics.totalRequests++;let s=await this.getMyRingPeers(e),o=this.getMyRingDepth();for(let a of s){let c=await this.queryPeer(a,e,t);if(c)return this.recordSuccess(o,e,Date.now()-n),c}for(let a=o-1;a>=0;a--){let c=this.fretAdapter.findPeersAtRing(a),l=this.filterByPartition(c,e,a);for(let u of l){let d=await this.queryPeer(u,e,t);if(d)return this.recordSuccess(a,e,Date.now()-n),d}}let i=Date.now()-n;this.log("restore failed for block %s after %dms",e,i)}createRestoreCallback(){return async(e,t)=>await this.restore(e,t)}async getMyRingPeers(e){let t=new TextEncoder().encode(e),n=await Yt(t);return this.fretAdapter.getFret().assembleCohort(n,10)}getMyRingDepth(){return this.fretAdapter.getMyArachnodeInfo()?.ringDepth??8}filterByPartition(e,t,n){if(n===0)return e;let s=this.extractBlockPrefix(t,n);return e.filter(o=>{let i=this.fretAdapter.getArachnodeInfo(o);return!i||!i.partition?!1:i.partition.prefixValue===s})}extractBlockPrefix(e,t){let n=new TextEncoder().encode(e),s=new Uint8Array(32);for(let i=0;i<Math.min(n.length,s.length);i++)s[i]=n[i];let o=0;for(let i=0;i<t;i++){let a=Math.floor(i/8),c=7-i%8,l=s[a]>>c&1;o=o<<1|l}return o}async queryPeer(e,t,n){try{let s=oe(e),i=await new js(s,this.peerNetwork,this.protocolPrefix).requestBlock({blockId:t,rev:n});return i.success?i.archive:void 0}catch(s){this.log("queryPeer failed for %s - %o",e,s);return}}recordSuccess(e,t,n){let s=this.metrics.successByRing.get(e)??0;this.metrics.successByRing.set(e,s+1);let o=Array.from(this.metrics.successByRing.values()).reduce((a,c)=>a+c,0),i=this.metrics.averageDurationMs*(o-1);this.metrics.averageDurationMs=(i+n)/o,console.log(`[Ring ${e}] Successfully restored block ${t} in ${n}ms`)}getMetrics(){return{...this.metrics}}};var fl=class{fretAdapter;storageMonitor;config;constructor(e,t,n){this.fretAdapter=e,this.storageMonitor=t,this.config=n}async determineRing(){let e=await this.storageMonitor.getCapacity();if(e.available<this.config.minCapacity)return-1;let s=1e3*(100*1024),o=e.available/s,i=Math.max(0,Math.ceil(-Math.log2(Math.max(.001,o))));return Math.min(i,16)}async calculatePartition(e,t){if(e===0)return;let n=await Ne({toString:()=>t}),s=e,o=this.extractPrefix(n,s);return{prefixBits:s,prefixValue:o}}async createArachnodeInfo(e){let t=await this.storageMonitor.getCapacity(),n=await this.determineRing(),s=n>=0?await this.calculatePartition(n,e):void 0;return{ringDepth:Math.max(0,n),partition:s,capacity:{total:t.total,used:t.used,available:t.available},status:"active"}}async shouldTransition(){let e=await this.storageMonitor.getCapacity(),t=e.used/e.total;if(t>this.config.thresholds.moveOut)return{shouldMove:!0,direction:"out",newRingDepth:await this.determineRing()+1};if(t<this.config.thresholds.moveIn){let n=await this.determineRing();if(n>0)return{shouldMove:!0,direction:"in",newRingDepth:n-1}}return{shouldMove:!1}}extractPrefix(e,t){let n=0;for(let s=0;s<t;s++){let o=Math.floor(s/8),i=7-s%8,a=e[o]>>i&1;n=n<<1|a}return n}};var pl=class{storage;config;constructor(e,t={}){this.storage=e,this.config=t}async getCapacity(){let t=this.config.totalBytes??10737418240,n=this.config.usedBytes,s=this.config.availableBytes;if(n!==void 0||s!==void 0||this.config.totalBytes!==void 0){let a=n??Math.max(0,t-(s??t)),c=s??Math.max(0,t-a);return{total:t,used:Math.min(t,Math.max(0,a)),available:Math.max(0,Math.min(t,c))}}let o=await this.estimateUsedSpace(),i=Math.max(0,t-o);return{total:t,used:o,available:i}}async estimateUsedSpace(){return 0}};var ml=class r{fret;static ARACHNODE_KEY="arachnode";constructor(e){this.fret=e}setArachnodeInfo(e){this.fret.setMetadata({[r.ARACHNODE_KEY]:e})}getArachnodeInfo(e){return this.fret.getMetadata(e)?.[r.ARACHNODE_KEY]}getMyArachnodeInfo(){let e=this.fret.node?.peerId?.toString();if(e)return this.getArachnodeInfo(e)}findPeersAtRing(e){return this.fret.listPeers().filter(n=>n.metadata?.[r.ARACHNODE_KEY]?.ringDepth===e).map(n=>n.id)}getKnownRings(){let e=this.fret.listPeers(),t=new Set;for(let n of e){let s=n.metadata?.[r.ARACHNODE_KEY];s?.ringDepth!==void 0&&t.add(s.ringDepth)}return Array.from(t).sort((n,s)=>n-s)}getRingStats(){let e=this.fret.listPeers(),t=new Map;for(let n of e){let s=n.metadata?.[r.ARACHNODE_KEY];if(s){let o=t.get(s.ringDepth)??{count:0,totalCapacity:0};t.set(s.ringDepth,{count:o.count+1,totalCapacity:o.totalCapacity+s.capacity.available})}}return Array.from(t.entries()).map(([n,s])=>({ringDepth:n,peerCount:s.count,avgCapacity:s.totalCapacity/s.count})).sort((n,s)=>n.ringDepth-s.ringDepth)}getFret(){return this.fret}};var _d=class{components;running=!1;log;protocol;repo;registrar;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("db-p2p:sync-service"),this.protocol=hl(t.protocolPrefix??""),this.repo=e.repo,this.registrar=e.registrar}async start(){this.running||(await this.registrar.handle(this.protocol,async e=>{await this.handleSyncRequest(e.stream)}),this.running=!0,this.log("Sync service started on protocol %s",this.protocol))}async stop(){this.running&&(await this.registrar.unhandle(this.protocol),this.running=!1,this.log("Sync service stopped"))}async handleSyncRequest(e){try{let t=await this.readRequest(e);this.log("[Ring Zulu] Received sync request for block %s revision %s",t.blockId,t.rev??"latest");let n=await this.buildArchive(t.blockId,t.rev,t.includePending,t.maxRevisions),s=n?{success:!0,archive:n,responderId:e.id}:{success:!1,error:"Block not found in local storage"};await this.sendResponse(e,s),this.log("[Ring Zulu] %s sync request for block %s",s.success?"Fulfilled":"Failed",t.blockId)}catch(t){this.log.error("Error handling sync request:",t);try{let n={success:!1,error:t instanceof Error?t.message:"Unknown error"};await this.sendResponse(e,n)}catch(n){this.log.error("Failed to send error response:",n)}}finally{try{await e.close()}catch{}}}async readRequest(e){let t=[];if(await rt(e,gr,async s=>{for await(let o of s)t.push(o.subarray())}),t.length===0)throw new Error("No request received");let n=C(t[0],"utf8");return JSON.parse(n)}async sendResponse(e,t){let n=JSON.stringify(t),s=P(n,"utf8"),o=rt([s],or);for await(let i of o)e.send(i)}async buildArchive(e,t,n,s){try{let o=t!==void 0?{rev:t,committed:[],pending:[]}:void 0,a=(await this.repo.get({blockIds:[e],context:o}))[e];if(!a||!a.state.latest)return;let c=a.state.latest;return{blockId:e,revisions:{[c.rev]:{action:{actionId:c.actionId,transform:{insert:a.block}},block:a.block}},range:[c.rev,c.rev+1]}}catch(o){this.log.error("Error building archive for block %s:",e,o);return}}},ey=(r={})=>e=>new _d(e,r);var dt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},vn=class extends Error{static name="ValidationError";name="ValidationError"},Pd=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Dd=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Vue=new Uint8Array(0);function zE(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function pr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function $E(r){return new TextEncoder().encode(r)}function HE(r){return new TextDecoder().decode(r)}var oy={};z(oy,{base32:()=>as,base32hex:()=>L9,base32hexpad:()=>O9,base32hexpadupper:()=>R9,base32hexupper:()=>M9,base32pad:()=>D9,base32padupper:()=>k9,base32upper:()=>P9,base32z:()=>N9});function S9(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var I9=S9,A9=I9,VE=A9;var ty=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ry=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 GE(this,e)}},ny=class{decoders;constructor(e){this.decoders=e}or(e){return GE(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function GE(r,e){return new ny({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var sy=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new ty(e,t,n),this.decoder=new ry(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Li({name:r,prefix:e,encode:t,decode:n}){return new sy(r,e,t,n)}function is({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=VE(t,r);return Li({prefix:e,name:r,encode:n,decode:o=>pr(s(o))})}function C9(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function T9(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function _9(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ke({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=_9(n);return Li({prefix:e,name:r,encode(o){return T9(o,n,t)},decode(o){return C9(o,s,t,r)}})}var as=Ke({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),P9=Ke({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),D9=Ke({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),k9=Ke({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),L9=Ke({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),M9=Ke({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),O9=Ke({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),R9=Ke({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),N9=Ke({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var iy={};z(iy,{base36:()=>gl,base36upper:()=>B9});var gl=is({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),B9=is({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ay={};z(ay,{base58btc:()=>qr,base58flickr:()=>U9});var qr=is({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),U9=is({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var K9=YE,WE=128,F9=127,z9=~F9,$9=Math.pow(2,31);function YE(r,e,t){e=e||[],t=t||0;for(var n=t;r>=$9;)e[t++]=r&255|WE,r/=128;for(;r&z9;)e[t++]=r&255|WE,r>>>=7;return e[t]=r|0,YE.bytes=t-n+1,e}var H9=cy,q9=128,jE=127;function cy(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw cy.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&jE)<<s:(i&jE)*Math.pow(2,s),s+=7}while(i>=q9);return cy.bytes=o-n,t}var V9=Math.pow(2,7),G9=Math.pow(2,14),W9=Math.pow(2,21),j9=Math.pow(2,28),Y9=Math.pow(2,35),X9=Math.pow(2,42),Q9=Math.pow(2,49),J9=Math.pow(2,56),Z9=Math.pow(2,63),eN=function(r){return r<V9?1:r<G9?2:r<W9?3:r<j9?4:r<Y9?5:r<X9?6:r<Q9?7:r<J9?8:r<Z9?9:10},tN={encode:K9,decode:H9,encodingLength:eN},rN=tN,yl=rN;function bl(r,e=0){return[yl.decode(r,e),yl.decode.bytes]}function Mi(r,e,t=0){return yl.encode(r,e,t),e}function Oi(r){return yl.encodingLength(r)}function Ni(r,e){let t=e.byteLength,n=Oi(r),s=n+Oi(t),o=new Uint8Array(s+t);return Mi(r,o,0),Mi(t,o,n),o.set(e,s),new Ri(r,t,e,o)}function XE(r){let e=pr(r),[t,n]=bl(e),[s,o]=bl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ri(t,s,i,e)}function QE(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&zE(r.bytes,t.bytes)}}var Ri=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function JE(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return sN(t,ly(r),e??qr.encoder);default:return oN(t,ly(r),e??as.encoder)}}var ZE=new WeakMap;function ly(r){let e=ZE.get(r);if(e==null){let t=new Map;return ZE.set(r,t),t}return e}var Bi=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==xl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==iN)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ni(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&QE(e.multihash,n.multihash)}toString(e){return JE(this,e)}toJSON(){return{"/":JE(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??eS(n,s,o.bytes))}else if(t[aN]===!0){let{version:n,multihash:s,code:o}=t,i=XE(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==xl)throw new Error(`Version 0 CID must use dag-pb (code: ${xl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=eS(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,xl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=pr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Ri(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=bl(e.subarray(t));return t+=p,d},s=n(),o=xl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=nN(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ly(o).set(n,e),o}};function nN(r,e){switch(r[0]){case"Q":{let t=e??qr;return[qr.prefix,t.decode(`${qr.prefix}${r}`)]}case qr.prefix:{let t=e??qr;return[qr.prefix,t.decode(r)]}case as.prefix:{let t=e??as;return[as.prefix,t.decode(r)]}case gl.prefix:{let t=e??gl;return[gl.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function sN(r,e,t){let{prefix:n}=t;if(n!==qr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function oN(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var xl=112,iN=18;function eS(r,e,t){let n=Oi(r),s=n+Oi(e),o=new Uint8Array(s+t.byteLength);return Mi(r,o,0),Mi(e,o,n),o.set(t,s),o}var aN=Symbol.for("@ipld/js-cid/CID");var cN=20;function hy({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new uy(r,e,t,n,s)}var uy=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??cN,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?tS(n,this.code,t?.truncate):n.then(s=>tS(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function tS(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ni(e,r)}var fy={};z(fy,{base64:()=>lN,base64pad:()=>uN,base64url:()=>dy,base64urlpad:()=>hN});var lN=Ke({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),uN=Ke({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),dy=Ke({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hN=Ke({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var py={};z(py,{base10:()=>dN});var dN=is({prefix:"9",name:"base10",alphabet:"0123456789"});var my={};z(my,{base16:()=>fN,base16upper:()=>pN});var fN=Ke({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),pN=Ke({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gy={};z(gy,{base2:()=>mN});var mN=Ke({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var yy={};z(yy,{base256emoji:()=>xN});var nS=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}"),gN=nS.reduce((r,e,t)=>(r[t]=e,r),[]),yN=nS.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function bN(r){return r.reduce((e,t)=>(e+=gN[t],e),"")}function wN(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=yN[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var xN=Li({prefix:"\u{1F680}",name:"base256emoji",encode:bN,decode:wN});var by={};z(by,{base8:()=>vN});var vN=Ke({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var wy={};z(wy,{identity:()=>EN});var EN=Li({prefix:"\0",name:"identity",encode:r=>HE(r),decode:r=>$E(r)});var Ahe=new TextEncoder,Che=new TextDecoder;var xy={};z(xy,{identity:()=>TN});var sS=0,AN="identity",oS=pr;function CN(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ni(sS,oS(r))}var TN={code:sS,name:AN,encode:oS,digest:CN};var Ey={};z(Ey,{sha256:()=>_N,sha512:()=>PN});var vy=ne(Z("crypto"),1);var _N=hy({name:"sha2-256",code:18,encode:r=>pr(vy.default.createHash("sha256").update(r).digest())}),PN=hy({name:"sha2-512",code:19,encode:r=>pr(vy.default.createHash("sha512").update(r).digest())});var iS={...wy,...gy,...by,...py,...my,...oy,...iy,...ay,...fy,...yy},Lhe={...Ey,...xy};function Iy(r){return e=>C(e,r)}function Ay(r){return e=>P(e,r)}function Ui(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ys(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function aS(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=P(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Ys(n);return be([t,s],t.length+s.length)}function cS(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=as.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 s=Ys(n);return be([t,s],t.length+s.length)}function Cy(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=C(e,"base32"),s=Ui(t);return`${n}:${s}`}var Ty=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new dt("Invalid byte value in IP address");e[n]=s}),e},lS=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,le.isIPv4)(t[n]),i;o&&(i=Ty(t[n]),t[n]=C(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,C(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new dt("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},uS=function(r){if(r.byteLength!==4)throw new dt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},hS=function(r){if(r.byteLength!==16)throw new dt("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new dt(`Invalid IPv6 address "${t}"`)}};function dS(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new dt(`Invalid IPv6 address "${r}"`)}}var Sy=Object.values(iS).map(r=>r.decoder),DN=(function(){let r=Sy[0].or(Sy[1]);return Sy.slice(2).forEach(e=>r=r.or(e)),r})();function fS(r){return DN.decode(r)}function pS(r){return e=>r.encoder.encode(e)}function kN(r){if(parseInt(r).toString()!==r)throw new vn("Value must be an integer")}function LN(r){if(r<0)throw new vn("Value must be a positive integer, or zero")}function MN(r){return e=>{if(e>r)throw new vn(`Value must be smaller than or equal to ${r}`)}}function ON(...r){return e=>{for(let t of r)t(e)}}var vl=ON(kN,LN,MN(65535));var it=-1,_y=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Dd(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},En=new _y,YN=[{code:4,name:"ip4",size:32,valueToBytes:Ty,bytesToValue:uS,validate:r=>{if(!(0,le.isIPv4)(r))throw new vn(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ys,bytesToValue:Ui,validate:vl},{code:273,name:"udp",size:16,valueToBytes:Ys,bytesToValue:Ui,validate:vl},{code:33,name:"dccp",size:16,valueToBytes:Ys,bytesToValue:Ui,validate:vl},{code:41,name:"ip6",size:128,valueToBytes:lS,bytesToValue:hS,stringToValue:dS,validate:r=>{if(!(0,le.isIPv6)(r))throw new vn(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:it},{code:43,name:"ipcidr",size:8,bytesToValue:Iy("base10"),valueToBytes:Ay("base10")},{code:53,name:"dns",size:it},{code:54,name:"dns4",size:it},{code:55,name:"dns6",size:it},{code:56,name:"dnsaddr",size:it},{code:132,name:"sctp",size:16,valueToBytes:Ys,bytesToValue:Ui,validate:vl},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:it,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:it,bytesToValue:Iy("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ay("base58btc")(r):Bi.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Cy,valueToBytes:aS},{code:445,name:"onion3",size:296,bytesToValue:Cy,valueToBytes:cS},{code:446,name:"garlic64",size:it},{code:447,name:"garlic32",size:it},{code:448,name:"tls"},{code:449,name:"sni",size:it},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:it,bytesToValue:pS(dy),valueToBytes:fS},{code:480,name:"http"},{code:481,name:"http-path",size:it,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:it}];YN.forEach(r=>{En.addProtocol(r)});function mS(r){let e=[],t=0;for(;t<r.length;){let n=Bt(r,t),s=En.getProtocol(n),o=ve(n),i=XN(s,r,t+o),a=0;i>0&&s.size===it&&(a=ve(i));let c=o+a+i,l={code:n,name:s.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,d=r.subarray(u,u+i);l.value=s.bytesToValue?.(d)??C(d)}e.push(l),t+=c}return e}function gS(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=En.getProtocol(n.code),o=ve(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??P(n.value),a=i.byteLength,s.size===it&&(c=ve(a)));let l=new Uint8Array(o+c+a),u=0;cn(n.code,l,u),u+=o,i!=null&&(s.size===it&&(cn(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return be(t,e)}function yS(r){if(r.charAt(0)!=="/")throw new dt('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=En.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new dt(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new dt(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new dt("Incomplete multiaddr");return e}function bS(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=En.getProtocol(e.code);if(t==null)throw new dt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function XN(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Bt(e,t)}var QN=Symbol.for("nodejs.util.inspect.custom"),Fy=Symbol.for("@multiformats/multiaddr");function JN(r){if(r==null&&(r="/"),ls(r))return r.getComponents();if(r instanceof Uint8Array)return mS(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),yS(r);if(Array.isArray(r))return r;throw new dt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Rd=class r{[Fy]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=JN(e),t.validate!==!1&&ZN(this)}get bytes(){return this.#r==null&&(this.#r=gS(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=bS(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Pd(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return V(this.bytes,e.bytes)}[QN](){return`Multiaddr(${this.toString()})`}};function ZN(r){r.getComponents().forEach(e=>{let t=En.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function ls(r){return!!r?.[Fy]}function H(r){return new Rd(r)}var Sl=class r{libp2p;clusterSize;selfCoordinationConfig;networkHighWaterMark=1;lastConnectedTime=Date.now();constructor(e,t=16,n){this.libp2p=e,this.clusterSize=t,this.selfCoordinationConfig={gracePeriodMs:n?.gracePeriodMs??3e4,shrinkageThreshold:n?.shrinkageThreshold??.5,allowSelfCoordination:n?.allowSelfCoordination??!0},this.setupConnectionTracking()}coordinatorCache=new Map;static MAX_CACHE_ENTRIES=1e3;log=ur("libp2p-key-network");toCacheKey(e){return C(e,"base64url")}setupConnectionTracking(){this.libp2p.addEventListener("connection:open",()=>{this.updateNetworkObservations()})}updateNetworkObservations(){(this.libp2p.getConnections?.()??[]).length>0&&(this.lastConnectedTime=Date.now());try{let n=this.getFret().getNetworkSizeEstimate();n.size_estimate>this.networkHighWaterMark&&(this.networkHighWaterMark=n.size_estimate,this.log("network-hwm-updated mark=%d confidence=%f",this.networkHighWaterMark,n.confidence))}catch{let n=(this.libp2p.getConnections?.().length??0)+1;n>this.networkHighWaterMark&&(this.networkHighWaterMark=n,this.log("network-hwm-updated mark=%d (from connections)",this.networkHighWaterMark))}}shouldAllowSelfCoordination(){if(!this.selfCoordinationConfig.allowSelfCoordination)return{allow:!1,reason:"disabled"};if(this.networkHighWaterMark<=1)return{allow:!0,reason:"bootstrap-node"};try{let t=this.getFret();if(t.detectPartition())return this.log("self-coord-blocked: partition-detected"),{allow:!1,reason:"partition-detected"};let n=t.getNetworkSizeEstimate(),s=1-n.size_estimate/this.networkHighWaterMark;if(s>this.selfCoordinationConfig.shrinkageThreshold)return this.log("self-coord-blocked: suspicious-shrinkage current=%d hwm=%d shrinkage=%f",n.size_estimate,this.networkHighWaterMark,s),{allow:!1,reason:"suspicious-shrinkage"}}catch{let t=this.libp2p.getConnections?.()??[];if(this.networkHighWaterMark>1&&t.length===0){let n=Date.now()-this.lastConnectedTime;if(n<this.selfCoordinationConfig.gracePeriodMs)return this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",n),{allow:!1,reason:"grace-period-not-elapsed"}}}let e=Date.now()-this.lastConnectedTime;return e<this.selfCoordinationConfig.gracePeriodMs&&(this.libp2p.getConnections?.()??[]).length===0?(this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",e),{allow:!1,reason:"grace-period-not-elapsed"}):(this.log("self-coord-allowed: extended-isolation (warn)"),{allow:!0,reason:"extended-isolation",warn:!0})}recordCoordinator(e,t,n=1800*1e3){let s=this.toCacheKey(e),o=Date.now();for(let[i,a]of this.coordinatorCache)a.expires<=o&&this.coordinatorCache.delete(i);for(this.coordinatorCache.set(s,{id:t,expires:o+n});this.coordinatorCache.size>r.MAX_CACHE_ENTRIES;){let i=this.coordinatorCache.keys().next().value;if(i==null)break;this.coordinatorCache.delete(i)}}getCachedCoordinator(e){let t=this.toCacheKey(e),n=this.coordinatorCache.get(t);if(n&&n.expires>Date.now())return n.id;n&&this.coordinatorCache.delete(t)}connect(e,t,n){let s=this.libp2p.getConnections?.(e)??[];if(Array.isArray(s)&&s.length>0&&typeof s[0]?.newStream=="function")return s[0].newStream([t]);let o={runOnLimitedConnection:!0,negotiateFully:!1};return this.libp2p.dialProtocol(e,[t],o)}getFret(){let e=this.libp2p.services?.fret;if(e==null)throw new Error("FRET service is not registered on this libp2p node");return e}async getNeighborIdsForKey(e,t){let n=this.getFret(),s=await Yt(e),o=n.getNeighbors(s,"both",t);return Array.from(new Set(o)).slice(0,t)}async findCoordinator(e,t){let n=new Set((t?.excludedPeers??[]).map(l=>l.toString())),s=this.toCacheKey(e).substring(0,12);this.log("findCoordinator:start key=%s excluded=%o",s,Array.from(n).map(l=>l.substring(0,12)));let o=this.getCachedCoordinator(e);if(o!=null&&!n.has(o.toString()))return this.log("findCoordinator:cached-hit key=%s coordinator=%s",s,o.toString().substring(0,12)),o;let i=3,a=500;for(let l=0;l<i;l++){let u=(this.libp2p.getConnections?.()??[]).map(f=>f.remotePeer),d=new Set(u.map(f=>f.toString()));this.log("findCoordinator:connected-peers key=%s count=%d peers=%o attempt=%d",s,u.length,u.map(f=>f.toString().substring(0,12)),l);try{let f=await this.getNeighborIdsForKey(e,this.clusterSize);this.log("findCoordinator:fret-neighbors key=%s candidates=%o",s,f.map(g=>g.substring(0,12)));let h=f.filter(g=>d.has(g)||g===this.libp2p.peerId.toString());this.log("findCoordinator:fret-connected key=%s count=%d peers=%o",s,h.length,h.map(g=>g.substring(0,12)));let m=h.find(g=>!n.has(g));if(m){let g=oe(m);return this.recordCoordinator(e,g),this.log("findCoordinator:fret-selected key=%s coordinator=%s",s,m.substring(0,12)),g}}catch(f){this.log("findCoordinator getNeighborIdsForKey failed - %o",f)}let p=u.find(f=>!n.has(f.toString()));if(p)return this.recordCoordinator(e,p),this.log("findCoordinator:connected-fallback key=%s coordinator=%s",s,p.toString().substring(0,12)),p;if(u.length===0&&l<i-1){this.log("findCoordinator:no-connections-retry key=%s attempt=%d delay=%dms",s,l,a),await new Promise(f=>setTimeout(f,a));continue}}let c=this.libp2p.peerId;if(!n.has(c.toString())){let l=this.shouldAllowSelfCoordination();if(!l.allow)throw this.log("findCoordinator:self-coord-blocked key=%s reason=%s",s,l.reason),new Error(`Self-coordination blocked: ${l.reason}. No coordinator available for key.`);return l.warn?this.log("findCoordinator:self-selected-warn key=%s coordinator=%s reason=%s",s,c.toString().substring(0,12),l.reason):this.log("findCoordinator:self-selected key=%s coordinator=%s reason=%s",s,c.toString().substring(0,12),l.reason),c}throw this.log("findCoordinator:all-excluded key=%s self=%s",s,c.toString().substring(0,12)),new Error("No coordinator available for key (all candidates excluded)")}getConnectedAddrsByPeer(){let e=this.libp2p.getConnections(),t={};for(let n of e){let s=n.remotePeer.toString(),o=n.remoteAddr?.toString?.();o&&(t[s]??=[]).push(o)}return t}parseMultiaddrs(e){let t=[];for(let n of e)try{H(n),t.push(n)}catch(s){console.warn("invalid multiaddr from connection",n,s)}return t}async findCluster(e){let t=this.getFret(),n=await Yt(e),s=t.assembleCohort(n,this.clusterSize),o=this.toCacheKey(e).substring(0,12),i=Array.from(new Set([...s,this.libp2p.peerId.toString()])),a=this.getConnectedAddrsByPeer(),c=Object.keys(a);this.log("findCluster key=%s fretCohort=%d connected=%d cohortPeers=%o",o,s.length,c.length,i.map(u=>u.substring(0,12)));let l={};for(let u of i){if(u===this.libp2p.peerId.toString()){l[u]={multiaddrs:this.libp2p.getMultiaddrs().map(p=>p.toString()),publicKey:this.libp2p.peerId.publicKey?.raw??new Uint8Array};continue}let d=a[u]??[];l[u]={multiaddrs:this.parseMultiaddrs(d),publicKey:new Uint8Array}}return this.log("findCluster:result key=%s clusterSize=%d withAddrs=%d connectedInCohort=%d",o,Object.keys(l).length,Object.values(l).filter(u=>u.multiaddrs.length>0).length,i.filter(u=>c.includes(u)||u===this.libp2p.peerId.toString()).length),l}};var jS=ne(Z("net"),1);var Ae=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),j=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),wS=r=>({match:e=>r.match(e)===!1?e:!1}),ce=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),wt=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),me=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function Ce(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var eB=j(421),xS=Ce(eB),Bd=j(54),Ud=j(55),Kd=j(56),$y=j(53),Sde=Ce(Bd,ce(j(421))),Ide=Ce(Ud,ce(j(421))),Ade=Ce(Kd,ce(j(421))),Cde=Ce(wt($y,Kd,Bd,Ud),ce(j(421))),vS=me(j(4),ce(j(43))),ES=me(ce(j(42)),j(41),ce(j(43))),Hy=wt(vS,ES),eo=wt(Hy,$y,Bd,Ud,Kd),SS=Ce(wt(Hy,me(wt($y,Kd,Bd,Ud),ce(j(421))))),qy=Ce(vS),Vy=Ce(ES),Tde=Ce(Hy),Gy=me(eo,j(6)),Il=me(eo,j(273)),Sn=Ce(me(Gy,ce(j(421)))),_de=Ce(Il),Wy=me(Il,Ae(460),ce(j(421))),Fd=me(Il,Ae(461),ce(j(421))),tB=wt(Wy,Fd),Pde=Ce(Wy),IS=Ce(Fd),zy=wt(eo,Gy,Il,Wy,Fd),AS=wt(me(zy,Ae(477),ce(j(421)))),Al=Ce(AS),CS=wt(me(zy,Ae(478),ce(j(421))),me(zy,Ae(448),ce(j(449)),Ae(477),ce(j(421)))),Cl=Ce(CS),TS=me(Il,Ae(280),ce(j(466)),ce(j(466)),ce(j(421))),jy=Ce(TS),_S=me(Fd,Ae(465),ce(j(466)),ce(j(466)),ce(j(421))),Yy=Ce(_S),Nd=wt(AS,CS,me(Gy,ce(j(421))),me(tB,ce(j(421))),me(eo,ce(j(421))),TS,_S,j(421)),zd=Ce(Nd),rB=me(ce(Nd),Ae(290),wS(Ae(281)),ce(j(421))),zt=Ce(rB),nB=wt(me(Nd,Ae(290),Ae(281),ce(j(421))),me(Nd,Ae(281),ce(j(421))),me(Ae(281),ce(j(421)))),Xy=Ce(nB),sB=wt(me(eo,j(6),Ae(480),ce(j(421))),me(eo,Ae(480),ce(j(421)))),Dde=Ce(sB),oB=me(eo,wt(me(j(6,"443"),Ae(480)),me(j(6),Ae(443)),me(j(6),Ae(448),Ae(480)),me(Ae(448),Ae(480)),Ae(448),Ae(443)),ce(j(421))),kde=Ce(oB),iB=wt(me(j(777),ce(j(421)))),Lde=Ce(iB),aB=wt(me(j(400),ce(j(421)))),$d=Ce(aB);var Te=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var WS=ne(Z("node:net"),1);var Qy={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},PS={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},DS=new globalThis.TextEncoder;function cB(r,e){let t=Qy[e],n=PS[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function lB(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Qy[e],s=PS[e],o=r;for(;o.length>0;){let i=DS.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function Jy(r,{size:e=32,utf8Buffer:t}={}){if(!Qy[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return lB(r,e,t);r=DS.encode(r)}return cB(r,e)}var Tl={hash:r=>Number(Jy(r,{size:32})),hashV:(r,e)=>uB(Tl.hash(r,e))};function uB(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),P(e,"base16")}var Zy=64,Ar=class{fp;h;seed;constructor(e,t,n,s=2){if(s>Zy)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=se(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?V(this.fp,e.fp):!1}};function to(r,e){return Math.floor(Math.random()*(e-r))+r}var ro=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ar))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Ar))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Ar))throw new TypeError("Invalid Fingerprint");let t=to(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Ar))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var hB=500,_l=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??Tl,this.seed=e.seed??to(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=P(e));let t=new Ar(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new ro(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new ro(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[to(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new ro(this.bucketSize));for(let a=0;a<hB;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new ro(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=P(e));let t=new Ar(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=P(e));let t=new Ar(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},dB={1:.5,2:.84,4:.95,8:.98};function fB(r=.001){return r>.002?2:r>1e-5?4:8}function kS(r,e=.001){let t=fB(e),n=dB[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Zy);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Hd=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Tl,this.seed=e.seed??to(0,Math.pow(2,10)),this.filterSeries=[new _l({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=P(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new _l({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Gr(r,e=.001,t){return new Hd({...kS(r,e),...t??{}})}function re(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new N(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}function LS(r){try{let e=re(r);switch(e.type){case"ip6":return kE("2000::/3",e.host);default:return!1}}catch{return!1}}function MS(r){try{let e=re(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function OS(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Pl(r){try{let e=re(r);switch(e.type){case"ip4":case"ip6":return OS(e.host);default:return!1}}catch{return!1}}function ft(r){try{return re(r),!0}catch{return!1}}var NS=ne(RS(),1),pB=["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"],mB=pB.map(r=>new NS.Netmask(r));function e3(r){for(let e of mB)if(e.contains(r))return!0;return!1}function gB(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function yB(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return e3(s)}function bB(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function wB(r){let e=r.split(":"),t=e[e.length-1];return e3(t)}function xB(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Hi(r){if((0,le.isIPv4)(r))return e3(r);if(gB(r))return yB(r);if(bB(r))return wB(r);if((0,le.isIPv6)(r))return xB(r)}function In(r){try{let e=re(r);switch(e.type){case"ip4":case"ip6":return Hi(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}var t3=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},BS=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function r3(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((d,p)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){p(BS(i));return}if(i&&(c=()=>{p(BS(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,p),t===Number.POSITIVE_INFINITY)return;let f=new t3;a=o.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(h){p(h)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?d():s instanceof Error?p(s):(f.message=s??`Promise timed out after ${t} milliseconds`,p(f))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var vB=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function EB(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=vB(r),d=async(...f)=>{let h=t.multiArgs?f:f[0];if(t.filter)try{if(!await t.filter(h))return}catch(m){n(),i(m);return}c.push(h),t.count===c.length&&(n(),o(c))},p=(...f)=>{n(),i(t.rejectionMultiArgs?f:f[0])};n=()=>{for(let f of a)u(f,d);for(let f of t.rejectionEvents)a.includes(f)||u(f,p)};for(let f of a)l(f,d);for(let f of t.rejectionEvents)a.includes(f)||l(f,p);t.signal&&t.signal.addEventListener("abort",()=>{p(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=r3(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function De(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=EB(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function no(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var qd=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Vd=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},so=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Gd=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Wd=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function SB(r){return r.reason}async function us(r,e,t){if(e==null)return r;let n=t?.translateError??SB;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var jd=class{deferred;signal;constructor(e){this.signal=e,this.deferred=tt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Vt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function IB(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Yd=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=IB(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,W(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Vt),this.cleanup())}async join(e={}){let t=new jd(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await us(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var qi=class extends he{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=no(this.emitEmpty.bind(this),1),this.emitIdle=no(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Vd;let n=new Yd(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Vt)}),this.clear()}async onEmpty(e){this.size!==0&&await De(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await De(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await De(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=It({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Vt("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var AB=Math.pow(2,20)*4,hs=class extends he{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??AB,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new B,this.writeBuffer=new B,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new Wd)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),us(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=It(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Fn(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new eh(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Fn("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Fn("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Fn(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Fn(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Gu;this.dispatchEvent(new th(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new qn))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new B(o);this.writeBuffer.consume(o.byteLength);let a=this.sendData(o);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Zu(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Va(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Va(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var Vi=class extends hs{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await De(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await De(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function US(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Xd=class extends he{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let s=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",s);let o=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",o)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await us(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new hn;let t=this.onCreateStream({...this.streamOptions,...e});return US(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Gd(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let s=this.streams.findIndex(o=>o===e);s!==-1&&this.streams.splice(s,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var Qd=class extends hs{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await De(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await De(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};function Dt(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var Gi=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var CB=1.2,TB=2,_B=5e3,PB=6e4,DB=5e3,Jd=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??DB;this.success=new Gi(t),this.failure=new Gi(t),this.next=new Gi(t),this.failureMultiplier=e.failureMultiplier??TB,this.timeoutMultiplier=e.timeoutMultiplier??CB,this.minTimeout=e.minTimeout??_B,this.maxTimeout=e.maxTimeout??PB,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),s=Dt([e.signal,n]);return W(1/0,s,n),s.start=Date.now(),s.timeout=t,s}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var FS=ne(Z("node:os"),1);function KS(r){return!!(r.startsWith("169.254.")||r.toLowerCase().startsWith("fe80"))}function n3(r,e,t){let n=[r.type,t??r.host];if(r.protocol!=null){let s=e??r.port;s!=null&&n.push(r.protocol,s)}return r.type==="ip6"&&r.zone!=null&&n.unshift("ip6zone",r.zone),r.cidr!=null&&n.push("ipcidr",r.cidr),H(`/${n.join("/")}`)}var kB={4:"IPv4",6:"IPv6"};function LB(r){return["0.0.0.0","::"].includes(r)}function MB(r){let e=[],t=FS.default.networkInterfaces();for(let[,n]of Object.entries(t))if(n!=null)for(let s of n)KS(s.address)||s.family===kB[r]&&e.push(s.address);return e}function zS(r,e){if(r==null)return[];let t=re(r);return(t.type==="ip4"||t.type==="ip6")&&LB(t.host)?MB(t.type==="ip4"?4:6).map(n=>n3(t,e,n)):[n3(t,e)]}function $S(r,e){if(typeof r!="string")throw new N(`invalid ip provided: ${r}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new N(`invalid port provided: ${e}`);if((0,le.isIPv4)(r))return H(`/ip4/${r}/tcp/${e}`);if((0,le.isIPv6)(r))return H(`/ip6/${r}/tcp/${e}`);throw new N(`invalid ip:port for creating a multiaddr: ${r}:${e}`)}var OB=4194304,Zd=class extends Error{static name="UnwrappedError";name="UnwrappedError"},kl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},o3=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},i3=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function RB(r){return typeof r?.closeRead=="function"}function NB(r){return typeof r?.close=="function"}function s3(r){return RB(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:NB(r)?r.status!=="open":!1}function BB(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function a3(r,e){let t=e?.maxBufferSize??OB,n=new B,s,o=!1;if(!BB(r))throw new N("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),s?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}s?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?s?.reject(u.error):s?.resolve()};r.addEventListener("close",a);let c=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(o===!0)throw new Zd("Stream was unwrapped");if(s3(r)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new so(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=d){s.resolve();break}if(await us(s.promise,u?.signal),s3(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}s=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(s3(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,p),new so(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return l.read(u)}let f=n.sublist(0,p);return n.consume(p),f},async write(u,d){if(o===!0)throw new Zd("Stream was unwrapped");r.send(u)||await De(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function ds(r,e={}){let t=a3(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ve(e.maxDataLength));let n=e?.lengthDecoder??Bt,s=e?.lengthEncoder??Dr;return{async read(i){let a=-1,c=new B;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new kl("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new i3(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new o3(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new so(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new so(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new B(s(i.byteLength),i),a)},async writeV(i,a){let c=new B(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Cr(r,e){let t=ds(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}function UB(r){return r?.addEventListener!=null}function KB(r){let e=It(),t,n=i=>{e.push(i.data)},s=()=>{e.end(),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",n),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",s)};return r.addEventListener("message",n),r.addEventListener("close",o,{once:!0}),r.addEventListener("remoteCloseWrite",s,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let c=a();for(;;){t=Promise.withResolvers();let{done:l,value:u}=await Promise.race([c.next(),t.promise]);if(r.writeStatus==="closing"||r.writeStatus==="closed"||(u!=null&&(r.send(u)||await Promise.race([De(r,"drain",{rejectionEvents:["close"]})])),l===!0))break}await r.close()}}}function HS(...r){let e=r.map(t=>UB(t)?KB(t):t);return rt(...e)}var FB=1024*1024*4,zB=1024*1024*4,ef=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new B,this.maxBufferSize=e.maxBufferSize??FB,this.maxDataLength=e.maxDataLength??zB,this.lengthDecoder=e.lengthDecoder??Bt,this.encodingLength=e.encodingLength??ve}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new N(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(t<0||t>this.maxDataLength)throw new kl("Invalid message length");let n=this.encodingLength(t),s=n+t;if(this.buffer.byteLength>=s){let o=this.buffer.sublist(n,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}};var fs=class extends qi{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var tf=class extends qi{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var rf=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new c3}consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new qd("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},c3=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function qS(r,e,t){let n,s,o=!1;function i(){let l={signal:s.signal};if(t?.timeout!=null){let u=Dt([s.signal,AbortSignal.timeout(t.timeout)]);W(1/0,u),l.signal=u}o=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{o=!1,!s.signal.aborted&&(n=setTimeout(i,e))})}let a=no(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{o||(clearTimeout(n),a())},start:()=>{c||(c=!0,s=new AbortController,W(1/0,s.signal),t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),s?.abort(),c=!1}}}var l3=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function xt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new l3({name:e,metrics:t}):n=new Map,n}var u3=class extends Vi{socket;constructor(e){let t=e.remoteAddr;if(e.localAddr!=null&&$d.matches(e.localAddr))t=e.localAddr;else if(t==null){if(e.socket.remoteAddress==null||e.socket.remotePort==null)throw new N("Could not determine remote address or port");t=$S(e.socket.remoteAddress,e.socket.remotePort)}super({...e,remoteAddr:t}),this.socket=e.socket,this.socket.on("data",n=>{this.onData(n)}),this.socket.on("error",n=>{this.log("tcp error",t,n),this.abort(n)}),this.socket.setTimeout(e.inactivityTimeout??120*1e3),this.socket.once("timeout",()=>{this.log("tcp timeout",t),this.abort(new kr)}),this.socket.once("end",()=>{this.log("tcp end",t),this.onTransportClosed()}),this.socket.once("close",n=>{if(this.log("tcp close",t),n){this.abort(new Error("TCP transmission error"));return}this.onTransportClosed()}),this.socket.on("drain",()=>{this.log("tcp drain"),this.safeDispatchEvent("drain")})}sendData(e){let t=0,n=!0;for(let s of e)if(t+=s.byteLength,n=this.socket.write(s),!n)break;return{sentBytes:t,canSendMore:n}}async sendClose(e){this.socket.destroyed||(this.socket.destroySoon(),await De(this.socket,"close",e))}sendReset(){this.socket.resetAndDestroy()}sendPause(){this.socket.pause()}sendResume(){this.socket.resume()}},nf=r=>new u3(r);var VS=ne(Z("os"),1),GS=ne(Z("path"),1);function sf(r,e={}){if($d.exactMatch(r)){let o=r.getComponents().find(i=>i.code===400)?.value;if(o==null)throw new N(`Multiaddr ${r} was not a Unix address`);return VS.default.platform()==="win32"?{path:GS.default.join("\\\\.\\pipe\\",o)}:{path:o}}let t=re(r),n=t.host,s=t.port;return{host:n,port:s,ipv6Only:t.type==="ip6",...e}}var at;(function(r){r[r.INACTIVE=0]="INACTIVE",r[r.ACTIVE=1]="ACTIVE",r[r.PAUSED=2]="PAUSED"})(at||(at={}));var of=class extends he{context;server;sockets=new Set;status={code:at.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,e.allowHalfOpen=e.allowHalfOpen??!1,this.shutdownController=new AbortController,W(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=WS.default.createServer(e,this.onSocket.bind(this)),e.maxConnections!==void 0&&(this.server.maxConnections=e.maxConnections),e.closeServerOnMaxConnections!=null&&e.closeServerOnMaxConnections.closeAbove<e.closeServerOnMaxConnections.listenBelow)throw new N("closeAbove must be >= listenBelow");e.metrics?.registerMetricGroup("libp2p_tcp_inbound_connections_total",{label:"address",help:"Current active connections in TCP listener",calculate:()=>({[this.addr]:this.sockets.size})}),this.metrics={status:e.metrics?.registerMetricGroup("libp2p_tcp_listener_status_info",{label:"address",help:"Current status of the TCP listener socket"}),errors:e.metrics?.registerMetricGroup("libp2p_tcp_listener_errors_total",{label:"address",help:"Total count of TCP listener errors by type"}),events:e.metrics?.registerMetricGroup("libp2p_tcp_listener_events_total",{label:"address",help:"Total count of TCP listener events by type"})},this.server.on("listening",()=>{let t=this.server.address();t==null?this.addr="unknown":typeof t=="string"?this.addr=t:this.addr=`${t.address}:${t.port}`,this.metrics.status?.update({[this.addr]:at.ACTIVE}),this.safeDispatchEvent("listening")}).on("error",t=>{this.metrics.errors?.increment({[`${this.addr} listen_error`]:!0}),this.safeDispatchEvent("error",{detail:t})}).on("close",()=>{this.metrics.status?.update({[this.addr]:this.status.code}),this.status.code!==at.PAUSED&&this.safeDispatchEvent("close")}).on("drop",()=>{this.metrics.events?.increment({[`${this.addr} drop`]:!0})})}onSocket(e){if(this.metrics.events?.increment({[`${this.addr} connection`]:!0}),this.status.code!==at.ACTIVE)throw e.destroy(),new yr("Server is not listening yet");let t;try{t=nf({socket:e,inactivityTimeout:this.context.inactivityTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,direction:"inbound",localAddr:this.status.listeningAddr,log:this.context.logger.forComponent("libp2p:tcp:connection")})}catch(n){this.log.error("inbound connection failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_to_connection`]:!0}),e.destroy();return}this.log("new inbound connection %s",t.remoteAddr),this.sockets.add(e),this.context.upgrader.upgradeInbound(t,{signal:this.shutdownController.signal}).then(()=>{this.log("inbound connection upgraded %s",t.remoteAddr),e.once("close",()=>{this.sockets.delete(e),this.context.closeServerOnMaxConnections!=null&&this.sockets.size<this.context.closeServerOnMaxConnections.listenBelow&&this.resume().catch(n=>{this.log.error("error attempting to listen server once connection count under limit - %e",n),this.context.closeServerOnMaxConnections?.onListenError?.(n)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&(this.log("pausing incoming connections as limit is exceeded - %d/%d",this.sockets.size,this.context.closeServerOnMaxConnections.closeAbove),this.pause())}).catch(async n=>{this.log.error("inbound connection upgrade failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),t.abort(n)})}getAddrs(){if(this.status.code===at.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[H(`/unix/${encodeURIComponent(e)}`)]:zS(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===at.ACTIVE||this.status.code===at.PAUSED)throw new Qu("server is already listening");try{this.status={code:at.ACTIVE,listeningAddr:e,netConfig:sf(e,this.context)},await this.resume()}catch(t){throw this.status={code:at.INACTIVE},t}}async close(e){let t=[];this.server.listening&&t.push(De(this.server,"close",e)),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(n=>{n.readable&&(t.push(De(n,"close",e)),n.destroy())}),await Promise.all(t)}async resume(){if(this.server.listening||this.status.code===at.INACTIVE)return;let e=this.status.netConfig;await new Promise((t,n)=>{this.server.once("error",n),this.server.listen(e,t)}),this.status={...this.status,code:at.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===at.PAUSED&&e){this.status={code:at.INACTIVE};return}!this.server.listening||this.status.code!==at.ACTIVE||(this.log("%s server on %s",e?"closing":"pausing",this.server.address()),this.status=e?{code:at.INACTIVE}:{...this.status,code:at.PAUSED},this.server.close())}};var af=class{opts;metrics;components;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:tcp"),this.opts=t,this.components=e,e.metrics!=null&&(this.metrics={events:e.metrics.registerCounterGroup("libp2p_tcp_dialer_events_total",{label:"event",help:"Total count of TCP dialer events by type"}),errors:e.metrics.registerCounterGroup("libp2p_tcp_dialer_errors_total",{label:"event",help:"Total count of TCP dialer events by type"})})}[ih]=!0;[Symbol.toStringTag]="@libp2p/tcp";[je]=["@libp2p/transport"];async dial(e,t){t.keepAlive=t.keepAlive??!0,t.noDelay=t.noDelay??!0,t.allowHalfOpen=t.allowHalfOpen??!1;let n=await this._connect(e,t),s;try{s=nf({socket:n,inactivityTimeout:this.opts.outboundSocketInactivityTimeout,metrics:this.metrics?.events,direction:"outbound",remoteAddr:e,log:this.log.newScope("connection")})}catch(o){throw this.metrics?.errors.increment({outbound_to_connection:!0}),n.destroy(o),o}try{return this.log("new outbound connection %s",s.remoteAddr),await t.upgrader.upgradeOutbound(s,t)}catch(o){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection - %e",o),s.abort(o),o}}async _connect(e,t){t.signal.throwIfAborted(),t.onProgress?.(new Te("tcp:open-connection"));let n;return new Promise((s,o)=>{let i=Date.now(),a=sf(e,{...this.opts.dialOpts??{},...t});this.log("dialing %a with opts %o",e,a),n=jS.default.connect(a);let c=f=>{this.log.error("dial to %a errored - %e",e,f);let h=a.path??`${a.host??""}:${a.port}`;f.message=`connection error ${h}: ${f.message}`,this.metrics?.events.increment({error:!0}),p(f)},l=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let f=new kr(`Connection timeout after ${Date.now()-i}ms`);n.emit("error",f)},u=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),p()},d=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),p(new Vt)},p=f=>{if(n.removeListener("error",c),n.removeListener("timeout",l),n.removeListener("connect",u),t.signal!=null&&t.signal.removeEventListener("abort",d),f!=null){o(f);return}s(n)};n.on("error",c),n.on("timeout",l),n.on("connect",u),t.signal.addEventListener("abort",d)}).catch(s=>{throw n?.destroy(),s})}createListener(e){return new of({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,inactivityTimeout:this.opts.inboundSocketInactivityTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(t=>Sn.exactMatch(t)||t.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function YS(r={}){return e=>new af(e,r)}var Ll;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:se(0),payloadType:se(0),payload:se(0),signature:se(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(Ll||(Ll={}));var cf=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Jt=class r{static createFromProtobuf=e=>{let t=Ll.decode(e),n=Pt(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let s=e.domain,o=e.codec,i=e.marshal(),a=XS(s,o,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let s=r.createFromProtobuf(e);if(!await s.validate(t,n))throw new cf("Envelope signature is not valid for the given domain");return s};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=Ll.encode({publicKey:nt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:V(this.marshal(),e.marshal())}async validate(e,t){let n=XS(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},XS=(r,e,t)=>{let n=P(r),s=Dr(n.byteLength),o=Dr(e.length),i=Dr(t.length);return new B(s,n,o,e,i,t)};var U1e=new Uint8Array(0);function QS(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var $B=eI,JS=128,HB=127,qB=~HB,VB=Math.pow(2,31);function eI(r,e,t){e=e||[],t=t||0;for(var n=t;r>=VB;)e[t++]=r&255|JS,r/=128;for(;r&qB;)e[t++]=r&255|JS,r>>>=7;return e[t]=r|0,eI.bytes=t-n+1,e}var GB=h3,WB=128,ZS=127;function h3(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw h3.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&ZS)<<s:(i&ZS)*Math.pow(2,s),s+=7}while(i>=WB);return h3.bytes=o-n,t}var jB=Math.pow(2,7),YB=Math.pow(2,14),XB=Math.pow(2,21),QB=Math.pow(2,28),JB=Math.pow(2,35),ZB=Math.pow(2,42),eU=Math.pow(2,49),tU=Math.pow(2,56),rU=Math.pow(2,63),nU=function(r){return r<jB?1:r<YB?2:r<XB?3:r<QB?4:r<JB?5:r<ZB?6:r<eU?7:r<tU?8:r<rU?9:10},sU={encode:$B,decode:GB,encodingLength:nU},oU=sU,d3=oU;function f3(r,e=0){return[d3.decode(r,e),d3.decode.bytes]}function tI(r){let e=QS(r),[t,n]=f3(e),[s,o]=f3(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new p3(t,s,i,e)}var p3=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var rI="libp2p-peer-record",nI=Uint8Array.from([3,1]);var Ml;(function(r){let e;(function(n){let s;n.codec=()=>(s==null&&(s=Q((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:se(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(u&7);break}}}return c})),s),n.encode=o=>X(o,n.codec()),n.decode=(o,i)=>Y(o,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Q((n,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(s.uint32(10),s.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(s.uint32(16),s.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)s.uint32(26),r.AddressInfo.codec().encode(i,s);o.lengthDelimited!==!1&&s.ldelim()},(n,s,o={})=>{let i={peerId:se(0),seq:0n,addresses:[]},a=s==null?n.len:n.pos+s;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(o.limits?.addresses!=null&&i.addresses.length===o.limits.addresses)throw new Ie('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:o.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>X(n,r.codec()),r.decode=(n,s)=>Y(n,r.codec(),s)})(Ml||(Ml={}));function sI(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var Zt=class r{static createFromProtobuf=e=>{let t=Ml.decode(e),n=Ur(tI(t.peerId)),s=(t.addresses??[]).map(i=>H(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=rI;static CODEC=nI;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Ml.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!sI(this.multiaddrs,e.multiaddrs))}};var ime=new Uint8Array(0);function oI(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function An(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var cU=cI,iI=128,lU=127,uU=~lU,hU=Math.pow(2,31);function cI(r,e,t){e=e||[],t=t||0;for(var n=t;r>=hU;)e[t++]=r&255|iI,r/=128;for(;r&uU;)e[t++]=r&255|iI,r>>>=7;return e[t]=r|0,cI.bytes=t-n+1,e}var dU=m3,fU=128,aI=127;function m3(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw m3.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&aI)<<s:(i&aI)*Math.pow(2,s),s+=7}while(i>=fU);return m3.bytes=o-n,t}var pU=Math.pow(2,7),mU=Math.pow(2,14),gU=Math.pow(2,21),yU=Math.pow(2,28),bU=Math.pow(2,35),wU=Math.pow(2,42),xU=Math.pow(2,49),vU=Math.pow(2,56),EU=Math.pow(2,63),SU=function(r){return r<pU?1:r<mU?2:r<gU?3:r<yU?4:r<bU?5:r<wU?6:r<xU?7:r<vU?8:r<EU?9:10},IU={encode:cU,decode:dU,encodingLength:SU},AU=IU,Ol=AU;function Rl(r,e=0){return[Ol.decode(r,e),Ol.decode.bytes]}function Wi(r,e,t=0){return Ol.encode(r,e,t),e}function ji(r){return Ol.encodingLength(r)}function lf(r,e){let t=e.byteLength,n=ji(r),s=n+ji(t),o=new Uint8Array(s+t);return Wi(r,o,0),Wi(t,o,n),o.set(e,s),new Yi(r,t,e,o)}function Xi(r){let e=An(r),[t,n]=Rl(e),[s,o]=Rl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Yi(t,s,i,e)}function uI(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&oI(r.bytes,t.bytes)}}var Yi=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var g3=1e3,hI=60*g3,dI=15,fI=120*hI,pI=1,hf=5e3,mI=100,y3="circuit-relay-source",Nl=`${ja}-circuit-relay`,gI=2*hI,yI=BigInt(1<<17),Wr="/libp2p/circuit/relay/0.2.0/hop",Bl="/libp2p/circuit/relay/0.2.0/stop",bI=30*g3,dme=30*g3,Ul=300,wI=4096,xI=.001;var Ee;(function(r){let e;(function(s){s.RESERVE="RESERVE",s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.RESERVE=0]="RESERVE",s[s.CONNECT=1]="CONNECT",s[s.STATUS=2]="STATUS"})(t||(t={})),(function(s){s.codec=()=>Wt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Q((s,o,i={})=>{i.lengthDelimited!==!1&&o.fork(),s.type!=null&&(o.uint32(8),r.Type.codec().encode(s.type,o)),s.peer!=null&&(o.uint32(18),Qi.codec().encode(s.peer,o)),s.reservation!=null&&(o.uint32(26),df.codec().encode(s.reservation,o)),s.limit!=null&&(o.uint32(34),Ji.codec().encode(s.limit,o)),s.status!=null&&(o.uint32(40),ie.codec().encode(s.status,o)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=Qi.codec().decode(s,s.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=df.codec().decode(s,s.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=Ji.codec().decode(s,s.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=ie.codec().decode(s);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>X(s,r.codec()),r.decode=(s,o)=>Y(s,r.codec(),o)})(Ee||(Ee={}));var er;(function(r){let e;(function(s){s.CONNECT="CONNECT",s.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(s){s[s.CONNECT=0]="CONNECT",s[s.STATUS=1]="STATUS"})(t||(t={})),(function(s){s.codec=()=>Wt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Q((s,o,i={})=>{i.lengthDelimited!==!1&&o.fork(),s.type!=null&&(o.uint32(8),r.Type.codec().encode(s.type,o)),s.peer!=null&&(o.uint32(18),Qi.codec().encode(s.peer,o)),s.limit!=null&&(o.uint32(26),Ji.codec().encode(s.limit,o)),s.status!=null&&(o.uint32(32),ie.codec().encode(s.status,o)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=Qi.codec().decode(s,s.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=Ji.codec().decode(s,s.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=ie.codec().decode(s);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>X(s,r.codec()),r.decode=(s,o)=>Y(s,r.codec(),o)})(er||(er={}));var Qi;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let o of t.addrs)n.uint32(18),n.bytes(o);s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={id:se(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.id=t.bytes();break}case 2:{if(s.limits?.addrs!=null&&o.addrs.length===s.limits.addrs)throw new Ie('Decode error - map field "addrs" had too many elements');o.addrs.push(t.bytes());break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(Qi||(Qi={}));var df;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let o of t.addrs)n.uint32(18),n.bytes(o);t.voucher!=null&&(n.uint32(26),ff.codec().encode(t.voucher,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.expire=t.uint64();break}case 2:{if(s.limits?.addrs!=null&&o.addrs.length===s.limits.addrs)throw new Ie('Decode error - map field "addrs" had too many elements');o.addrs.push(t.bytes());break}case 3:{o.voucher=ff.codec().decode(t,t.uint32(),{limits:s.limits?.voucher});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(df||(df={}));var Ji;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.duration=t.uint32();break}case 2:{o.data=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(Ji||(Ji={}));var ie;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(ie||(ie={}));var b3;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(b3||(b3={}));(function(r){r.codec=()=>Wt(b3)})(ie||(ie={}));var Zi;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={relay:se(0),peer:se(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.relay=t.bytes();break}case 2:{o.peer=t.bytes();break}case 3:{o.expiration=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(Zi||(Zi={}));var ff;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&(n.uint32(26),Zi.codec().encode(t.payload,n)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:se(0),payloadType:se(0),signature:se(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=Zi.codec().decode(t,t.uint32(),{limits:s.limits?.payload});break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(ff||(ff={}));function CU(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var TU=CU,_U=TU,vI=_U;var w3=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},x3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 EI(this,e)}},v3=class{decoders;constructor(e){this.decoders=e}or(e){return EI(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function EI(r,e){return new v3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var E3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new w3(e,t,n),this.decoder=new x3(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function SI({name:r,prefix:e,encode:t,decode:n}){return new E3(r,e,t,n)}function ea({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=vI(t,r);return SI({prefix:e,name:r,encode:n,decode:o=>An(s(o))})}function PU(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function DU(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function kU(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function jr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=kU(n);return SI({prefix:e,name:r,encode(o){return DU(o,n,t)},decode(o){return PU(o,s,t,r)}})}var Kl=jr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Eme=jr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Sme=jr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ime=jr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ame=jr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Cme=jr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Tme=jr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),_me=jr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Pme=jr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var pf=ea({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Lme=ea({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Cn=ea({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Rme=ea({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});function II(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return MU(t,S3(r),e??Cn.encoder);default:return OU(t,S3(r),e??Kl.encoder)}}var AI=new WeakMap;function S3(r){let e=AI.get(r);if(e==null){let t=new Map;return AI.set(r,t),t}return e}var I3=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Fl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==RU)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=lf(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&uI(e.multihash,n.multihash)}toString(e){return II(this,e)}toJSON(){return{"/":II(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??CI(n,s,o.bytes))}else if(t[NU]===!0){let{version:n,multihash:s,code:o}=t,i=Xi(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Fl)throw new Error(`Version 0 CID must use dag-pb (code: ${Fl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=CI(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Fl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=An(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Yi(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=Rl(e.subarray(t));return t+=p,d},s=n(),o=Fl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=LU(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return S3(o).set(n,e),o}};function LU(r,e){switch(r[0]){case"Q":{let t=e??Cn;return[Cn.prefix,t.decode(`${Cn.prefix}${r}`)]}case Cn.prefix:{let t=e??Cn;return[Cn.prefix,t.decode(r)]}case Kl.prefix:{let t=e??Kl;return[Kl.prefix,t.decode(r)]}case pf.prefix:{let t=e??pf;return[pf.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function MU(r,e,t){let{prefix:n}=t;if(n!==Cn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function OU(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Fl=112,RU=18;function CI(r,e,t){let n=ji(r),s=n+ji(e),o=new Uint8Array(s+t.byteLength);return Wi(r,o,0),Wi(e,o,n),o.set(t,s),o}var NU=Symbol.for("@ipld/js-cid/CID");var T3=ne(Z("crypto"),1);var BU=20;function C3({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new A3(r,e,t,n,s)}var A3=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??BU,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?TI(n,this.code,t?.truncate):n.then(s=>TI(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function TI(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return lf(e,r)}var UU=C3({name:"sha2-256",code:18,encode:r=>An(T3.default.createHash("sha256").update(r).digest())}),Gme=C3({name:"sha2-512",code:19,encode:r=>An(T3.default.createHash("sha512").update(r).digest())});var mf=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},gf=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},zl=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},yf=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},bf=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function _I(r,e,t){let n=e.remaining,s=o=>{let i=BigInt(o.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new mf(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",s)}function PI(r,e,t,n,s){function o(u){r.abort(u),e.abort(u)}let i=[t,n.signal];if(n.limit?.duration!=null){s.log("limiting relayed connection duration to %dms",n.limit.duration);let u=AbortSignal.timeout(n.limit.duration);W(1/0,u),i.push(u)}let a=Dt(i);W(1/0,a);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let l=()=>{let u;t.aborted?u=t.reason:u=new gf(`duration limit of ${n.limit?.duration} ms exceeded`),o(u)};a.addEventListener("abort",l,{once:!0}),c!=null&&(_I(e,c,s),_I(r,c,s)),HS(r,e,r).catch(u=>{o(u)}).finally(()=>{a.clear()})}function _3(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var $l=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},wf=Ce(me(zd.matchers[0],Ae(290))),xf=Ce(Ae(290));var o0e=new Uint8Array(0);function vf(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function KU(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var FU=KU,zU=FU,DI=zU;var P3=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},D3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 kI(this,e)}},k3=class{decoders;constructor(e){this.decoders=e}or(e){return kI(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function kI(r,e){return new k3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var L3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new P3(e,t,n),this.decoder=new D3(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function $U({name:r,prefix:e,encode:t,decode:n}){return new L3(r,e,t,n)}function M3({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=DI(t,r);return $U({prefix:e,name:r,encode:n,decode:o=>vf(s(o))})}var LI=M3({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),d0e=M3({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var HU=RI,MI=128,qU=127,VU=~qU,GU=Math.pow(2,31);function RI(r,e,t){e=e||[],t=t||0;for(var n=t;r>=GU;)e[t++]=r&255|MI,r/=128;for(;r&VU;)e[t++]=r&255|MI,r>>>=7;return e[t]=r|0,RI.bytes=t-n+1,e}var WU=O3,jU=128,OI=127;function O3(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw O3.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&OI)<<s:(i&OI)*Math.pow(2,s),s+=7}while(i>=jU);return O3.bytes=o-n,t}var YU=Math.pow(2,7),XU=Math.pow(2,14),QU=Math.pow(2,21),JU=Math.pow(2,28),ZU=Math.pow(2,35),eK=Math.pow(2,42),tK=Math.pow(2,49),rK=Math.pow(2,56),nK=Math.pow(2,63),sK=function(r){return r<YU?1:r<XU?2:r<QU?3:r<JU?4:r<ZU?5:r<eK?6:r<tK?7:r<rK?8:r<nK?9:10},oK={encode:HU,decode:WU,encodingLength:sK},iK=oK,R3=iK;function N3(r,e=0){return[R3.decode(r,e),R3.decode.bytes]}function NI(r){let e=vf(r),[t,n]=N3(e),[s,o]=N3(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new B3(t,s,i,e)}var B3=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function oo(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function Ef(r){let e=NI(LI.decode(`z${r}`));return Ur(e)}var $t=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return oo(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return oo(this.map.values(),e=>e.key)}values(){return oo(this.map.values(),e=>e.value)}get size(){return this.map.size}};var io=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return oo(this.set.entries(),e=>{let t=Ef(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Ef(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return oo(this.set.values(),e=>Ef(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Sf=class{filter;constructor(e,t){this.filter=Gr(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function U3(r,e=.001){return new Sf(r,e)}var K3=class extends $t{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Hl(r){let{name:e,metrics:t}=r,n;return t!=null?n=new K3({name:e,metrics:t}):n=new $t,n}var F3=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};function BI(r,e){let t=new F3(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,s=()=>{n.abort(t)},o=AbortSignal.timeout(r);o.addEventListener("abort",s);let i=n.signal;return i.reset=a=>{o?.removeEventListener("abort",s),o=AbortSignal.timeout(a??r),o.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{o?.removeEventListener("abort",s),o=void 0},i}var If=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=t.maxReservations??dI,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??fI,this.defaultDurationLimit=t.defaultDurationLimit??gI,this.defaultDataLimit=t.defaultDataLimit??yI,this.reservations=Hl({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let s=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&s==null)return{status:ie.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",e),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),s={addr:t,expiry:o,limit:i,signal:BI(this.reservationTtl)}),this.reservations.set(e,s),s.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:ie.OK,expire:Math.round(o.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var Af=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return Zi.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof r)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var lK={maxOutboundStopStreams:Ul},Cf=class extends he{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=t?.hopTimeout??bI,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??lK.maxOutboundStopStreams,this.reservationStore=new If(e,t.reservations),this.shutdownController=new AbortController,W(1/0,this.shutdownController.signal),this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(Wr,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(Wr),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);W(1/0,n);let s={signal:n},o=Cr(e);try{let i=await o.pb(Ee).read(s);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},s)}catch(i){this.log.error("error while handling hop - %e",i),await o.pb(Ee).write({type:Ee.Type.STATUS,status:ie.MALFORMED_MESSAGE},s),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},s){switch(this.log("received hop message"),t.type){case Ee.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},s);break;case Ee.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(Ee).write({type:Ee.Type.STATUS,status:ie.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let s=e.pb(Ee);if(this.log("hop reserve request from %p",t.remotePeer),zt.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await s.write({type:Ee.Type.STATUS,status:ie.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await s.write({type:Ee.Type.STATUS,status:ie.PERMISSION_DENIED},n);return}let o=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(o.status!==ie.OK){await s.write({type:Ee.Type.STATUS,status:o.status},n);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[y3]:{value:1,ttl:i}}},n)}await s.write({type:Ee.Type.STATUS,status:ie.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await s.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[y3]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let n=[];for(let o of this.components.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||n.push(o.bytes);let s=await Jt.seal(new Af({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:nt(s.publicKey),payloadType:s.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:s.signature}}}async handleConnect({stream:e,request:t,connection:n},s){let o=e.pb(Ee);if(zt.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await o.write({type:Ee.Type.STATUS,status:ie.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(H),i=Ur(Xi(t.peer.id))}catch(d){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,d),await o.write({type:Ee.Type.STATUS,status:ie.MALFORMED_MESSAGE},s);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,ie.NO_RESERVATION),await o.write({type:Ee.Type.STATUS,status:ie.NO_RESERVATION},s);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await o.write({type:Ee.Type.STATUS,status:ie.PERMISSION_DENIED},s);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await o.write({type:Ee.Type.STATUS,status:ie.NO_RESERVATION},s);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:er.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await o.write({type:Ee.Type.STATUS,status:ie.CONNECTION_FAILED},s);return}await o.write({type:Ee.Type.STATUS,status:ie.OK,limit:a?.limit},s),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),PI(e.unwrap(),u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let s=await e.newStream(Bl,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),o=Cr(s),i=o.pb(er);await i.write(t,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await s.close(n);return}if(a.status===ie.OK)return this.log("stop request to %p was successful",e.remotePeer),o.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};var Tf=class extends he{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,W(1/0,this.discoveryController.signal),this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(Wr,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,W(1/0,this.discoveryController.signal),this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(Wr)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let o=UI(n),i=UI(s);return o>i?-1:i>o?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new fs({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(s=>s.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p - %e",n.id,s)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,s)})}async dialPeer({peerId:e,signal:t}){let n=Dt([AbortSignal.timeout(5e3),t]);W(1/0,n);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function UI(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(C(e)).getTime()}var z3=class extends he{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??hf,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(xf.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(wf.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);W(1/0,t);let n=e.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let o=await this.reservationStore.addRelay(s.remotePeer,"configured");this.addedRelay(o)}}else throw new Ts(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>H(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function KI(r){return new z3(r)}var $3=Z("node:crypto");var FI="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var uK=128,ao,ta;function hK(r){!ao||ao.length<r?(ao=Buffer.allocUnsafe(r*uK),$3.webcrypto.getRandomValues(ao),ta=0):ta+r>ao.length&&($3.webcrypto.getRandomValues(ao),ta=0),ta+=r}function zI(r=21){hK(r|=0);let e="";for(let t=ta-r;t<ta;t++)e+=FI[ao[t]&63];return e}var dK=60*1e3*10,fK=60*1e3*5,pK=30*1e3,_f=class extends he{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new $t,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??mI,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??hf,this.started=!1,this.relayFilter=Gr(100),this.reserveQueue=new fs({concurrency:t?.reservationConcurrency??pI,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(o=>o.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(o=>{this.log("could not remove relay %p - %e",n.detail,o)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Nl)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[Nl]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=zI();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new Ts("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new bf("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new Ts("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let s=Date.now();try{let o=this.reservations.get(e);if(o!=null){let h=this.connectionManager.getConnections(e),m=!1;if(h.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),h.map(g=>g.id).includes(o.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),m=!0),m&&_3(o.reservation.expire)>dK)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new zl("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);W(1/0,i);let a=await this.connectionManager.openConnection(e,{signal:i});if(zt.matches(a.remoteAddr))throw new yf("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=_3(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-fK,pK),Math.pow(2,31)-1),d=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async h=>{this.log.error("could not refresh reservation to relay %p - %e",e,h),await this.#t(e)}).catch(h=>{this.log.error("could not remove expired reservation to relay %p - %e",e,h)})},u),p;if(t==="discovered"){let h=this.pendingReservations.pop();if(h==null)throw new zl("Made reservation on relay but did not need any more discovered relays");p={timeout:d,reservation:c,type:t,connection:a.id,id:h}}else p={timeout:d,reservation:c,type:t,connection:a.id};this.reservations.set(e,p),await this.peerStore.merge(e,{tags:{[Nl]:{value:1,ttl:l}}}),this.#r();let f={relay:e,details:p};return this.safeDispatchEvent("relay:created-reservation",{detail:f}),f}catch(o){throw t==="discovered"&&o.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-s,o),(o.name==="DialError"||o.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),o}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(Wr,t),o=Cr(n).pb(Ee);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:Ee.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===ie.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=H(l);u.getComponents().find(d=>d.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=H(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>H(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[Nl]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Gr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var H3=class extends Vi{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function q3(r){return new H3(r)}var mK=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(H)}catch{return!1}return!0},$I={maxInboundStopStreams:Ul,maxOutboundStopStreams:Ul,stopTimeout:3e4},Pf=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??$I.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??$I.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new Tf(e,{filter:t.discoveryFilter??U3(wI,xI)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,s)})}),this.reservationStore=new _f(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[je]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Xa](){return this.discovery!=null?["@libp2p/identify"]:[]}[ih]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,W(1/0,this.shutdownController.signal),await this.components.registrar.handle(Bl,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await sh(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await oh(this.discovery,this.reservationStore),await this.components.registrar.unhandle(Bl),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),s=H(n[0]),o=H(n[n.length-1]),i=s.getComponents().find(f=>f.code===421)?.value,a=o.getComponents().find(f=>f.code===421)?.value;if(i==null||a==null){let f=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${f}`),new $n(`C${f}`)}let c=oe(i),l=oe(a),d=this.components.connectionManager.getConnections(c)[0];d==null?(await this.components.peerStore.merge(c,{multiaddrs:[s]}),t.onProgress?.(new Te("circuit-relay:open-connection")),d=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Te("circuit-relay:reuse-connection"));let p;try{t.onProgress?.(new Te("circuit-relay:open-hop-stream")),p=await d.newStream(Wr,t);let f=Cr(p).pb(Ee);t.onProgress?.(new Te("circuit-relay:write-connect-message")),await f.write({type:Ee.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[H(o).bytes]}},t),t.onProgress?.(new Te("circuit-relay:read-connect-response"));let h=await f.read(t);if(h.status!==ie.OK)throw new At(`failed to connect via relay with status ${h?.status?.toString()??"undefined"}`);let m=new $l(h.limit),g=q3({stream:f.unwrap().unwrap(),remoteAddr:e,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:m.onData,onDataWrite:m.onData,log:p.log.newScope("circuit-relay:connection")}),y=await this.components.upgrader.upgradeOutbound(g,{...t,limits:m.getLimits()});return y.log("outbound relayed connection established to %p with limits %o, over connection %s",y.remotePeer,h.limit??"none",d.id),y}catch(f){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,f),p?.abort(f),f}}createListener(e){return KI({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>wf.exactMatch(t)||xf.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>zt.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(d){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",d)}let s=Cr(e).pb(er),o=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:er.Type.STATUS,status:ie.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(o.type!==er.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:er.Type.STATUS,status:ie.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!mK(o)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:er.Type.STATUS,status:ie.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Ur(Xi(o.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:er.Type.STATUS,status:ie.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:er.Type.STATUS,status:ie.OK},{signal:n});let a=new $l(o.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=q3({stream:s.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,o.limit??"none",t.id)}finally{n?.clear()}}};function HI(r={}){return e=>new Cf(e,r)}function qI(r={}){return e=>new Pf(e,r)}async function VI(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new N("Private network is enforced, but no protector was provided");return r}var nge=new Uint8Array(0);function GI(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function gK(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var yK=gK,bK=yK,WI=bK;var V3=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},G3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 jI(this,e)}},W3=class{decoders;constructor(e){this.decoders=e}or(e){return jI(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function jI(r,e){return new W3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var j3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new V3(e,t,n),this.decoder=new G3(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function YI({name:r,prefix:e,encode:t,decode:n}){return new j3(r,e,t,n)}function Y3({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=WI(t,r);return YI({prefix:e,name:r,encode:n,decode:o=>GI(s(o))})}function wK(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function xK(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function vK(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function kt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=vK(n);return YI({prefix:e,name:r,encode(o){return xK(o,n,t)},decode(o){return wK(o,s,t,r)}})}var XI=kt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),uge=kt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hge=kt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),dge=kt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fge=kt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pge=kt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),mge=kt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gge=kt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yge=kt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var QI=Y3({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xge=Y3({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var JI=kt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Sge=kt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ige=kt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Age=kt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ZI=ne(Z("node:tty"),1),kf=ne(Z("node:util"),1);function EK(r,e){if(typeof r=="string")return SK(r);if(typeof r=="number")return CK(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var Df=EK;function SK(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,s=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return s*315576e5;case"months":case"month":case"mo":return s*26298e5;case"weeks":case"week":case"w":return s*6048e5;case"days":case"day":case"d":return s*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return s*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return s*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return s*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function IK(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function AK(r){let e=Math.abs(r);return e>=315576e5?co(r,e,315576e5,"year"):e>=26298e5?co(r,e,26298e5,"month"):e>=6048e5?co(r,e,6048e5,"week"):e>=864e5?co(r,e,864e5,"day"):e>=36e5?co(r,e,36e5,"hour"):e>=6e4?co(r,e,6e4,"minute"):e>=1e3?co(r,e,1e3,"second"):`${r} ms`}function CK(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?AK(r):IK(r)}function co(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}N2();function X3(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=i,t.humanize=Df,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let p=0;p<u.length;p++)d=(d<<5)-d+u.charCodeAt(p),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let p,f=null,h,m;function g(...y){if(!g.enabled)return;let b=g,E=Number(new Date),x=E-(p||E);b.diff=x,b.prev=p,b.curr=E,p=E,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let v=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(w,I)=>{if(w==="%%")return"%";v++;let A=t.formatters[I];if(typeof A=="function"){let G=y[v];w=A.call(b,G),y.splice(v,1),v--}return w}),t.formatArgs.call(b,y),d?.onLog!=null&&d.onLog(...y),(b.log||t.log).apply(b,y)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==t.namespaces&&(h=t.namespaces,m=t.enabled(u)),m),set:y=>{f=y}}),typeof t.init=="function"&&t.init(g),g}function n(u,d){let p=t(this.namespace+(typeof d>"u"?":":d)+u);return p.log=this.log,p}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,p=(typeof u=="string"?u:"").split(/[\s,]+/),f=p.length;for(d=0;d<f;d++)p[d]&&(u=p[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let d,p;for(d=0,p=t.skips.length;d<p;d++)if(t.skips[d].test(u))return!1;for(d=0,p=t.names.length;d<p;d++)if(t.names[d].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var eA=[6,2,3,4,5,1];zc.stderr!==!1&&(zc.stderr??zc).level>=2&&(eA=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]);var ra=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,o)=>o.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function TK(){return"colors"in ra?!!ra.colors:ZI.default.isatty(process.stderr.fd)}function _K(r){let{namespace:e,useColors:t}=this;if(t===!0){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),o=` ${s};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
7
7
  `).join(`
8
- `+o),r.push(s+"m+"+lp(this.diff)+"\x1B[0m")}else r[0]=e$()+e+" "+r[0]}function e$(){return Ea.hideDate!=null?"":new Date().toISOString()+" "}function t$(...r){return process.stderr.write(up.default.format(...r)+`
9
- `)}function r$(r){r!=null?process.env.DEBUG=r:delete process.env.DEBUG}function n$(){return process.env.DEBUG}function s$(r){r.inspectOpts={};let e=Object.keys(Ea);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=Ea[e[t]]}function o$(r){r.o=function(e){return this.inspectOpts.colors=this.useColors,up.default.inspect(e,this.inspectOpts).split(`
10
- `).map(t=>t.trim()).join(" ")},r.O=function(e){return this.inspectOpts.colors=this.useColors,up.default.inspect(e,this.inspectOpts)}}var _C=ow({init:s$,log:t$,formatArgs:Zz,save:r$,load:n$,useColors:Jz,setupFormatters:o$,colors:TC,inspectOpts:Ea});var er=_C;er.formatters.b=r=>r==null?"undefined":IC.baseEncode(r);er.formatters.t=r=>r==null?"undefined":SC.baseEncode(r);er.formatters.m=r=>r==null?"undefined":AC.baseEncode(r);er.formatters.p=r=>r==null?"undefined":r.toString();er.formatters.c=r=>r==null?"undefined":r.toString();er.formatters.k=r=>r==null?"undefined":r.toString();er.formatters.a=r=>r==null?"undefined":r.toString();function PC(r,e=""){let t=DC(r.message),n=DC(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
8
+ `+o),r.push(s+"m+"+Df(this.diff)+"\x1B[0m")}else r[0]=PK()+e+" "+r[0]}function PK(){return ra.hideDate!=null?"":new Date().toISOString()+" "}function DK(...r){return process.stderr.write(kf.default.format(...r)+`
9
+ `)}function kK(r){r!=null?process.env.DEBUG=r:delete process.env.DEBUG}function LK(){return process.env.DEBUG}function MK(r){r.inspectOpts={};let e=Object.keys(ra);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=ra[e[t]]}function OK(r){r.o=function(e){return this.inspectOpts.colors=this.useColors,kf.default.inspect(e,this.inspectOpts).split(`
10
+ `).map(t=>t.trim()).join(" ")},r.O=function(e){return this.inspectOpts.colors=this.useColors,kf.default.inspect(e,this.inspectOpts)}}var tA=X3({init:MK,log:DK,formatArgs:_K,save:kK,load:LK,useColors:TK,setupFormatters:OK,colors:eA,inspectOpts:ra});var Ht=tA;Ht.formatters.b=r=>r==null?"undefined":QI.baseEncode(r);Ht.formatters.t=r=>r==null?"undefined":XI.baseEncode(r);Ht.formatters.m=r=>r==null?"undefined":JI.baseEncode(r);Ht.formatters.p=r=>r==null?"undefined":r.toString();Ht.formatters.c=r=>r==null?"undefined":r.toString();Ht.formatters.k=r=>r==null?"undefined":r.toString();Ht.formatters.a=r=>r==null?"undefined":r.toString();function rA(r,e=""){let t=nA(r.message),n=nA(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
11
11
  `).join(`
12
12
  ${e}`)}`:`${t}
13
13
  ${e}${n.split(`
14
14
  `).join(`
15
15
  ${e}`)}`:n!=null?`${n.split(`
16
16
  `).join(`
17
- ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function i$(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function kC(r,e=""){if(i$(r)){let t=PC(r,e);return r.errors.length>0?(e=`${e} `,t+=`
18
- ${e}${r.errors.map(n=>`${kC(n,`${e}`)}`).join(`
17
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function RK(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function sA(r,e=""){if(RK(r)){let t=rA(r,e);return r.errors.length>0?(e=`${e} `,t+=`
18
+ ${e}${r.errors.map(n=>`${sA(n,`${e}`)}`).join(`
19
19
  ${e}`)}`):t+=`
20
- ${e}[Error list was empty]`,t.trim()}return PC(r,e)}er.formatters.e=r=>r==null?"undefined":kC(r);function a$(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function hp(r){return{forComponent(e){return LC(e,r)}}}function LC(r,e){let t=a$(`${r}:trace`);return er.enabled(`${r}:trace`)&&er.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=er(`${r}:trace`,e)),Object.assign(er(r,e),{error:er(`${r}:error`,e),trace:t,newScope:n=>LC(`${r}:${n}`,e)})}function DC(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}ke();V();ke();function c$(r){return r[Symbol.asyncIterator]!=null}function l$(r){if(c$(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var yu=l$;V();ke();var dr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};Ue();async function dp(r,e,t,n){let s=new dr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){aw(t,"abort",d),aw(r,e,l),aw(r,o,u)}let l=p=>{try{if(n?.filter?.(p)===!1)return}catch(f){c(),a(f);return}c(),i(p)},u=p=>{if(c(),p instanceof Error){a(p);return}a(p.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{c(),a(s)};iw(t,"abort",d),iw(r,e,l),iw(r,o,u)})}function iw(r,e,t){r!=null&&(MC(r)?r.addEventListener(e,t):r.addListener(e,t))}function aw(r,e,t){r!=null&&(MC(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function MC(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var fp=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};Ue();var pp=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new dr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function u$(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var mp=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=u$(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,Y(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new dr),this.cleanup())}async join(e={}){let t=new pp(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await uh(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function cw(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var bu=class extends me{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=cw(this.emitEmpty.bind(this),1),this.emitIdle=cw(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new fp;let n=new mp(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new dr)}),this.clear()}async onEmpty(e){this.size!==0&&await dp(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await dp(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await dp(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ot({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new dr("Queue aborted"))};this.addEventListener("success",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var xu=ae(te("node:cluster"),1),wp=ae(te("node:worker_threads"),1);Ue();var To="lock:worker:request-read",_o="lock:worker:abort-read-request",Po="lock:worker:release-read",Do="lock:master:grant-read",ko="lock:master:error-read",Lo="lock:worker:request-write",Mo="lock:worker:abort-write-request",Oo="lock:worker:release-write",Ro="lock:master:grant-write",No="lock:master:error-write",Ds="lock:worker:finalize",gp="mortice",OC={singleProcess:!1};var lw=(r,e,t,n,s,o,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(d=>{let p=f=>{if(f?.data==null)return;let h={type:f.data.type,name:f.data.name,identifier:f.data.identifier};h.type===a&&h.identifier===u.identifier&&(e.removeEventListener("message",p),d())};e.addEventListener("message",p)})},onError:d=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:d.message,name:d.name,stack:d.stack}})}}}),u.type===o&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Ds&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var uw=(r,e,t,n,s,o,i,a)=>(c,l)=>{l!=null&&(l.type===n&&r.safeDispatchEvent(e,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{c.send({type:a,name:l.name,identifier:l.identifier}),await new Promise(u=>{let d=p=>{p.type===i&&p.identifier===l.identifier&&(c.removeListener("message",d),u())};c.on("message",d)})},onError:u=>{c.send({type:o,name:l.name,identifier:l.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),l.type===s&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier}}),l.type===Ds&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}}))};var wu=(r=10)=>Math.random().toString().substring(2,r+2);var yp=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(gp)}readLock(e){return this.sendRequest(To,_o,Do,ko,Po,e)}writeLock(e){return this.sendRequest(Lo,Mo,Ro,No,Oo,e)}finalize(){this.channel.postMessage({type:Ds,name:this.name}),this.channel.close()}async sendRequest(e,t,n,s,o,i){i?.signal?.throwIfAborted();let a=wu();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let d=p=>{if(p.data?.identifier===a&&(p.data?.type===n&&(this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),p.data.type===s)){this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u);let f=new Error;p.data.error!=null&&(f.message=p.data.error.message,f.name=p.data.error.name,f.stack=p.data.error.stack),l(f)}};this.channel.addEventListener("message",d)})}};var bp=class{name;constructor(e){this.name=e}readLock(e){return this.sendRequest(To,_o,Do,ko,Po,e)}writeLock(e){return this.sendRequest(Lo,Mo,Ro,No,Oo,e)}finalize(){if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");process.send({type:Ds,identifier:wu(),name:this.name})}async sendRequest(e,t,n,s,o,i){i?.signal?.throwIfAborted();let a=wu();if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");return process.send({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{process.send?.({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let d=p=>{if(p.identifier===a&&(p.type===n&&(process.removeListener("message",d),i?.signal?.removeEventListener("abort",u),c(()=>{process.send?.({type:o,identifier:a,name:this.name})})),p.type===s)){process.removeListener("message",d),i?.signal?.removeEventListener("abort",u);let f=new Error;p.error!=null&&(f.message=p.error.message,f.name=p.error.name,f.stack=p.error.stack),l(f)}};process.on("message",d)})}};function h$(){return wp.default.isMainThread===!1||wp.default.isInternalThread===!0?!1:xu.default.isPrimary}var RC=r=>{if(r=Object.assign({},OC,r),h$()||r.singleProcess){let e=new me;xu.default.on("message",uw(e,"requestReadLock","abortReadLockRequest",To,_o,ko,Po,Do)),xu.default.on("message",uw(e,"requestWriteLock","abortWriteLockRequest",Lo,Mo,No,Oo,Ro));let t=new BroadcastChannel(gp);return t.addEventListener("message",lw(e,t,"requestReadLock","abortReadLockRequest",To,_o,ko,Po,Do)),t.addEventListener("message",lw(e,t,"requestWriteLock","abortWriteLockRequest",Lo,Mo,No,Oo,Ro)),t.unref?.(),e}if(xu.default.isWorker)return new bp(r.name);if(wp.default.isMainThread===!1)return new yp(r.name);throw new Error("Not a cluster worker or worker thread")};var Bo=new Map,vu;function NC(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function d$(r){if(vu==null&&(vu=RC(r),!NC(vu))){let e=vu;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=Bo.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=Bo.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,s=Bo.get(n);s?.finalize()})}return vu}async function hw(r,e){let t,n,s=new Promise((i,a)=>{t=i,n=a}),o=()=>{n(new dr)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",o),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),s}var BC=(r,e)=>{let t=Bo.get(r);if(t!=null)return t;let n=d$(e);if(NC(n))return t=n,Bo.set(r,t),t;let s=new bu({concurrency:1}),o;return t={async readLock(i){if(o!=null)return hw(o,i);o=new bu({concurrency:e.concurrency,autoStart:!1});let a=o,c=hw(o,i);return s.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(i){return o=null,hw(s,i)},finalize:()=>{Bo.delete(r)},queue:s},Bo.set(r,t),e.autoFinalize===!0&&s.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var f$={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function dw(r){let e=Object.assign({},f$,r);return BC(e.name,e)}var awe=new Uint8Array(0);function UC(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Sa(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function p$(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var m$=p$,g$=m$,KC=g$;var fw=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},pw=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 FC(this,e)}},mw=class{decoders;constructor(e){this.decoders=e}or(e){return FC(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function FC(r,e){return new mw({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gw=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new fw(e,t,n),this.decoder=new pw(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function zC({name:r,prefix:e,encode:t,decode:n}){return new gw(r,e,t,n)}function Ia({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=KC(t,r);return zC({prefix:e,name:r,encode:n,decode:o=>Sa(s(o))})}function y$(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function b$(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function w$(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function dn({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=w$(n);return zC({prefix:e,name:r,encode(o){return b$(o,n,t)},decode(o){return y$(o,s,t,r)}})}var Uo=dn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),pwe=dn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),mwe=dn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),gwe=dn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ywe=dn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),bwe=dn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wwe=dn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),xwe=dn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),vwe=dn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xp=Ia({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Iwe=Ia({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var qn=Ia({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Twe=Ia({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var x$=qC,$C=128,v$=127,E$=~v$,S$=Math.pow(2,31);function qC(r,e,t){e=e||[],t=t||0;for(var n=t;r>=S$;)e[t++]=r&255|$C,r/=128;for(;r&E$;)e[t++]=r&255|$C,r>>>=7;return e[t]=r|0,qC.bytes=t-n+1,e}var I$=yw,A$=128,HC=127;function yw(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw yw.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&HC)<<s:(i&HC)*Math.pow(2,s),s+=7}while(i>=A$);return yw.bytes=o-n,t}var C$=Math.pow(2,7),T$=Math.pow(2,14),_$=Math.pow(2,21),P$=Math.pow(2,28),D$=Math.pow(2,35),k$=Math.pow(2,42),L$=Math.pow(2,49),M$=Math.pow(2,56),O$=Math.pow(2,63),R$=function(r){return r<C$?1:r<T$?2:r<_$?3:r<P$?4:r<D$?5:r<k$?6:r<L$?7:r<M$?8:r<O$?9:10},N$={encode:x$,decode:I$,encodingLength:R$},B$=N$,Eu=B$;function Su(r,e=0){return[Eu.decode(r,e),Eu.decode.bytes]}function Aa(r,e,t=0){return Eu.encode(r,e,t),e}function Ca(r){return Eu.encodingLength(r)}function GC(r,e){let t=e.byteLength,n=Ca(r),s=n+Ca(t),o=new Uint8Array(s+t);return Aa(r,o,0),Aa(t,o,n),o.set(e,s),new Ta(r,t,e,o)}function WC(r){let e=Sa(r),[t,n]=Su(e),[s,o]=Su(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Ta(t,s,i,e)}function jC(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&UC(r.bytes,t.bytes)}}var Ta=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function YC(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return F$(t,bw(r),e??qn.encoder);default:return z$(t,bw(r),e??Uo.encoder)}}var XC=new WeakMap;function bw(r){let e=XC.get(r);if(e==null){let t=new Map;return XC.set(r,t),t}return e}var vp=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Iu)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==$$)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=GC(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&jC(e.multihash,n.multihash)}toString(e){return YC(this,e)}toJSON(){return{"/":YC(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??QC(n,s,o.bytes))}else if(t[H$]===!0){let{version:n,multihash:s,code:o}=t,i=WC(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Iu)throw new Error(`Version 0 CID must use dag-pb (code: ${Iu}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=QC(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Iu,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Sa(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Ta(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=Su(e.subarray(t));return t+=p,d},s=n(),o=Iu;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=K$(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return bw(o).set(n,e),o}};function K$(r,e){switch(r[0]){case"Q":{let t=e??qn;return[qn.prefix,t.decode(`${qn.prefix}${r}`)]}case qn.prefix:{let t=e??qn;return[qn.prefix,t.decode(r)]}case Uo.prefix:{let t=e??Uo;return[Uo.prefix,t.decode(r)]}case xp.prefix:{let t=e??xp;return[xp.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function F$(r,e,t){let{prefix:n}=t;if(n!==qn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function z$(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Iu=112,$$=18;function QC(r,e,t){let n=Ca(r),s=n+Ca(e),o=new Uint8Array(s+t.byteLength);return Aa(r,o,0),Aa(e,o,n),o.set(t,s),o}var H$=Symbol.for("@ipld/js-cid/CID");wr();rt();var Vn;(function(r){let e;(function(s){let o;s.codec=()=>(o==null&&(o=Z((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ce(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(d&7);break}}}return l})),o),s.encode=i=>J(i,s.codec()),s.decode=(i,a)=>Q(i,s.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(s){let o;s.codec=()=>(o==null&&(o=Z((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Sp.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Sp.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(d&7);break}}}return l})),o),s.encode=i=>J(i,s.codec()),s.decode=(i,a)=>Q(i,s.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Z((s,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),s.addresses!=null)for(let a of s.addresses)o.uint32(10),Ep.codec().encode(a,o);if(s.protocols!=null)for(let a of s.protocols)o.uint32(18),o.string(a);if(s.publicKey!=null&&(o.uint32(34),o.bytes(s.publicKey)),s.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(s.peerRecordEnvelope)),s.metadata!=null&&s.metadata.size!==0)for(let[a,c]of s.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(s.tags!=null&&s.tags.size!==0)for(let[a,c]of s.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);s.updated!=null&&(o.uint32(64),o.uint64Number(s.updated)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new _e('Decode error - map field "addresses" had too many elements');a.addresses.push(Ep.codec().decode(s,s.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new _e('Decode error - map field "protocols" had too many elements');a.protocols.push(s.string());break}case 4:{a.publicKey=s.bytes();break}case 5:{a.peerRecordEnvelope=s.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Bc('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(s,s.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Bc('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(s,s.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=s.uint64Number();break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>J(s,r.codec()),r.decode=(s,o)=>Q(s,r.codec(),o)})(Vn||(Vn={}));var Ep;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={multiaddr:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}case 3:{o.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Ep||(Ep={}));var Sp;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Sp||(Sp={}));Bt();ke();function q$(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Ft(e.publicKey,t);return On(n)}function JC(r,e,t){let n=Vn.decode(e);return _a(r,n,t)}function _a(r,e,t){let n=new Map,s=BigInt(Date.now());for(let[o,i]of e.tags.entries())i.expiry!=null&&i.expiry<s||n.set(o,i);return{...e,id:q$(r,e),addresses:e.addresses.filter(({observed:o})=>o!=null&&o>Date.now()-t).map(({multiaddr:o,isCertified:i})=>({multiaddr:q(o),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}Ne();function ZC(r,e){return V$(r.addresses,e.addresses)&&G$(r.protocols,e.protocols)&&W$(r.publicKey,e.publicKey)&&j$(r.peerRecordEnvelope,e.peerRecordEnvelope)&&Y$(r.metadata,e.metadata)&&X$(r.tags,e.tags)}function V$(r,e){return tT(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!W(t.multiaddr,n.multiaddr)))}function G$(r,e){return tT(r,e,(t,n)=>t===n)}function W$(r,e){return eT(r,e)}function j$(r,e){return eT(r,e)}function Y$(r,e){return rT(r,e,(t,n)=>W(t,n))}function X$(r,e){return rT(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function eT(r,e){return r==null&&e==null?!0:r!=null&&e!=null?W(r,e):!1}function tT(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function rT(r,e,t){if(r.size!==e.size)return!1;for(let[n,s]of r.entries()){let o=e.get(n);if(o==null||!t(s,o))return!1}return!0}V();re();ie();var Gn="/",nT=new TextEncoder().encode(Gn),Ip=nT[0],Ko=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Ip)throw new Error("Invalid key")}toString(e="utf8"){return T(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Gn))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=nT),this._buf[0]!==Ip){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ip,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ip;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let s=0;s<t.length;s++){if(n.length<s+1)return!1;let o=t[s],i=n[s];if(o<i)return!0;if(o>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Gn).slice(1)}type(){return Q$(this.baseNamespace())}name(){return J$(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Gn)||(e+=Gn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Gn):new r(e.slice(0,-1).join(Gn))}child(e){return this.toString()===Gn?e:e.toString()===Gn?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Z$(e.map(t=>t.namespaces()))])}};function Q$(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function J$(r){let e=r.split(":");return e[e.length-1]}function Z$(r){return[].concat(...r)}var ww="/peers/";function Au(r){if(!cs(r)||r.type==null)throw new B("Invalid PeerId");let e=r.toCID().toString();return new Ko(`${ww}${e}`)}Bt();V();Ne();V();async function sT(r,e,t,n,s){let o=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=q(i.multiaddr)),!As(i.multiaddr))throw new B("Multiaddr was invalid");if(!await e(r,i.multiaddr,s))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=o.get(c);l!=null?i.isCertified=l.isCertified||a:o.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...o.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(q(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Cp(r,e,t,n){if(e==null)throw new B("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new B("publicKey bytes do not match peer id publicKey bytes");let s=n.existingPeer?.peer;if(s!=null&&!r.equals(s.id))throw new B("peer id did not match existing peer id");let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(p=>({isCertified:!1,multiaddr:p}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let p=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Ap(p,{validate:oT})}if(e.tags!=null){let p=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Ap(p,{validate:iT,map:aT})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(p=>({isCertified:!1,multiaddr:p}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let p=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,h]of p)h==null?a.delete(f):a.set(f,h);a=Ap([...a.entries()],{validate:oT})}if(e.tags!=null){let p=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[h,m]of p)m==null?f.delete(h):f.set(h,m);c=Ap([...f.entries()],{validate:iT,map:aT})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;s?.id.publicKey!=null?u=dt(s.id.publicKey):e.publicKey!=null?u=dt(e.publicKey):r.publicKey!=null&&(u=dt(r.publicKey));let d={addresses:await sT(r,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((p,f)=>p.localeCompare(f)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return d.addresses.forEach(p=>{p.observed=n.existingPeer?.peerPB.addresses?.find(f=>W(f.multiaddr,f.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete d.publicKey,d}function Ap(r,e){let t=new Map;for(let[n,s]of r)s!=null&&e.validate(n,s);for(let[n,s]of r.sort(([o],[i])=>o.localeCompare(i)))s!=null&&t.set(n,e.map?.(n,s)??s);return t}function oT(r,e){if(typeof r!="string")throw new B("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new B("Metadata value must be a Uint8Array")}function iT(r,e){if(typeof r!="string")throw new B("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new B("Tag value must be an integer");if(e.value<0||e.value>100)throw new B("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new B("Tag ttl must be an integer");if(e.ttl<0)throw new B("Tag ttl must be between greater than 0")}}function aT(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function cT(r){let e=r.toString().split("/")[2],t=vp.parse(e,Uo);return en(t)}function xw(r,e,t){let n=cT(r);return JC(n,e,t)}function eH(r,e){return{prefix:ww,filters:(r.filters??[]).map(t=>({key:n,value:s})=>t(xw(n,s,e))),orders:(r.orders??[]).map(t=>(n,s)=>t(xw(n.key,n.value,e),xw(s.key,s.value,e)))}}var Tp=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=gu({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:dw({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let s=await n.lock.readLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async getWriteLock(e,t){let n=this.getLock(e);try{let s=await n.lock.writeLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Au(e),t)}async load(e,t){let n=Au(e),s=await this.datastore.get(n,t),o=Vn.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new $s;return _a(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let s=await this.#e(e,n),o=await Cp(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,o,s)}async patch(e,t,n){let s=await this.#e(e,n),o=await Cp(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async merge(e,t,n){let s=await this.#e(e,n),o=await Cp(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(eH(e??{},this.maxAddressAge),e)){let s=cT(t);if(s.equals(this.peerId))continue;let o=Vn.decode(n);if(this.#r(s,o)){await this.datastore.delete(t,e);continue}yield _a(s,o,this.peerId.equals(s)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Au(e),s=await this.datastore.get(n,t),o=Vn.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new $s;return{peerPB:o,peer:_a(e,o,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,s){t.updated=Date.now();let o=Vn.encode(t);return await this.datastore.put(Au(e),o,s),{peer:_a(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!ZC(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,s=Date.now()-this.maxAddressAge,o=t.addresses.filter(i=>i.observed!=null&&i.observed>s);return n&&o.length===0}};var vw=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Tp(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return yu(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:s})=>s)}}async save(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.save(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async patch(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.patch(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async merge(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.merge(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async consumePeerRecord(e,t,n){let s=cs(t)?t:cs(t?.expectedPeer)?t.expectedPeer:void 0,o=cs(t)||t===void 0?n:t,i=await lr.openAndCertify(e,ur.DOMAIN,o),a=en(i.publicKey.toCID());if(s?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",s,a),!1;let c=ur.createFromProtobuf(i.payload),l;try{l=await this.get(a,o)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=lr.createFromProtobuf(l.peerRecordEnvelope),d=ur.createFromProtobuf(u.payload);if(d.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},o),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function lT(r,e={}){return new vw(r,e)}var _p=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function tH(r){return r[Symbol.asyncIterator]!=null}function rH(r){if(tH(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ew=rH;function nH(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var uT=nH;function sH(r){return r[Symbol.asyncIterator]!=null}function oH(r,e){let t=0;if(sH(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=uT(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var Fo=oH;function iH(r){return r[Symbol.asyncIterator]!=null}function aH(r,e){return iH(r)?(async function*(){yield*(await yu(r)).sort(e)})():(function*(){yield*yu(r).sort(e)})()}var Sw=aH;function cH(r){return r[Symbol.asyncIterator]!=null}function lH(r,e){return cH(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Iw=lH;var Pp=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:s}of e)await this.put(n,s,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,s){e.push({key:n,value:s})},delete(n){t.push(n)},commit:async n=>{await Ew(this.putMany(e,n)),e=[],await Ew(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let s=e.prefix;n=Fo(n,o=>o.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Fo(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>Sw(s,o),n)),e.offset!=null){let s=0,o=e.offset;n=Fo(n,()=>s++>=o)}return e.limit!=null&&(n=Iw(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let s=e.prefix;n=Fo(n,o=>o.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Fo(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>Sw(s,o),n)),e.offset!=null){let s=e.offset,o=0;n=Fo(n,()=>o++>=s)}return e.limit!=null&&(n=Iw(n,e.limit)),n}};var Dp=class extends Pp{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new _p;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,s]of this.data.entries())yield{key:new Ko(n),value:s},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Ko(n),t?.signal?.throwIfAborted()}};Ue();bt();re();ke();var hT=864e13;var kp=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Dt({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=oe(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let s of this.mappings.values())if(s.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let s=la(n)===!0;this.mappings.set(n,{domain:e,verified:s,expires:s?hT-Date.now():0,lastVerified:s?hT-Date.now():void 0})})}remove(e){let t=oe(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries())o.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",s,o.domain),this.mappings.delete(s),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n].multiaddr;if(!St(s))continue;let o=oe(s);for(let[i,a]of this.mappings.entries()){if(o.host!==i)continue;let c=this.maybeAddSNIComponent(s,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let s=0;s<n.length;s++)if(n[s].code===448&&n[s+1]?.code!==449)return n.splice(s+1,0,{name:"sni",code:449,value:t}),q(n)}confirm(e,t){let n=oe(e),s=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(s=n.sni);let o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=oe(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let s=n.sni??n.host,o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t);return o}};var Lp=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Dt({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=oe(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let s of n)if(s.externalIp===t.host)return!0;return!1}add(e,t,n,s=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:s,externalFamily:(0,fe.isIPv4)(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=oe(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries()){for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,o.splice(i,1),i--)}o.length===0&&this.mappings.delete(s)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!St(n))continue;let s=oe(n);if(s.type!=="ip4"&&s.type!=="ip6")continue;let o;if(s.protocol==="tcp"?o=`${s.host}-${s.port}-tcp`:s.protocol==="udp"&&(o=`${s.host}-${s.port}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,s,o){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===s);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${o}`,q(i)):e}confirm(e,t){if(!St(e))return!1;let n=oe(e),s=!1;for(let o of this.mappings.values())for(let i of o)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),s=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return s}unconfirm(e,t){if(!St(e))return!1;let n=oe(e),s=!1;for(let o of this.mappings.values())for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t)}return s}};var uH={maxObservedAddresses:10},Mp=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Dt({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??uH.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(zn(e)||i8(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:q(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),s=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,s),o}};var hH={maxObservedAddresses:10},Op=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Dt({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??hH.maxObservedAddresses}get(e,t){if(zn(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),s=this.addresses.get(n);return s==null&&(s={verified:!St(e),expires:0},this.addresses.set(n,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.addresses.set(n,s),o}unconfirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0},o=s.verified;return s.verified=!1,s.expires=Date.now()+t,this.addresses.set(n,s),o}toKey(e){if(!St(e))return e.toString();let t=oe(e);return`${t.host}-${t.port}-${t.protocol}`}};var dT=6e4,fT={maxObservedAddresses:10,addressVerificationTTL:dT*10,addressVerificationRetry:dT*5},dH=r=>r;function Aw(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&de(t).equals(e)&&(r=r.decapsulate(q(`/p2p/${e.toString()}`))),r}var Rp=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:s=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(s.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new Mp(e,t),this.dnsMappings=new kp(e,t),this.ipMappings=new Lp(e,t),this.transportAddresses=new Op(e,t),this.announceFilter=t.announceFilter??dH,this.observedAddressFilter=ln(1024),this.addressVerificationTTL=t.addressVerificationTTL??fT.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??fT.addressVerificationRetry,this._updatePeerStoreAddresses=vo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>q(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>q(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>q(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=oe(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Aw(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Aw(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Aw(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let s=n.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let s=q(n);return s.getComponents().pop()?.value===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(e)}),e.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(s=>this.transportAddresses.get(s,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(n)}),t=t.concat(n.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(q(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.add(e,t,n,s,o),this.observed.removePrefixed(`/ip${(0,fe.isIPv4)(n)?4:6}/${n}/${o}/${s}`)}removePublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.remove(q(`/ip${(0,fe.isIPv4)(n)?4:6}/${n}/${o}/${s}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!St(e))return!1;let t=oe(e);if(t.type!=="ip4"||la(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),s=[o=>Jl.exactMatch(o)||Zl.exactMatch(o),o=>Fn.exactMatch(o),o=>QA.exactMatch(o)];for(let o of s){if(!o(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>oe(u).type==="ip4"&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!ru(l)).pop();if(a==null)continue;let c=oe(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};V();var pT;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(pT||(pT={}));var Np=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Bp=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Pa=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Cu=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Up=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Kp=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Fp=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Tu=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},zp=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},$p=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},Hp=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},qp=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Vp=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},ks=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},zo=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Gp=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Wp=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Cw=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=hp())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Dh(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},fH=["metrics","connectionProtector","dns"],pH=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mT(r={}){let e=new Cw(r);return new Proxy(e,{get(n,s,o){if(typeof s=="string"&&!pH.includes(s)){let i=e.components[s];if(i==null&&!fH.includes(s))throw new Np(`${s} not set`);return i}return Reflect.get(n,s,o)},set(n,s,o){return typeof s=="string"?e.components[s]=o:Reflect.set(n,s,o),!0}})}function gT(r){let e={};for(let t of Object.values(r.components))for(let n of mH(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of gH(t))if(e[n]!==!0)throw new Bp(`Service "${yH(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function mH(r){return Array.isArray(r?.[nt])?r[nt]:[]}function gH(r){return Array.isArray(r?.[yc])?r[yc]:[]}function yH(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function yT(r={}){return r}V();V();ke();function jp(r){if(cs(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(s=>s.code===421)?.value;t=n==null?void 0:de(n),e.forEach(s=>{if(!As(s))throw new ss("Invalid multiaddr");let o=s.getComponents().findLast(i=>i.code===421)?.value;if(o==null){if(t!=null)throw new B("Multiaddrs must all have the same peer id or have no peer id")}else{let i=de(o);if(t?.equals(i)!==!0)throw new B("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!WA.exactMatch(n)),{peerId:t,multiaddrs:e}}V();var bH=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function bT(r,e){let t=r?.streams?.map(s=>s.protocol)??[],n=e?.closableProtocols??bH;if(!(t.filter(s=>s!=null&&!n.includes(s)).length>0))try{await r?.close(e)}catch(s){r?.abort(s)}}function _u(r){let e=oe(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new B(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new B(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Bn(e.host,t)}function Tw(r){return!Jt.exactMatch(r)}function Yp(r,e,t){if(r==null||e==null)return;let n=e.sort((o,i)=>o.direct?-1:i.direct?1:0).find(o=>o.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(o=>Tw(o)))return n}var Xp=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>_u(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let s=new Zt;for(let c of e){let l=c.remotePeer;if(!s.has(l)){s.set(l,0);try{let u=await this.peerStore.get(l);s.set(l,[...u.tags.values()].reduce((d,p)=>d+p.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let o=this.sortConnections(e,s),i=Math.max(t-n,0),a=[];for(let c of o)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(St(c.remoteAddr)){let d=oe(c.remoteAddr);return u.contains(d.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await bT(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,s)=>{let o=n.timeline.open,i=s.timeline.open;return o<i?1:o>i?-1:0}).sort((n,s)=>n.direction==="outbound"&&s.direction==="inbound"?1:n.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((n,s)=>n.streams.length>s.streams.length?1:n.streams.length<s.streams.length?-1:0).sort((n,s)=>{let o=t.get(n.remotePeer)??0,i=t.get(s.remotePeer)??0;return o>i?1:o<i?-1:0})}};var wT="last-dial-failure",xT="last-dial-success";var vT=300,Qp=100;V();Ue();re();function wH(r,e){let t=Fn.exactMatch(r.multiaddr),n=Fn.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let s=Zl.exactMatch(r.multiaddr),o=Zl.exactMatch(e.multiaddr);if(s&&!o)return-1;if(!s&&o)return 1;let i=Jl.exactMatch(r.multiaddr),a=Jl.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=ob.exactMatch(r.multiaddr),l=ob.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=nb.exactMatch(r.multiaddr),d=nb.exactMatch(e.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;let p=sb.exactMatch(r.multiaddr),f=sb.exactMatch(e.multiaddr);return p&&!f?-1:!p&&f?1:0}function xH(r,e){let t=ru(r.multiaddr),n=ru(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function vH(r,e){let t=zn(r.multiaddr),n=zn(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function EH(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function SH(r,e){let t=Jt.exactMatch(r.multiaddr),n=Jt.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function ET(r){return r.sort(wH).sort(EH).sort(SH).sort(vH).sort(xH)}var IT=te("dns/promises");function Jp(r){let e=[kt.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}ie();var _w=60;function Zp(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:kt[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:kt[e.type],TTL:e.TTL??e.ttl??_w,data:e.data instanceof Uint8Array?T(e.data):e.data}))}}var IH=async(r,e={})=>{let t=new IT.Resolver,n=()=>{t.cancel()},s=Jp(e.types);try{e.signal?.addEventListener("abort",n);let o=await Promise.all(s.map(async i=>{if(i===kt.A)return e1(r,i,await t.resolve4(r));if(i===kt.CNAME)return e1(r,i,await t.resolveCname(r));if(i===kt.TXT)return e1(r,i,await t.resolveTxt(r));if(i===kt.AAAA)return e1(r,i,await t.resolve6(r));throw new TypeError("Unsupported DNS record type")}));return Zp({Question:s.map(i=>({name:r,type:i})),Answer:o.flat()})}finally{e.signal?.removeEventListener("abort",n)}};function AT(){return[IH]}function ST(r,e,t){return{name:r,type:e,data:t}}function e1(r,e,t){return Array.isArray(t)||(t=[t]),t.map(n=>Array.isArray(n)?n.map(s=>ST(r,e,s)):ST(r,e,n)).flat()}var _T=ae(TT(),1);var Pw=class{lru;constructor(e){this.lru=(0,_T.default)(e)}get(e,t){let n=!0,s=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){n=!1;break}s.push(...i)}if(n)return Zp({answers:s})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,s=this.lru.get(n);if(s!=null){let o=s.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:kt[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,s=this.lru.get(n)??[];s.push({expires:Date.now()+(t.TTL??_w)*1e3,value:t}),this.lru.set(n,s)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function PT(r){return new Pw(r)}var AH=1e3,t1=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=PT(e.cacheSize??AH),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=AT())}async query(e,t={}){let n=Jp(t.types),s=t.cached!==!1?this.cache.get(e,n):void 0;if(s!=null)return t.onProgress?.(new Le("dns:cache",s)),s;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new Le("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var kt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(kt||(kt={}));function DT(r={}){return new t1(r)}var Dw=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let o=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[kt.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of o.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(q(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=DT()),this.dns)}},Pu=new Dw;async function kw(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Wp("Max recursive depth reached");let s=!1,o=[];for(let i of Object.values(e))if(i.canResolve(r)){s=!0;let a=await i.resolve(r,t);for(let c of a)o.push(...await kw(c,e,{...t,depth:n+1}))}return s===!1&&o.push(r),o}var Du={maxParallelDials:Qp,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Pu}},r1=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Du.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Du.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Du.dialTimeout,this.connections=t.connections??new Zt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Du.resolvers,this.shutDownController=new AbortController,Y(1/0,this.shutDownController.signal),this.queue=new Rf({concurrency:t.maxParallelDials??Du.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==rr.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,Y(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:s}=jp(e);if(n!=null&&t.force!==!0){let i=Yp(n,this.connections.get(n),s);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new Le("dial-queue:already-connected")),i}let o=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of s)if(a.has(c.toString()))return!0;return!1});if(o!=null){this.log("joining existing dial target for %p",n);for(let i of s)o.options.multiaddrs.add(i.toString());return t.onProgress?.(new Le("dial-queue:already-in-dial-queue")),o.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new os("Dial queue is full");return this.log("creating dial target for %p",n,s.map(i=>i.toString())),t.onProgress?.(new Le("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new Le("dial-queue:start-dial"));let a=zt([this.shutDownController.signal,i.signal]);Y(1/0,a);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Rw,multiaddrs:new Set(s.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,s=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||s.size>0;){c++,i=!1;let u=[],d=new Set(e.multiaddrs);s.clear(),this.log("calculating addrs to dial %p from %s",n,[...d]);let p=await this.calculateMultiaddrs(n,d,{...e,signal:t});for(let f of p){if(o.has(f.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",f.multiaddr,n);continue}u.push(f)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(f=>f.multiaddr.toString())),e?.onProgress?.(new Le("dial-queue:calculated-addresses",u));for(let f of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new os("Peer had more than maxPeerAddrsToDial");a++;try{let h=await this.components.transportManager.dial(f.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",f.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[xT]:D(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}return h}catch(h){if(this.log.error("dial failed to %a - %e",f.multiaddr,h),o.add(f.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[wT]:D(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}if(t.aborted)throw new Gr(h.message);l.push(h)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let s=[...t].map(d=>({multiaddr:q(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new os("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Tu("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{let d=await this.components.peerStore.get(e);s.push(...d.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:p})=>p.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(s.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let d=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,s.map(({multiaddr:p})=>p.toString())),s.push(...d.multiaddrs.map(p=>({multiaddr:p,isCertified:!1})))}catch(d){d.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,d)}}}let o=(await Promise.all(s.map(async d=>{let p=await kw(d.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return p.length===1&&p[0].equals(d.multiaddr)?d:p.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let d=`/p2p/${e.toString()}`;o=o.map(p=>p.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:p.multiaddr.encapsulate(d),isCertified:p.isCertified}:p)}let i=o.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;let p=d.multiaddr.getComponents().findLast(f=>f.code===421)?.value;return e!=null&&p!=null?e.equals(p):!0}),a=new Map;for(let d of i){let p=d.multiaddr.toString(),f=a.get(p);if(f!=null){f.isCertified=f.isCertified||d.isCertified||!1;continue}a.set(p,d)}let c=[...a.values()];if(c.length===0)throw new Hp("The dial request has no valid addresses");let l=[];for(let d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);let u=this.addressSorter==null?ET(l):l.sort(this.addressSorter);if(u.length===0)throw new Tu("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(s=>s.toString())),t);return t.runOnLimitedConnection===!1?n.find(s=>!Jt.matches(s.multiaddr))!=null:!0}catch{}return!1}};V();var CH=Object.prototype.toString,TH=r=>CH.call(r)==="[object Error]",_H=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Nw(r){if(!(r&&TH(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:_H.has(t)}function PH(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function n1(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var Bw=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function DH(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function kT(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function kH({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:s}){let o=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(o instanceof Bw)throw o.originalError;let i=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,a=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:o,attemptNumber:e,retriesLeft:i,retriesConsumed:t});if(await s.onFailedAttempt(c),kT(n,a)<=0)throw o;let l=await s.shouldConsumeRetry(c),u=kT(n,a);if(u<=0||i<=0)throw o;if(o instanceof TypeError&&!Nw(o)){if(l)throw o;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw o;if(!l)return s.signal?.throwIfAborted(),!1;let d=DH(t,s),p=Math.min(d,u);return p>0&&await new Promise((f,h)=>{let m=()=>{clearTimeout(g),s.signal?.removeEventListener("abort",m),h(s.signal.reason)},g=setTimeout(()=>{s.signal?.removeEventListener("abort",m),f()},p);s.unref&&g.unref?.(),s.signal?.addEventListener("abort",m,{once:!0})}),s.signal?.throwIfAborted(),!0}async function Uw(r,e={}){if(e={...e},PH(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,n1("factor",e.factor,{min:0,allowInfinity:!1}),n1("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),n1("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),n1("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let o=await r(t);return e.signal?.throwIfAborted(),o}catch(o){await kH({error:o,attemptNumber:t,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var s1=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Ps({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,s)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);LT(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Uw(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let s={};[...t.tags.keys()].forEach(o=>{o.startsWith(mc)&&(s[o]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>LT(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function LT(r){for(let e of r.tags.keys())if(e.startsWith(mc))return!0;return!1}var Rw=50,Kw={maxConnections:vT,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},o1=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Kw.maxConnections,this.maxConnections<1)throw new B("Connection Manager maxConnections must be greater than 0");this.connections=new Zt,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>_u(q(n))),this.deny=(t.deny??[]).map(n=>_u(q(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Kw.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Nf({points:t.inboundConnectionThreshold??Kw.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Xp({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>q(n))}),this.dialQueue=new r1(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Qp,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Pu},connections:this.connections}),this.reconnectQueue=new s1({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let s of n.streams){let o=`${s.direction} ${s.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 s of n){let o={};for(let i of s.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,s]of Object.entries(e)){s=s.sort((i,a)=>i-a);let o=Math.floor(s.length*.9);t[n]=s[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await kh(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Lh(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([Re(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(s=>{n.abort(s)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new B("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,s=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Dr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:s}=jp(e);if(this.peerId.equals(n))throw new Qo("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=Yp(n,this.getConnections(n),s);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new Le("dial-queue:already-connected")),c}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??Rw});if(o.status!=="open")throw new zs("Remote closed connection during opening");let i=this.connections.get(o.remotePeer);i==null&&(i=[],this.connections.set(o.remotePeer,i));let a=!1;for(let c of i)if(c.id===o.id&&(a=!0),t.force!==!0&&c.id!==o.id&&c.remoteAddr.equals(o.remoteAddr))return o.abort(new ss("Duplicate multiaddr connection")),c;return a||i.push(o),o}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async s=>{try{await Promise.all([Re(s,"close",t),s.close(t)])}catch(o){s.abort(o)}}))}acceptIncomingConnection(e){if(this.deny.some(s=>{if(St(e.remoteAddr)){let o=oe(e.remoteAddr);return s.contains(o.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(s=>{if(St(e.remoteAddr)){let o=oe(e.remoteAddr);return s.contains(o.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(St(e.remoteAddr)){let s=oe(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(s.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>q(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};V();Ue();var OH=1e4,RH="1.0.0",NH="ping",BH="ipfs",MT=32,UH=!0,i1=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??BH}/${NH}/${RH}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??OH,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??UH,this.timeout=new Lf({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[nt]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,Y(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),s=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),o=gb(s);t=Date.now(),await Promise.all([o.write(fs(MT),{signal:n}),o.read({bytes:MT,signal:n})]),e.rtt=Date.now()-t,await s.close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};V();ie();var a1=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()}),getAttributesFromYieldedValue:(n,s)=>({...s,providers:[...Array.isArray(s.providers)?s.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:T(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:T(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Pa("No content routers available");let n=this,s=new Io;for await(let o of Ks(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id)&&(s.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new Pa("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Pa("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Dr;await Promise.all(this.routers.filter(s=>s.put instanceof Function).map(async s=>{await s.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Dr;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};V();var c1=globalThis.CustomEvent??Event;async function*Fw(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,s=new EventTarget,o=[],i=ut(),a=ut(),c=!1,l,u=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of r){if(o.length===t&&(i=ut(),await i.promise),u)break;let m={done:!1};o.push(m),h().then(g=>{m.done=!0,m.ok=!0,m.value=g,s.dispatchEvent(new c1("task-complete"))},g=>{m.done=!0,m.err=g,s.dispatchEvent(new c1("task-complete"))})}c=!0,s.dispatchEvent(new c1("task-complete"))}catch(h){l=h,s.dispatchEvent(new c1("task-complete"))}});function d(){return n?o[0]?.done:!!o.find(h=>h.done)}function*p(){for(;o.length>0&&o[0].done;){let h=o[0];if(o.shift(),h.ok)yield h.value;else throw u=!0,i.resolve(),h.err;i.resolve()}}function*f(){for(;d();)for(let h=0;h<o.length;h++)if(o[h].done){let m=o[h];if(o.splice(h,1),h--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(d()||(a=ut(),await a.promise),l!=null||(n?yield*p():yield*f(),l!=null))throw l;if(c&&o.length===0)break}}ie();var l1=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,key:T(n,"base36")}),getAttributesFromYieldedValue:(n,s)=>({...s,peers:[...Array.isArray(s.peers)?s.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Cu("No peer routers available");if(e.toString()===this.peerId.toString())throw new Up("Should not try to find self");let n=this,s=Ks(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let o of s)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new $s}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Cu("No peer routers available");let n=this,s=ln(1024);for await(let o of Fw((async function*(){let i=Ks(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id.toMultihash().bytes)&&(s.add(o.id.toMultihash().bytes),yield o))}};Ue();function KH(r){return r.reason}async function ku(r,e,t){if(e==null)return r;let n=t?.translateError??KH;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var u1=class extends me{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,Y(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,Y(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=zt([this.shutdownController.signal,e?.signal]);Y(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ut(),yield(await Re(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,Y(1/0,this.walkController.signal);let e=zt([this.walkController.signal,this.shutdownController.signal]);Y(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let s=fs(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await ku(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,n)}catch(s){this.log.error("random walk errored - %e",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("random walk errored - %e",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};V();var zw=32,$w=64,h1=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,s]of this.topologies)t[n]=s.size;return t}}),this.handlers=Dt({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new Kp(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new Fp(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:zw,maxOutboundStreams:$w,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(s=>{this.handlers.delete(s)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new B("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let s=await this.components.peerStore.get(t,n);for(let o of s.protocols){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t)!==!1&&(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(s){if(s.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,s)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,s=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));try{for(let o of s){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(o){this.log.error("could not inform topologies of updated peer %p - %e",t.id,o)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,s=e.detail.peerId;try{for(let o of t){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),await a.onConnect?.(s,n))}))}}catch(o){this.log.error("could not inform topologies of updated peer after identify %p - %e",s,o)}}};V();var d1=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Dt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Dt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??gc.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new B("Transport must have a valid tag");if(this.transports.has(t))throw new B(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let s=n.pop();s!=null&&e.push(s.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Gp(`No transport available for address ${String(e)}`);return t?.onProgress?.(new Le("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Dr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(o=>{t.errors.set(o.toString(),new zp)});let n=[];for(let[o,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=u.findIndex(p=>p===l);u.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Z3.matches(c)?t.ipv4.attempts++:eb.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Z3.matches(c)&&t.ipv4.success++,eb.matches(c)&&t.ipv6.success++},d=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,d),t.errors.set(c.toString(),d),d}))}}let s=await Promise.allSettled(n);if(!(s.length>0&&s.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===gc.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new $p(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
20
+ ${e}[Error list was empty]`,t.trim()}return rA(r,e)}Ht.formatters.e=r=>r==null?"undefined":sA(r);function NK(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Lf(r){return{forComponent(e){return oA(e,r)}}}function oA(r,e){let t=NK(`${r}:trace`);return Ht.enabled(`${r}:trace`)&&Ht.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ht(`${r}:trace`,e)),Object.assign(Ht(r,e),{error:Ht(`${r}:error`,e),trace:t,newScope:n=>oA(`${r}:${n}`,e)})}function nA(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function BK(r){return r[Symbol.asyncIterator]!=null}function UK(r){if(BK(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var ql=UK;var tr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Mf(r,e,t,n){let s=new tr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){J3(t,"abort",d),J3(r,e,l),J3(r,o,u)}let l=p=>{try{if(n?.filter?.(p)===!1)return}catch(f){c(),a(f);return}c(),i(p)},u=p=>{if(c(),p instanceof Error){a(p);return}a(p.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{c(),a(s)};Q3(t,"abort",d),Q3(r,e,l),Q3(r,o,u)})}function Q3(r,e,t){r!=null&&(iA(r)?r.addEventListener(e,t):r.addListener(e,t))}function J3(r,e,t){r!=null&&(iA(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function iA(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Of=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Rf=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new tr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function KK(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Nf=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=KK(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,W(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new tr),this.cleanup())}async join(e={}){let t=new Rf(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Bu(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Z3(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Vl=class extends he{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Z3(this.emitEmpty.bind(this),1),this.emitIdle=Z3(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Of;let n=new Nf(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new tr)}),this.clear()}async onEmpty(e){this.size!==0&&await Mf(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Mf(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Mf(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=It({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new tr("Queue aborted"))};this.addEventListener("success",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Wl=ne(Z("node:cluster"),1),Ff=ne(Z("node:worker_threads"),1);var lo="lock:worker:request-read",uo="lock:worker:abort-read-request",ho="lock:worker:release-read",fo="lock:master:grant-read",po="lock:master:error-read",mo="lock:worker:request-write",go="lock:worker:abort-write-request",yo="lock:worker:release-write",bo="lock:master:grant-write",wo="lock:master:error-write",ps="lock:worker:finalize",Bf="mortice",aA={singleProcess:!1};var eb=(r,e,t,n,s,o,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(d=>{let p=f=>{if(f?.data==null)return;let h={type:f.data.type,name:f.data.name,identifier:f.data.identifier};h.type===a&&h.identifier===u.identifier&&(e.removeEventListener("message",p),d())};e.addEventListener("message",p)})},onError:d=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:d.message,name:d.name,stack:d.stack}})}}}),u.type===o&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===ps&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var tb=(r,e,t,n,s,o,i,a)=>(c,l)=>{l!=null&&(l.type===n&&r.safeDispatchEvent(e,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{c.send({type:a,name:l.name,identifier:l.identifier}),await new Promise(u=>{let d=p=>{p.type===i&&p.identifier===l.identifier&&(c.removeListener("message",d),u())};c.on("message",d)})},onError:u=>{c.send({type:o,name:l.name,identifier:l.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),l.type===s&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier}}),l.type===ps&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}}))};var Gl=(r=10)=>Math.random().toString().substring(2,r+2);var Uf=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Bf)}readLock(e){return this.sendRequest(lo,uo,fo,po,ho,e)}writeLock(e){return this.sendRequest(mo,go,bo,wo,yo,e)}finalize(){this.channel.postMessage({type:ps,name:this.name}),this.channel.close()}async sendRequest(e,t,n,s,o,i){i?.signal?.throwIfAborted();let a=Gl();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let d=p=>{if(p.data?.identifier===a&&(p.data?.type===n&&(this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),p.data.type===s)){this.channel.removeEventListener("message",d),i?.signal?.removeEventListener("abort",u);let f=new Error;p.data.error!=null&&(f.message=p.data.error.message,f.name=p.data.error.name,f.stack=p.data.error.stack),l(f)}};this.channel.addEventListener("message",d)})}};var Kf=class{name;constructor(e){this.name=e}readLock(e){return this.sendRequest(lo,uo,fo,po,ho,e)}writeLock(e){return this.sendRequest(mo,go,bo,wo,yo,e)}finalize(){if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");process.send({type:ps,identifier:Gl(),name:this.name})}async sendRequest(e,t,n,s,o,i){i?.signal?.throwIfAborted();let a=Gl();if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");return process.send({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{process.send?.({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let d=p=>{if(p.identifier===a&&(p.type===n&&(process.removeListener("message",d),i?.signal?.removeEventListener("abort",u),c(()=>{process.send?.({type:o,identifier:a,name:this.name})})),p.type===s)){process.removeListener("message",d),i?.signal?.removeEventListener("abort",u);let f=new Error;p.error!=null&&(f.message=p.error.message,f.name=p.error.name,f.stack=p.error.stack),l(f)}};process.on("message",d)})}};function FK(){return Ff.default.isMainThread===!1||Ff.default.isInternalThread===!0?!1:Wl.default.isPrimary}var cA=r=>{if(r=Object.assign({},aA,r),FK()||r.singleProcess){let e=new he;Wl.default.on("message",tb(e,"requestReadLock","abortReadLockRequest",lo,uo,po,ho,fo)),Wl.default.on("message",tb(e,"requestWriteLock","abortWriteLockRequest",mo,go,wo,yo,bo));let t=new BroadcastChannel(Bf);return t.addEventListener("message",eb(e,t,"requestReadLock","abortReadLockRequest",lo,uo,po,ho,fo)),t.addEventListener("message",eb(e,t,"requestWriteLock","abortWriteLockRequest",mo,go,wo,yo,bo)),t.unref?.(),e}if(Wl.default.isWorker)return new Kf(r.name);if(Ff.default.isMainThread===!1)return new Uf(r.name);throw new Error("Not a cluster worker or worker thread")};var xo=new Map,jl;function lA(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function zK(r){if(jl==null&&(jl=cA(r),!lA(jl))){let e=jl;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=xo.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,s=t.detail.identifier,o=xo.get(n);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==s||i.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,s=xo.get(n);s?.finalize()})}return jl}async function rb(r,e){let t,n,s=new Promise((i,a)=>{t=i,n=a}),o=()=>{n(new tr)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",o),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),s}var uA=(r,e)=>{let t=xo.get(r);if(t!=null)return t;let n=zK(e);if(lA(n))return t=n,xo.set(r,t),t;let s=new Vl({concurrency:1}),o;return t={async readLock(i){if(o!=null)return rb(o,i);o=new Vl({concurrency:e.concurrency,autoStart:!1});let a=o,c=rb(o,i);return s.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(i){return o=null,rb(s,i)},finalize:()=>{xo.delete(r)},queue:s},xo.set(r,t),e.autoFinalize===!0&&s.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var $K={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function nb(r){let e=Object.assign({},$K,r);return uA(e.name,e)}var Rye=new Uint8Array(0);function hA(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function na(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function HK(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var qK=HK,VK=qK,dA=VK;var sb=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ob=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 fA(this,e)}},ib=class{decoders;constructor(e){this.decoders=e}or(e){return fA(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function fA(r,e){return new ib({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ab=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new sb(e,t,n),this.decoder=new ob(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function pA({name:r,prefix:e,encode:t,decode:n}){return new ab(r,e,t,n)}function sa({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=dA(t,r);return pA({prefix:e,name:r,encode:n,decode:o=>na(s(o))})}function GK(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function WK(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function jK(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Yr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=jK(n);return pA({prefix:e,name:r,encode(o){return WK(o,n,t)},decode(o){return GK(o,s,t,r)}})}var vo=Yr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$ye=Yr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Hye=Yr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qye=Yr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Vye=Yr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gye=Yr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wye=Yr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jye=Yr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yye=Yr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var zf=sa({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Jye=sa({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Tn=sa({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),t3e=sa({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var YK=yA,mA=128,XK=127,QK=~XK,JK=Math.pow(2,31);function yA(r,e,t){e=e||[],t=t||0;for(var n=t;r>=JK;)e[t++]=r&255|mA,r/=128;for(;r&QK;)e[t++]=r&255|mA,r>>>=7;return e[t]=r|0,yA.bytes=t-n+1,e}var ZK=cb,eF=128,gA=127;function cb(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw cb.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&gA)<<s:(i&gA)*Math.pow(2,s),s+=7}while(i>=eF);return cb.bytes=o-n,t}var tF=Math.pow(2,7),rF=Math.pow(2,14),nF=Math.pow(2,21),sF=Math.pow(2,28),oF=Math.pow(2,35),iF=Math.pow(2,42),aF=Math.pow(2,49),cF=Math.pow(2,56),lF=Math.pow(2,63),uF=function(r){return r<tF?1:r<rF?2:r<nF?3:r<sF?4:r<oF?5:r<iF?6:r<aF?7:r<cF?8:r<lF?9:10},hF={encode:YK,decode:ZK,encodingLength:uF},dF=hF,Yl=dF;function Xl(r,e=0){return[Yl.decode(r,e),Yl.decode.bytes]}function oa(r,e,t=0){return Yl.encode(r,e,t),e}function ia(r){return Yl.encodingLength(r)}function wA(r,e){let t=e.byteLength,n=ia(r),s=n+ia(t),o=new Uint8Array(s+t);return oa(r,o,0),oa(t,o,n),o.set(e,s),new aa(r,t,e,o)}function xA(r){let e=na(r),[t,n]=Xl(e),[s,o]=Xl(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new aa(t,s,i,e)}function vA(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&hA(r.bytes,t.bytes)}}var aa=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function EA(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return mF(t,lb(r),e??Tn.encoder);default:return gF(t,lb(r),e??vo.encoder)}}var SA=new WeakMap;function lb(r){let e=SA.get(r);if(e==null){let t=new Map;return SA.set(r,t),t}return e}var $f=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ql)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==yF)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=wA(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&vA(e.multihash,n.multihash)}toString(e){return EA(this,e)}toJSON(){return{"/":EA(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??IA(n,s,o.bytes))}else if(t[bF]===!0){let{version:n,multihash:s,code:o}=t,i=xA(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ql)throw new Error(`Version 0 CID must use dag-pb (code: ${Ql}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=IA(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ql,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=na(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new aa(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=Xl(e.subarray(t));return t+=p,d},s=n(),o=Ql;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=pF(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return lb(o).set(n,e),o}};function pF(r,e){switch(r[0]){case"Q":{let t=e??Tn;return[Tn.prefix,t.decode(`${Tn.prefix}${r}`)]}case Tn.prefix:{let t=e??Tn;return[Tn.prefix,t.decode(r)]}case vo.prefix:{let t=e??vo;return[vo.prefix,t.decode(r)]}case zf.prefix:{let t=e??zf;return[zf.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function mF(r,e,t){let{prefix:n}=t;if(n!==Tn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function gF(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Ql=112,yF=18;function IA(r,e,t){let n=ia(r),s=n+ia(e),o=new Uint8Array(s+t.byteLength);return oa(r,o,0),oa(e,o,n),o.set(t,s),o}var bF=Symbol.for("@ipld/js-cid/CID");var _n;(function(r){let e;(function(s){let o;s.codec=()=>(o==null&&(o=Q((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:se(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(d&7);break}}}return l})),o),s.encode=i=>X(i,s.codec()),s.decode=(i,a)=>Y(i,s.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(s){let o;s.codec=()=>(o==null&&(o=Q((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),qf.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{l.key=i.string();break}case 2:{l.value=qf.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(d&7);break}}}return l})),o),s.encode=i=>X(i,s.codec()),s.decode=(i,a)=>Y(i,s.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Q((s,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),s.addresses!=null)for(let a of s.addresses)o.uint32(10),Hf.codec().encode(a,o);if(s.protocols!=null)for(let a of s.protocols)o.uint32(18),o.string(a);if(s.publicKey!=null&&(o.uint32(34),o.bytes(s.publicKey)),s.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(s.peerRecordEnvelope)),s.metadata!=null&&s.metadata.size!==0)for(let[a,c]of s.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(s.tags!=null&&s.tags.size!==0)for(let[a,c]of s.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);s.updated!=null&&(o.uint32(64),o.uint64Number(s.updated)),i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new Ie('Decode error - map field "addresses" had too many elements');a.addresses.push(Hf.codec().decode(s,s.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new Ie('Decode error - map field "protocols" had too many elements');a.protocols.push(s.string());break}case 4:{a.publicKey=s.bytes();break}case 5:{a.peerRecordEnvelope=s.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new fc('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(s,s.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new fc('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(s,s.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=s.uint64Number();break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>X(s,r.codec()),r.decode=(s,o)=>Y(s,r.codec(),o)})(_n||(_n={}));var Hf;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={multiaddr:se(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}case 3:{o.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(Hf||(Hf={}));var qf;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(qf||(qf={}));function wF(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Pt(e.publicKey,t);return Zn(n)}function AA(r,e,t){let n=_n.decode(e);return ca(r,n,t)}function ca(r,e,t){let n=new Map,s=BigInt(Date.now());for(let[o,i]of e.tags.entries())i.expiry!=null&&i.expiry<s||n.set(o,i);return{...e,id:wF(r,e),addresses:e.addresses.filter(({observed:o})=>o!=null&&o>Date.now()-t).map(({multiaddr:o,isCertified:i})=>({multiaddr:H(o),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function CA(r,e){return xF(r.addresses,e.addresses)&&vF(r.protocols,e.protocols)&&EF(r.publicKey,e.publicKey)&&SF(r.peerRecordEnvelope,e.peerRecordEnvelope)&&IF(r.metadata,e.metadata)&&AF(r.tags,e.tags)}function xF(r,e){return _A(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!V(t.multiaddr,n.multiaddr)))}function vF(r,e){return _A(r,e,(t,n)=>t===n)}function EF(r,e){return TA(r,e)}function SF(r,e){return TA(r,e)}function IF(r,e){return PA(r,e,(t,n)=>V(t,n))}function AF(r,e){return PA(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function TA(r,e){return r==null&&e==null?!0:r!=null&&e!=null?V(r,e):!1}function _A(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function PA(r,e,t){if(r.size!==e.size)return!1;for(let[n,s]of r.entries()){let o=e.get(n);if(o==null||!t(s,o))return!1}return!0}var Pn="/",DA=new TextEncoder().encode(Pn),Vf=DA[0],Eo=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=P(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Vf)throw new Error("Invalid key")}toString(e="utf8"){return C(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Pn))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=DA),this._buf[0]!==Vf){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Vf,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Vf;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let s=0;s<t.length;s++){if(n.length<s+1)return!1;let o=t[s],i=n[s];if(o<i)return!0;if(o>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Pn).slice(1)}type(){return CF(this.baseNamespace())}name(){return TF(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Pn)||(e+=Pn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Pn):new r(e.slice(0,-1).join(Pn))}child(e){return this.toString()===Pn?e:e.toString()===Pn?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),..._F(e.map(t=>t.namespaces()))])}};function CF(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function TF(r){let e=r.split(":");return e[e.length-1]}function _F(r){return[].concat(...r)}var ub="/peers/";function Jl(r){if(!Vn(r)||r.type==null)throw new N("Invalid PeerId");let e=r.toCID().toString();return new Eo(`${ub}${e}`)}async function kA(r,e,t,n,s){let o=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=H(i.multiaddr)),!ls(i.multiaddr))throw new N("Multiaddr was invalid");if(!await e(r,i.multiaddr,s))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=o.get(c);l!=null?i.isCertified=l.isCertified||a:o.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...o.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(H(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Wf(r,e,t,n){if(e==null)throw new N("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new N("publicKey bytes do not match peer id publicKey bytes");let s=n.existingPeer?.peer;if(s!=null&&!r.equals(s.id))throw new N("peer id did not match existing peer id");let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(p=>({isCertified:!1,multiaddr:p}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let p=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Gf(p,{validate:LA})}if(e.tags!=null){let p=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Gf(p,{validate:MA,map:OA})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(p=>({isCertified:!1,multiaddr:p}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let p=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,h]of p)h==null?a.delete(f):a.set(f,h);a=Gf([...a.entries()],{validate:LA})}if(e.tags!=null){let p=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[h,m]of p)m==null?f.delete(h):f.set(h,m);c=Gf([...f.entries()],{validate:MA,map:OA})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;s?.id.publicKey!=null?u=nt(s.id.publicKey):e.publicKey!=null?u=nt(e.publicKey):r.publicKey!=null&&(u=nt(r.publicKey));let d={addresses:await kA(r,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((p,f)=>p.localeCompare(f)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return d.addresses.forEach(p=>{p.observed=n.existingPeer?.peerPB.addresses?.find(f=>V(f.multiaddr,f.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete d.publicKey,d}function Gf(r,e){let t=new Map;for(let[n,s]of r)s!=null&&e.validate(n,s);for(let[n,s]of r.sort(([o],[i])=>o.localeCompare(i)))s!=null&&t.set(n,e.map?.(n,s)??s);return t}function LA(r,e){if(typeof r!="string")throw new N("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new N("Metadata value must be a Uint8Array")}function MA(r,e){if(typeof r!="string")throw new N("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new N("Tag value must be an integer");if(e.value<0||e.value>100)throw new N("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new N("Tag ttl must be an integer");if(e.ttl<0)throw new N("Tag ttl must be between greater than 0")}}function OA(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function RA(r){let e=r.toString().split("/")[2],t=$f.parse(e,vo);return yn(t)}function hb(r,e,t){let n=RA(r);return AA(n,e,t)}function PF(r,e){return{prefix:ub,filters:(r.filters??[]).map(t=>({key:n,value:s})=>t(hb(n,s,e))),orders:(r.orders??[]).map(t=>(n,s)=>t(hb(n.key,n.value,e),hb(s.key,s.value,e)))}}var jf=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=Hl({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:nb({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let s=await n.lock.readLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async getWriteLock(e,t){let n=this.getLock(e);try{let s=await n.lock.writeLock(t);return()=>{s(),this.maybeRemoveLock(e,n)}}catch(s){throw this.maybeRemoveLock(e,n),s}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Jl(e),t)}async load(e,t){let n=Jl(e),s=await this.datastore.get(n,t),o=_n.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new Cs;return ca(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let s=await this.#e(e,n),o=await Wf(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,o,s)}async patch(e,t,n){let s=await this.#e(e,n),o=await Wf(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async merge(e,t,n){let s=await this.#e(e,n),o=await Wf(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,s)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(PF(e??{},this.maxAddressAge),e)){let s=RA(t);if(s.equals(this.peerId))continue;let o=_n.decode(n);if(this.#r(s,o)){await this.datastore.delete(t,e);continue}yield ca(s,o,this.peerId.equals(s)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Jl(e),s=await this.datastore.get(n,t),o=_n.decode(s);if(this.#r(e,o))throw await this.datastore.delete(n,t),new Cs;return{peerPB:o,peer:ca(e,o,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,s){t.updated=Date.now();let o=_n.encode(t);return await this.datastore.put(Jl(e),o,s),{peer:ca(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!CA(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,s=Date.now()-this.maxAddressAge,o=t.addresses.filter(i=>i.observed!=null&&i.observed>s);return n&&o.length===0}};var db=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new jf(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return ql(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:s})=>s)}}async save(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.save(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async patch(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.patch(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async merge(e,t,n){let s=await this.store.getWriteLock(e,n);try{let o=await this.store.merge(e,t,n);return this.#e(e,o),o.peer}finally{s?.()}}async consumePeerRecord(e,t,n){let s=Vn(t)?t:Vn(t?.expectedPeer)?t.expectedPeer:void 0,o=Vn(t)||t===void 0?n:t,i=await Jt.openAndCertify(e,Zt.DOMAIN,o),a=yn(i.publicKey.toCID());if(s?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",s,a),!1;let c=Zt.createFromProtobuf(i.payload),l;try{l=await this.get(a,o)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=Jt.createFromProtobuf(l.peerRecordEnvelope),d=Zt.createFromProtobuf(u.payload);if(d.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},o),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function NA(r,e={}){return new db(r,e)}var Yf=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function DF(r){return r[Symbol.asyncIterator]!=null}function kF(r){if(DF(r))return(async()=>{for await(let e of r);})();for(let e of r);}var fb=kF;function LF(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var BA=LF;function MF(r){return r[Symbol.asyncIterator]!=null}function OF(r,e){let t=0;if(MF(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=BA(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var So=OF;function RF(r){return r[Symbol.asyncIterator]!=null}function NF(r,e){return RF(r)?(async function*(){yield*(await ql(r)).sort(e)})():(function*(){yield*ql(r).sort(e)})()}var pb=NF;function BF(r){return r[Symbol.asyncIterator]!=null}function UF(r,e){return BF(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var mb=UF;var Xf=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:s}of e)await this.put(n,s,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,s){e.push({key:n,value:s})},delete(n){t.push(n)},commit:async n=>{await fb(this.putMany(e,n)),e=[],await fb(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let s=e.prefix;n=So(n,o=>o.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>So(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>pb(s,o),n)),e.offset!=null){let s=0,o=e.offset;n=So(n,()=>s++>=o)}return e.limit!=null&&(n=mb(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let s=e.prefix;n=So(n,o=>o.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>So(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>pb(s,o),n)),e.offset!=null){let s=e.offset,o=0;n=So(n,()=>o++>=s)}return e.limit!=null&&(n=mb(n,e.limit)),n}};var Qf=class extends Xf{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Yf;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,s]of this.data.entries())yield{key:new Eo(n),value:s},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Eo(n),t?.signal?.throwIfAborted()}};var UA=864e13;var Jf=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=xt({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=re(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let s of this.mappings.values())if(s.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let s=Hi(n)===!0;this.mappings.set(n,{domain:e,verified:s,expires:s?UA-Date.now():0,lastVerified:s?UA-Date.now():void 0})})}remove(e){let t=re(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries())o.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",s,o.domain),this.mappings.delete(s),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n].multiaddr;if(!ft(s))continue;let o=re(s);for(let[i,a]of this.mappings.entries()){if(o.host!==i)continue;let c=this.maybeAddSNIComponent(s,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let s=0;s<n.length;s++)if(n[s].code===448&&n[s+1]?.code!==449)return n.splice(s+1,0,{name:"sni",code:449,value:t}),H(n)}confirm(e,t){let n=re(e),s=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(s=n.sni);let o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=re(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let s=n.sni??n.host,o=!1;for(let[i,a]of this.mappings.entries())a.domain===s&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t);return o}};var Zf=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=xt({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=re(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let s of n)if(s.externalIp===t.host)return!0;return!1}add(e,t,n,s=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:s,externalFamily:(0,le.isIPv4)(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=re(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[s,o]of this.mappings.entries()){for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,o.splice(i,1),i--)}o.length===0&&this.mappings.delete(s)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!ft(n))continue;let s=re(n);if(s.type!=="ip4"&&s.type!=="ip6")continue;let o;if(s.protocol==="tcp"?o=`${s.host}-${s.port}-tcp`:s.protocol==="udp"&&(o=`${s.host}-${s.port}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,s,o){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===s);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${o}`,H(i)):e}confirm(e,t){if(!ft(e))return!1;let n=re(e),s=!1;for(let o of this.mappings.values())for(let i of o)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),s=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return s}unconfirm(e,t){if(!ft(e))return!1;let n=re(e),s=!1;for(let o of this.mappings.values())for(let i=0;i<o.length;i++){let a=o[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t)}return s}};var KF={maxObservedAddresses:10},ep=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=xt({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??KF.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(In(e)||MS(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:H(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),s=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,s),o}};var FF={maxObservedAddresses:10},tp=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=xt({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??FF.maxObservedAddresses}get(e,t){if(In(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),s=this.addresses.get(n);return s==null&&(s={verified:!ft(e),expires:0},this.addresses.set(n,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.addresses.set(n,s),o}unconfirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0},o=s.verified;return s.verified=!1,s.expires=Date.now()+t,this.addresses.set(n,s),o}toKey(e){if(!ft(e))return e.toString();let t=re(e);return`${t.host}-${t.port}-${t.protocol}`}};var KA=6e4,FA={maxObservedAddresses:10,addressVerificationTTL:KA*10,addressVerificationRetry:KA*5},zF=r=>r;function gb(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&oe(t).equals(e)&&(r=r.decapsulate(H(`/p2p/${e.toString()}`))),r}var rp=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:s=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(s.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new ep(e,t),this.dnsMappings=new Jf(e,t),this.ipMappings=new Zf(e,t),this.transportAddresses=new tp(e,t),this.announceFilter=t.announceFilter??zF,this.observedAddressFilter=Gr(1024),this.addressVerificationTTL=t.addressVerificationTTL??FA.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??FA.addressVerificationRetry,this._updatePeerStoreAddresses=no(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>H(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>H(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>H(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=re(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=gb(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=gb(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=gb(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let s=n.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let s=H(n);return s.getComponents().pop()?.value===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(e)}),e.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(s=>this.transportAddresses.get(s,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(s=>{s.updateAnnounceAddrs(n)}),t=t.concat(n.map(s=>({multiaddr:s,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(H(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.add(e,t,n,s,o),this.observed.removePrefixed(`/ip${(0,le.isIPv4)(n)?4:6}/${n}/${o}/${s}`)}removePublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.remove(H(`/ip${(0,le.isIPv4)(n)?4:6}/${n}/${o}/${s}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!ft(e))return!1;let t=re(e);if(t.type!=="ip4"||Hi(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),s=[o=>Al.exactMatch(o)||Cl.exactMatch(o),o=>Sn.exactMatch(o),o=>IS.exactMatch(o)];for(let o of s){if(!o(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>re(u).type==="ip4"&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!Pl(l)).pop();if(a==null)continue;let c=re(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var zA;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(zA||(zA={}));var np=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},sp=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},la=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Zl=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},op=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},ip=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},ap=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},eu=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},cp=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},lp=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},up=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},hp=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},dp=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},ms=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Io=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},fp=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},pp=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var yb=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Lf())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>nh(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},$F=["metrics","connectionProtector","dns"],HF=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function $A(r={}){let e=new yb(r);return new Proxy(e,{get(n,s,o){if(typeof s=="string"&&!HF.includes(s)){let i=e.components[s];if(i==null&&!$F.includes(s))throw new np(`${s} not set`);return i}return Reflect.get(n,s,o)},set(n,s,o){return typeof s=="string"?e.components[s]=o:Reflect.set(n,s,o),!0}})}function HA(r){let e={};for(let t of Object.values(r.components))for(let n of qF(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of VF(t))if(e[n]!==!0)throw new sp(`Service "${GF(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function qF(r){return Array.isArray(r?.[je])?r[je]:[]}function VF(r){return Array.isArray(r?.[Xa])?r[Xa]:[]}function GF(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function qA(r={}){return r}function mp(r){if(Vn(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(s=>s.code===421)?.value;t=n==null?void 0:oe(n),e.forEach(s=>{if(!ls(s))throw new zn("Invalid multiaddr");let o=s.getComponents().findLast(i=>i.code===421)?.value;if(o==null){if(t!=null)throw new N("Multiaddrs must all have the same peer id or have no peer id")}else{let i=oe(o);if(t?.equals(i)!==!0)throw new N("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!xS.exactMatch(n)),{peerId:t,multiaddrs:e}}var WF=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function VA(r,e){let t=r?.streams?.map(s=>s.protocol)??[],n=e?.closableProtocols??WF;if(!(t.filter(s=>s!=null&&!n.includes(s)).length>0))try{await r?.close(e)}catch(s){r?.abort(s)}}function tu(r){let e=re(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new N(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new N(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new xn(e.host,t)}function bb(r){return!zt.exactMatch(r)}function gp(r,e,t){if(r==null||e==null)return;let n=e.sort((o,i)=>o.direct?-1:i.direct?1:0).find(o=>o.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(o=>bb(o)))return n}var yp=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>tu(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let s=new $t;for(let c of e){let l=c.remotePeer;if(!s.has(l)){s.set(l,0);try{let u=await this.peerStore.get(l);s.set(l,[...u.tags.values()].reduce((d,p)=>d+p.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let o=this.sortConnections(e,s),i=Math.max(t-n,0),a=[];for(let c of o)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(ft(c.remoteAddr)){let d=re(c.remoteAddr);return u.contains(d.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await VA(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,s)=>{let o=n.timeline.open,i=s.timeline.open;return o<i?1:o>i?-1:0}).sort((n,s)=>n.direction==="outbound"&&s.direction==="inbound"?1:n.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((n,s)=>n.streams.length>s.streams.length?1:n.streams.length<s.streams.length?-1:0).sort((n,s)=>{let o=t.get(n.remotePeer)??0,i=t.get(s.remotePeer)??0;return o>i?1:o<i?-1:0})}};var GA="last-dial-failure",WA="last-dial-success";var jA=300,bp=100;function jF(r,e){let t=Sn.exactMatch(r.multiaddr),n=Sn.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let s=Cl.exactMatch(r.multiaddr),o=Cl.exactMatch(e.multiaddr);if(s&&!o)return-1;if(!s&&o)return 1;let i=Al.exactMatch(r.multiaddr),a=Al.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Xy.exactMatch(r.multiaddr),l=Xy.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=jy.exactMatch(r.multiaddr),d=jy.exactMatch(e.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;let p=Yy.exactMatch(r.multiaddr),f=Yy.exactMatch(e.multiaddr);return p&&!f?-1:!p&&f?1:0}function YF(r,e){let t=Pl(r.multiaddr),n=Pl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function XF(r,e){let t=In(r.multiaddr),n=In(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function QF(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function JF(r,e){let t=zt.exactMatch(r.multiaddr),n=zt.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function YA(r){return r.sort(jF).sort(QF).sort(JF).sort(XF).sort(YF)}var QA=Z("dns/promises");function wp(r){let e=[vt.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var wb=60;function xp(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:vt[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:vt[e.type],TTL:e.TTL??e.ttl??wb,data:e.data instanceof Uint8Array?C(e.data):e.data}))}}var ZF=async(r,e={})=>{let t=new QA.Resolver,n=()=>{t.cancel()},s=wp(e.types);try{e.signal?.addEventListener("abort",n);let o=await Promise.all(s.map(async i=>{if(i===vt.A)return vp(r,i,await t.resolve4(r));if(i===vt.CNAME)return vp(r,i,await t.resolveCname(r));if(i===vt.TXT)return vp(r,i,await t.resolveTxt(r));if(i===vt.AAAA)return vp(r,i,await t.resolve6(r));throw new TypeError("Unsupported DNS record type")}));return xp({Question:s.map(i=>({name:r,type:i})),Answer:o.flat()})}finally{e.signal?.removeEventListener("abort",n)}};function JA(){return[ZF]}function XA(r,e,t){return{name:r,type:e,data:t}}function vp(r,e,t){return Array.isArray(t)||(t=[t]),t.map(n=>Array.isArray(n)?n.map(s=>XA(r,e,s)):XA(r,e,n)).flat()}var t8=ne(e8(),1);var xb=class{lru;constructor(e){this.lru=(0,t8.default)(e)}get(e,t){let n=!0,s=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){n=!1;break}s.push(...i)}if(n)return xp({answers:s})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,s=this.lru.get(n);if(s!=null){let o=s.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:vt[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,s=this.lru.get(n)??[];s.push({expires:Date.now()+(t.TTL??wb)*1e3,value:t}),this.lru.set(n,s)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function r8(r){return new xb(r)}var ez=1e3,Ep=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=r8(e.cacheSize??ez),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=JA())}async query(e,t={}){let n=wp(t.types),s=t.cached!==!1?this.cache.get(e,n):void 0;if(s!=null)return t.onProgress?.(new Te("dns:cache",s)),s;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new Te("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var vt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(vt||(vt={}));function n8(r={}){return new Ep(r)}var vb=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let o=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[vt.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of o.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(H(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=n8()),this.dns)}},ru=new vb;async function Eb(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new pp("Max recursive depth reached");let s=!1,o=[];for(let i of Object.values(e))if(i.canResolve(r)){s=!0;let a=await i.resolve(r,t);for(let c of a)o.push(...await Eb(c,e,{...t,depth:n+1}))}return s===!1&&o.push(r),o}var nu={maxParallelDials:bp,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:ru}},Sp=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??nu.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??nu.maxDialQueueLength,this.dialTimeout=t.dialTimeout??nu.dialTimeout,this.connections=t.connections??new $t,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??nu.resolvers,this.shutDownController=new AbortController,W(1/0,this.shutDownController.signal),this.queue=new tf({concurrency:t.maxParallelDials??nu.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Vt.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,W(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:s}=mp(e);if(n!=null&&t.force!==!0){let i=gp(n,this.connections.get(n),s);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new Te("dial-queue:already-connected")),i}let o=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of s)if(a.has(c.toString()))return!0;return!1});if(o!=null){this.log("joining existing dial target for %p",n);for(let i of s)o.options.multiaddrs.add(i.toString());return t.onProgress?.(new Te("dial-queue:already-in-dial-queue")),o.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new $n("Dial queue is full");return this.log("creating dial target for %p",n,s.map(i=>i.toString())),t.onProgress?.(new Te("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new Te("dial-queue:start-dial"));let a=Dt([this.shutDownController.signal,i.signal]);W(1/0,a);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Cb,multiaddrs:new Set(s.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,s=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||s.size>0;){c++,i=!1;let u=[],d=new Set(e.multiaddrs);s.clear(),this.log("calculating addrs to dial %p from %s",n,[...d]);let p=await this.calculateMultiaddrs(n,d,{...e,signal:t});for(let f of p){if(o.has(f.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",f.multiaddr,n);continue}u.push(f)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(f=>f.multiaddr.toString())),e?.onProgress?.(new Te("dial-queue:calculated-addresses",u));for(let f of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new $n("Peer had more than maxPeerAddrsToDial");a++;try{let h=await this.components.transportManager.dial(f.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",f.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[WA]:P(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}return h}catch(h){if(this.log.error("dial failed to %a - %e",f.multiaddr,h),o.add(f.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[GA]:P(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}if(t.aborted)throw new kr(h.message);l.push(h)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let s=[...t].map(d=>({multiaddr:H(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new $n("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new eu("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{let d=await this.components.peerStore.get(e);s.push(...d.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:p})=>p.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(s.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let d=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,s.map(({multiaddr:p})=>p.toString())),s.push(...d.multiaddrs.map(p=>({multiaddr:p,isCertified:!1})))}catch(d){d.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,d)}}}let o=(await Promise.all(s.map(async d=>{let p=await Eb(d.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return p.length===1&&p[0].equals(d.multiaddr)?d:p.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let d=`/p2p/${e.toString()}`;o=o.map(p=>p.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:p.multiaddr.encapsulate(d),isCertified:p.isCertified}:p)}let i=o.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;let p=d.multiaddr.getComponents().findLast(f=>f.code===421)?.value;return e!=null&&p!=null?e.equals(p):!0}),a=new Map;for(let d of i){let p=d.multiaddr.toString(),f=a.get(p);if(f!=null){f.isCertified=f.isCertified||d.isCertified||!1;continue}a.set(p,d)}let c=[...a.values()];if(c.length===0)throw new up("The dial request has no valid addresses");let l=[];for(let d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);let u=this.addressSorter==null?YA(l):l.sort(this.addressSorter);if(u.length===0)throw new eu("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(s=>s.toString())),t);return t.runOnLimitedConnection===!1?n.find(s=>!zt.matches(s.multiaddr))!=null:!0}catch{}return!1}};var tz=Object.prototype.toString,rz=r=>tz.call(r)==="[object Error]",nz=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Tb(r){if(!(r&&rz(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:nz.has(t)}function sz(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Ip(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var _b=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function oz(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function s8(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function iz({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:s}){let o=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(o instanceof _b)throw o.originalError;let i=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,a=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:o,attemptNumber:e,retriesLeft:i,retriesConsumed:t});if(await s.onFailedAttempt(c),s8(n,a)<=0)throw o;let l=await s.shouldConsumeRetry(c),u=s8(n,a);if(u<=0||i<=0)throw o;if(o instanceof TypeError&&!Tb(o)){if(l)throw o;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw o;if(!l)return s.signal?.throwIfAborted(),!1;let d=oz(t,s),p=Math.min(d,u);return p>0&&await new Promise((f,h)=>{let m=()=>{clearTimeout(g),s.signal?.removeEventListener("abort",m),h(s.signal.reason)},g=setTimeout(()=>{s.signal?.removeEventListener("abort",m),f()},p);s.unref&&g.unref?.(),s.signal?.addEventListener("abort",m,{once:!0})}),s.signal?.throwIfAborted(),!0}async function Pb(r,e={}){if(e={...e},sz(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Ip("factor",e.factor,{min:0,allowInfinity:!1}),Ip("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Ip("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Ip("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let o=await r(t);return e.signal?.throwIfAborted(),o}catch(o){await iz({error:o,attemptNumber:t,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Ap=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new fs({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,s)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);o8(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Pb(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let s={};[...t.tags.keys()].forEach(o=>{o.startsWith(ja)&&(s[o]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>o8(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function o8(r){for(let e of r.tags.keys())if(e.startsWith(ja))return!0;return!1}var Cb=50,Db={maxConnections:jA,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Cp=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Db.maxConnections,this.maxConnections<1)throw new N("Connection Manager maxConnections must be greater than 0");this.connections=new $t,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>tu(H(n))),this.deny=(t.deny??[]).map(n=>tu(H(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Db.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new rf({points:t.inboundConnectionThreshold??Db.inboundConnectionThreshold,duration:1}),this.connectionPruner=new yp({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>H(n))}),this.dialQueue=new Sp(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??bp,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:ru},connections:this.connections}),this.reconnectQueue=new Ap({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let s of n.streams){let o=`${s.direction} ${s.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 s of n){let o={};for(let i of s.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,s]of Object.entries(e)){s=s.sort((i,a)=>i-a);let o=Math.floor(s.length*.9);t[n]=s[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await sh(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await oh(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([De(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(s=>{n.abort(s)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new N("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,s=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new yr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:s}=mp(e);if(this.peerId.equals(n))throw new Oo("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=gp(n,this.getConnections(n),s);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new Te("dial-queue:already-connected")),c}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??Cb});if(o.status!=="open")throw new As("Remote closed connection during opening");let i=this.connections.get(o.remotePeer);i==null&&(i=[],this.connections.set(o.remotePeer,i));let a=!1;for(let c of i)if(c.id===o.id&&(a=!0),t.force!==!0&&c.id!==o.id&&c.remoteAddr.equals(o.remoteAddr))return o.abort(new zn("Duplicate multiaddr connection")),c;return a||i.push(o),o}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async s=>{try{await Promise.all([De(s,"close",t),s.close(t)])}catch(o){s.abort(o)}}))}acceptIncomingConnection(e){if(this.deny.some(s=>{if(ft(e.remoteAddr)){let o=re(e.remoteAddr);return s.contains(o.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(s=>{if(ft(e.remoteAddr)){let o=re(e.remoteAddr);return s.contains(o.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(ft(e.remoteAddr)){let s=re(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(s.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>H(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var lz=1e4,uz="1.0.0",hz="ping",dz="ipfs",i8=32,fz=!0,Tp=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??dz}/${hz}/${uz}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??lz,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??fz,this.timeout=new Jd({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[je]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,W(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),s=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),o=a3(s);t=Date.now(),await Promise.all([o.write(Xn(i8),{signal:n}),o.read({bytes:i8,signal:n})]),e.rtt=Date.now()-t,await s.close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var _p=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()}),getAttributesFromYieldedValue:(n,s)=>({...s,providers:[...Array.isArray(s.providers)?s.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:C(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:C(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new la("No content routers available");let n=this,s=new io;for await(let o of Ss(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id)&&(s.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new la("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new la("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new yr;await Promise.all(this.routers.filter(s=>s.put instanceof Function).map(async s=>{await s.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new yr;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Pp=globalThis.CustomEvent??Event;async function*kb(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,s=new EventTarget,o=[],i=tt(),a=tt(),c=!1,l,u=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of r){if(o.length===t&&(i=tt(),await i.promise),u)break;let m={done:!1};o.push(m),h().then(g=>{m.done=!0,m.ok=!0,m.value=g,s.dispatchEvent(new Pp("task-complete"))},g=>{m.done=!0,m.err=g,s.dispatchEvent(new Pp("task-complete"))})}c=!0,s.dispatchEvent(new Pp("task-complete"))}catch(h){l=h,s.dispatchEvent(new Pp("task-complete"))}});function d(){return n?o[0]?.done:!!o.find(h=>h.done)}function*p(){for(;o.length>0&&o[0].done;){let h=o[0];if(o.shift(),h.ok)yield h.value;else throw u=!0,i.resolve(),h.err;i.resolve()}}function*f(){for(;d();)for(let h=0;h<o.length;h++)if(o[h].done){let m=o[h];if(o.splice(h,1),h--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(d()||(a=tt(),await a.promise),l!=null||(n?yield*p():yield*f(),l!=null))throw l;if(c&&o.length===0)break}}var Dp=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,key:C(n,"base36")}),getAttributesFromYieldedValue:(n,s)=>({...s,peers:[...Array.isArray(s.peers)?s.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Zl("No peer routers available");if(e.toString()===this.peerId.toString())throw new op("Should not try to find self");let n=this,s=Ss(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let o of s)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new Cs}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Zl("No peer routers available");let n=this,s=Gr(1024);for await(let o of kb((async function*(){let i=Ss(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!s.has(o.id.toMultihash().bytes)&&(s.add(o.id.toMultihash().bytes),yield o))}};function pz(r){return r.reason}async function su(r,e,t){if(e==null)return r;let n=t?.translateError??pz;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var kp=class extends he{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,W(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,W(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Dt([this.shutdownController.signal,e?.signal]);W(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=tt(),yield(await De(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,W(1/0,this.walkController.signal);let e=Dt([this.walkController.signal,this.shutdownController.signal]);W(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let s=Xn(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await su(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,n)}catch(s){this.log.error("random walk errored - %e",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("random walk errored - %e",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Lb=32,Mb=64,Lp=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,s]of this.topologies)t[n]=s.size;return t}}),this.handlers=xt({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new ip(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new ap(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:Lb,maxOutboundStreams:Mb,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(s=>{this.handlers.delete(s)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new N("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let s=await this.components.peerStore.get(t,n);for(let o of s.protocols){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t)!==!1&&(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(s){if(s.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,s)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,s=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));try{for(let o of s){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(o){this.log.error("could not inform topologies of updated peer %p - %e",t.id,o)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,s=e.detail.peerId;try{for(let o of t){let i=this.topologies.get(o);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),await a.onConnect?.(s,n))}))}}catch(o){this.log.error("could not inform topologies of updated peer after identify %p - %e",s,o)}}};var Mp=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=xt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=xt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ya.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new N("Transport must have a valid tag");if(this.transports.has(t))throw new N(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let s=n.pop();s!=null&&e.push(s.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new fp(`No transport available for address ${String(e)}`);return t?.onProgress?.(new Te("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new yr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(o=>{t.errors.set(o.toString(),new cp)});let n=[];for(let[o,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=u.findIndex(p=>p===l);u.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),qy.matches(c)?t.ipv4.attempts++:Vy.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),qy.matches(c)&&t.ipv4.success++,Vy.matches(c)&&t.ipv6.success++},d=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,d),t.errors.set(c.toString(),d),d}))}}let s=await Promise.allSettled(n);if(!(s.length>0&&s.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Ya.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new lp(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
21
21
  ${[...t.errors.entries()].map(([o,i])=>`
22
- ${o}: ${`${FH(i)}`.split(`
22
+ ${o}: ${`${mz(i)}`.split(`
23
23
  `).join(`
24
24
  `)}
25
- `).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let s=t.pop();s!=null&&n.push(s.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function FH(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}V();var fn="/multistream/1.0.0";V();re();V();re();ie();var zH=D(`
26
- `);async function Lu(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==zH[0])throw new Rt("Missing newline");return T(n).trimEnd()}async function Da(r,e,t={}){if(e=Array.isArray(e)?[...e]:[e],e.length===0)throw new Error("At least one protocol must be specified");let n=r.log.newScope("mss:select"),s=_s(r,{...t,maxDataLength:1024});for(let o=0;o<e.length;o++){let i=e[o],a;if(o===0){n.trace('write ["%s", "%s"]',fn,i);let c=D(`${fn}
27
- `),l=D(`${i}
28
- `);if(await s.writeV([c,l],t),n.trace("reading multistream-select header"),a=await Lu(s,t),n.trace('read "%s"',a),a!==fn){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await s.write(D(`${i}
29
- `),t);if(n.trace("reading protocol response"),a=await Lu(s,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),s.unwrap(),i}throw new Eh(`Protocol selection failed - could not negotiate ${e}`)}Be();re();async function ka(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),s=_s(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let o=await Lu(s,t);if(n.trace('read "%s"',o),o===fn){n.trace('respond with "%s" for "%s"',fn,o),await s.write(D(`${fn}
30
- `),t),n.trace('responded with "%s" for "%s"',fn,o);continue}if(e.includes(o))return n.trace('respond with "%s" for "%s"',o,o),await s.write(D(`${o}
31
- `),t),n.trace('responded with "%s" for "%s"',o,o),s.unwrap(),o;if(o==="ls"){let i=new U(...e.map(a=>yr.single(D(`${a}
32
- `))),D(`
33
- `));n.trace('respond with "%s" for %s',e,o),await s.write(i,t),n.trace('responded with "%s" for %s',e,o);continue}n.trace('respond with "na" for "%s"',o),await s.write(D(`na
34
- `),t),n('responded with "na" for "%s"',o)}}ke();Ue();V();Ue();var qw=class extends me{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Tw(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new as(n.local,n.error))})}[Symbol.toStringTag]="Connection";[X5]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new ks("Connection is not multiplexed");if(this.muxer.status!=="open")throw new zs(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new zs(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new fc("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);Y(1/0,a),t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Da(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let s=qH(n.protocol,this.components.registrar,t),o=NT(n.protocol,"outbound",this);if(o>s){let a=new Jo(`Too many outbound protocol streams for protocol "${n.protocol}" - ${o}/${s}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(s){throw n.status==="open"?n.abort(s):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,s),s}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Y(1/0,n),t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await ka(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let s=HH(t.protocol,this.components.registrar);if(NT(t.protocol,"inbound",this)>s)throw new Ah(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${s}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new fc("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,d)=>{await i(l,u),d(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(s){t.abort(s)}}async runMiddlewareChain(e,t,n){for(let s=0;s<n.length;s++){let o=n[s];e.log.trace("running middleware",s,o),await new Promise((i,a)=>{try{let c=o(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",s,o)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);Y(1/0,t),e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function BT(r,e){return new qw(r,e)}function HH(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return zw}function qH(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??$w}function NT(r,e,t){let n=0;return t.streams.forEach(s=>{s.direction===e&&s.protocol===r&&n++}),n}var f1=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Dt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Dt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new qp(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=zt([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return Y(1/0,t),t}async upgradeInbound(e,t){let n=!1,s=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Vp("Connection denied");await ku(this.shouldBlockConnection("denyInboundConnection",e),s),await this._performUpgrade(e,"inbound",{...t,signal:s})}catch(o){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[o.name??"Error"]:!0}),o}finally{s.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,s;n!=null&&(s=de(n),await ku(this.shouldBlockConnection("denyOutboundConnection",s,e),t.signal));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let s=e,o,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),s=await d.protect(s,n))}try{if(VH(n)){if(n.remotePeer==null)throw new ss(`${t} connection that skipped encryption must have a peer id`);c="native",o=n.remotePeer}else{let d=e.remoteAddr.getComponents().findLast(f=>f.code===421)?.value,p;d!=null&&(p=de(d)),n?.onProgress?.(new Le(`upgrader:encrypt-${t}-connection`)),{connection:s,remotePeer:o,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(s,{...n,remotePeer:p}):this._encryptOutbound(s,{...n,remotePeer:p}))}if(o.equals(this.components.peerId)){let d=new Qo("Can not dial self");throw e.abort(d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new Le(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(s,this.streamMuxers,n):this._multiplexOutbound(s,this.streamMuxers,n)))}catch(d){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,d),d}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(s)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:s,muxer:a,remotePeer:o,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=BT(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let s=await ka(e,n,t),o=this.connectionEncrypters.get(s);if(o==null)throw new zo(`no crypto module found for ${s}`);return e.log("encrypting inbound connection using %s",s),{...await o.secureInbound(e,t),protocol:s}}catch(s){throw new zo(s.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let s=await Da(e,n,t),o=this.connectionEncrypters.get(s);if(o==null)throw new zo(`no crypto module found for ${s}`);return e.log("encrypting outbound connection using %s",s),{...await o.secureOutbound(e,t),protocol:s}}catch(s){throw new zo(s.message)}}async _multiplexOutbound(e,t,n){let s=Array.from(t.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);let o=await Da(e,s,n),i=t.get(o);if(i==null)throw new ks(`No muxer configured for protocol "${o}"`);return e.log("selected %s as muxer protocol",o),i}catch(o){throw e.log.error("error multiplexing outbound connection - %e",o),new ks(String(o))}}async _multiplexInbound(e,t,n){let s=Array.from(t.keys());e.log("inbound handling muxers %s",s);try{e.log.trace("selecting stream muxer from %s",s);let o=await ka(e,s,n),i=t.get(o);if(i==null)throw new ks(`No muxer configured for protocol "${o}"`);return e.log("selected %s as muxer protocol",o),i}catch(o){throw e.log.error("error multiplexing inbound connection - %e",o),o}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function VH(r){return r.skipEncryption===!0}var Ls=ae(te("node:process"),1);var p1="3.1.3",m1="js-libp2p";function KT(r,e){let t="node",n=Ls.default.versions.node;return Ls.default.versions.deno!=null&&(t="deno",n=Ls.default.versions.deno),Ls.default.versions.bun!=null&&(t="bun",n=Ls.default.versions.bun),Ls.default.versions.electron!=null&&(t="electron",n=Ls.default.versions.electron),`${r??m1}/${e??p1} ${t}/${n.replaceAll("v","")}`}var g1=class extends me{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new me,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},Y(1/0,t),this.peerId=e.peerId,this.logger=e.logger??hp(),this.log=this.logger.forComponent("libp2p"),this.services={};let s=e.nodeInfo?.name??m1,o=e.nodeInfo?.version??p1,i=this.components=mT({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:s,version:o,userAgent:e.nodeInfo?.userAgent??KT(s,o)},logger:this.logger,events:t,datastore:e.datastore??new Dp,connectionGater:yT(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",lT(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new f1(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new d1(this.components,e.transportManager)),this.configureComponent("connectionManager",new o1(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new i1(this.components,e.connectionMonitor)),this.configureComponent("registrar",new h1(this.components)),this.configureComponent("addressManager",new Rp(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new l1(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new a1(this.components,{routers:c})),this.configureComponent("randomWalk",new u1(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",p=>{this.#e(p)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[Mm]!=null&&(this.log("registering service %s for content routing",l),c.push(d[Mm])),d[Om]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[Om])),d[pc]!=null&&(this.log("registering service %s for peer discovery",l),d[pc].addEventListener?.("peer",p=>{this.#e(p)}))}gT(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Io;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new B("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new B("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){As(e)&&(e=de(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ee([D("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(n,t),o=Ft(s);return await this.peerStore.patch(e,{publicKey:o},t),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function FT(r={}){r.privateKey??=await dE("Ed25519");let e=new g1({...await bC(r),peerId:q2(r.privateKey)});return r.start!==!1&&await e.start(),e}Bt();V();ke();rt();var La=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Vw=16;var yn=ae(te("node:crypto"),1),_1=ae(WT(),1);var lq=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,jT=lq?hq:uq;function uq(r=0){return new Uint8Array(r)}function hq(r=0){let e=Buffer.allocUnsafe(r);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var YT=Uint8Array.from([0,97,115,109,1,0,0,0,1,43,8,96,2,127,127,0,96,1,127,0,96,1,127,1,127,96,2,127,127,1,127,96,0,0,96,3,127,127,127,0,96,4,127,127,127,127,0,96,3,127,127,126,0,2,13,1,3,101,110,118,5,97,98,111,114,116,0,6,3,23,22,0,0,0,0,0,7,2,3,3,2,4,5,1,2,5,0,1,1,0,1,1,4,5,3,1,0,1,6,187,1,37,127,0,65,4,11,127,0,65,128,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,0,11,7,169,1,13,8,72,65,83,95,83,73,77,68,3,36,22,98,97,116,99,104,72,97,115,104,52,85,105,110,116,65,114,114,97,121,54,52,115,0,17,26,98,97,116,99,104,72,97,115,104,52,72,97,115,104,79,98,106,101,99,116,73,110,112,117,116,115,0,18,12,73,78,80,85,84,95,76,69,78,71,84,72,3,1,15,80,65,82,65,76,76,69,76,95,70,65,67,84,79,82,3,0,5,105,110,112,117,116,3,30,6,111,117,116,112,117,116,3,32,4,105,110,105,116,0,11,6,117,112,100,97,116,101,0,19,5,102,105,110,97,108,0,20,6,100,105,103,101,115,116,0,21,8,100,105,103,101,115,116,54,52,0,16,6,109,101,109,111,114,121,2,0,8,1,22,12,1,18,10,153,23,22,9,0,32,0,32,1,54,2,0,11,9,0,32,0,32,1,54,2,4,11,9,0,32,0,32,1,54,2,8,11,192,1,1,4,127,32,1,40,2,0,65,124,113,34,3,65,128,2,73,4,127,32,3,65,4,118,5,65,31,65,252,255,255,255,3,32,3,32,3,65,252,255,255,255,3,79,27,34,3,103,107,34,4,65,7,107,33,2,32,3,32,4,65,4,107,118,65,16,115,11,33,3,32,1,40,2,8,33,5,32,1,40,2,4,34,4,4,64,32,4,32,5,16,3,11,32,5,4,64,32,5,32,4,16,2,11,32,1,32,0,32,2,65,4,116,32,3,106,65,2,116,106,34,1,40,2,96,70,4,64,32,1,32,5,54,2,96,32,5,69,4,64,32,0,32,2,65,2,116,106,34,1,40,2,4,65,126,32,3,119,113,33,3,32,1,32,3,54,2,4,32,3,69,4,64,32,0,32,0,40,2,0,65,126,32,2,119,113,16,1,11,11,11,11,181,2,1,5,127,32,1,40,2,0,33,3,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,2,65,1,113,4,64,32,0,32,4,16,4,32,1,32,3,65,4,106,32,2,65,124,113,106,34,3,16,1,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,2,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,1,40,2,0,33,6,32,0,32,1,16,4,32,1,32,6,65,4,106,32,3,65,124,113,106,34,3,16,1,11,32,4,32,2,65,2,114,16,1,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,5,65,31,65,252,255,255,255,3,32,2,32,2,65,252,255,255,255,3,79,27,34,2,103,107,34,3,65,7,107,33,5,32,2,32,3,65,4,107,118,65,16,115,11,34,2,32,5,65,4,116,106,65,2,116,106,40,2,96,33,3,32,1,65,0,16,2,32,1,32,3,16,3,32,3,4,64,32,3,32,1,16,2,11,32,0,32,5,65,4,116,32,2,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,5,116,114,16,1,32,0,32,5,65,2,116,106,34,0,32,0,40,2,4,65,1,32,2,116,114,54,2,4,11,130,1,1,3,127,32,1,65,19,106,65,112,113,65,4,107,33,1,32,0,40,2,160,12,34,3,4,64,32,3,32,1,65,16,107,34,5,70,4,64,32,3,40,2,0,33,4,32,5,33,1,11,11,32,2,167,65,112,113,32,1,107,34,3,65,20,73,4,64,15,11,32,1,32,4,65,2,113,32,3,65,8,107,34,3,65,1,114,114,16,1,32,1,65,0,16,2,32,1,65,0,16,3,32,1,65,4,106,32,3,106,34,3,65,2,16,1,32,0,32,3,54,2,160,12,32,0,32,1,16,5,11,29,0,32,0,65,1,65,27,32,0,103,107,116,106,65,1,107,32,0,32,0,65,254,255,255,255,1,73,27,11,142,1,1,2,127,32,1,65,128,2,73,4,127,32,1,65,4,118,5,65,31,32,1,16,7,34,1,103,107,34,3,65,7,107,33,2,32,1,32,3,65,4,107,118,65,16,115,11,33,1,32,0,32,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,148,2,1,3,127,32,1,65,252,255,255,255,3,75,4,64,65,176,14,65,176,15,65,205,3,65,29,16,0,0,11,32,0,65,12,32,1,65,19,106,65,112,113,65,4,107,32,1,65,12,77,27,34,1,16,8,34,2,69,4,64,32,1,65,128,2,79,4,127,32,1,16,7,5,32,1,11,33,2,63,0,34,3,32,2,65,4,32,0,40,2,160,12,32,3,65,16,116,65,4,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,2,32,2,32,3,72,27,64,0,65,0,72,4,64,32,2,64,0,65,0,72,4,64,0,11,11,32,0,32,3,65,16,116,63,0,172,66,16,134,16,6,32,0,32,1,16,8,33,2,11,32,2,40,2,0,26,32,0,32,2,16,4,32,2,40,2,0,34,3,65,124,113,32,1,107,34,4,65,16,79,4,64,32,2,32,1,32,3,65,2,113,114,16,1,32,2,65,4,106,32,1,106,34,1,32,4,65,4,107,65,1,114,16,1,32,0,32,1,16,5,5,32,2,32,3,65,126,113,16,1,32,2,65,4,106,32,2,40,2,0,65,124,113,106,34,0,32,0,40,2,0,65,125,113,16,1,11,32,2,11,169,2,1,3,127,32,0,65,252,255,255,255,3,75,4,64,65,192,13,65,240,13,65,52,65,43,16,0,0,11,32,0,65,236,255,255,255,3,75,4,64,65,176,14,65,240,14,65,253,0,65,30,16,0,0,11,35,23,69,4,64,63,0,34,2,65,0,76,4,127,65,1,32,2,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,128,16,65,0,16,1,65,160,28,65,0,54,2,0,3,64,32,1,65,23,73,4,64,32,1,65,2,116,65,128,16,106,65,0,54,2,4,65,0,33,2,3,64,32,2,65,16,73,4,64,32,1,65,4,116,32,2,106,65,2,116,65,128,16,106,65,0,54,2,96,32,2,65,1,106,33,2,12,1,11,11,32,1,65,1,106,33,1,12,1,11,11,65,128,16,65,164,28,63,0,172,66,16,134,16,6,65,128,16,36,23,11,35,23,32,0,65,16,106,16,9,34,2,65,1,54,2,12,32,2,32,0,54,2,16,35,24,34,3,40,2,8,33,1,32,2,32,3,16,2,32,2,32,1,16,3,32,1,32,2,32,1,40,2,4,65,3,113,114,16,2,32,3,32,2,16,3,35,25,32,2,40,2,0,65,124,113,65,4,106,106,36,25,32,2,65,20,106,34,1,65,0,32,0,252,11,0,32,1,11,74,0,65,231,204,167,208,6,36,4,65,133,221,158,219,123,36,5,65,242,230,187,227,3,36,6,65,186,234,191,170,122,36,7,65,255,164,185,136,5,36,8,65,140,209,149,216,121,36,9,65,171,179,143,252,1,36,10,65,153,154,131,223,5,36,11,65,0,36,34,65,0,36,35,11,233,3,1,1,127,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,35,8,36,16,35,9,36,17,35,10,36,18,35,11,36,19,65,0,36,20,3,64,35,20,65,16,73,4,64,32,0,35,20,65,2,116,106,32,1,35,20,32,2,108,65,2,116,34,3,65,3,106,106,45,0,0,32,1,32,3,106,45,0,0,65,24,116,32,1,32,3,65,1,106,106,45,0,0,65,16,116,114,32,1,32,3,65,2,106,106,45,0,0,65,8,116,114,114,54,2,0,35,20,65,1,106,36,20,12,1,11,11,65,16,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,106,32,0,35,20,65,16,107,65,2,116,106,40,2,0,32,0,35,20,65,7,107,65,2,116,106,40,2,0,32,0,35,20,65,2,107,65,2,116,106,40,2,0,34,1,65,17,120,32,1,65,19,120,115,32,1,65,10,118,115,106,32,0,35,20,65,15,107,65,2,116,106,40,2,0,34,1,65,7,120,32,1,65,18,120,115,32,1,65,3,118,115,106,106,54,2,0,35,20,65,1,106,36,20,12,1,11,11,65,0,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,34,1,106,40,2,0,32,1,35,2,106,40,2,0,35,19,35,16,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,16,34,1,35,17,113,35,18,32,1,65,127,115,113,115,106,106,106,36,21,35,12,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,13,34,1,35,14,34,2,113,32,1,35,12,34,1,113,32,1,32,2,113,115,115,106,36,22,35,18,36,19,35,17,36,18,35,16,36,17,35,15,35,21,106,36,16,35,14,36,15,35,13,36,14,35,12,36,13,35,21,35,22,106,36,12,35,20,65,1,106,36,20,12,1,11,11,35,4,35,12,106,36,4,35,5,35,13,106,36,5,35,6,35,14,106,36,6,35,7,35,15,106,36,7,35,8,35,16,106,36,8,35,9,35,17,106,36,9,35,10,35,18,106,36,10,35,11,35,19,106,36,11,11,253,1,1,2,127,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,35,8,36,16,35,9,36,17,35,10,36,18,35,11,36,19,65,0,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,106,40,2,0,35,19,35,16,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,16,34,1,35,17,113,35,18,32,1,65,127,115,113,115,106,106,36,21,35,12,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,13,34,2,35,14,34,1,113,32,2,35,12,34,2,113,32,1,32,2,113,115,115,106,36,22,35,18,36,19,35,17,36,18,35,16,36,17,35,15,35,21,106,36,16,35,14,36,15,35,13,36,14,35,12,36,13,35,21,35,22,106,36,12,35,20,65,1,106,36,20,12,1,11,11,35,4,35,12,106,36,4,35,5,35,13,106,36,5,35,6,35,14,106,36,6,35,7,35,15,106,36,7,35,8,35,16,106,36,8,35,9,35,17,106,36,9,35,10,35,18,106,36,10,35,11,35,19,106,36,11,11,25,0,32,0,65,128,254,131,120,113,65,8,119,32,0,65,255,129,252,7,113,65,8,120,114,11,88,0,16,11,35,29,32,0,32,2,16,12,35,3,16,13,32,1,35,4,16,14,54,2,0,32,1,35,5,16,14,54,2,4,32,1,35,6,16,14,54,2,8,32,1,35,7,16,14,54,2,12,32,1,35,8,16,14,54,2,16,32,1,35,9,16,14,54,2,20,32,1,35,10,16,14,54,2,24,32,1,35,11,16,14,54,2,28,11,10,0,32,0,32,1,65,1,16,15,11,42,1,1,127,3,64,32,1,65,4,72,4,64,35,31,32,1,65,6,116,106,32,0,32,1,65,5,116,106,16,16,32,1,65,1,106,33,1,12,1,11,11,11,44,1,1,127,3,64,32,1,65,4,72,4,64,35,31,32,1,65,2,116,106,32,0,32,1,65,5,116,106,65,4,16,15,32,1,65,1,106,33,1,12,1,11,11,11,178,1,1,2,127,35,35,32,1,106,36,35,35,34,4,64,65,192,0,35,34,107,34,2,32,1,76,4,64,35,27,35,34,106,32,0,32,2,252,10,0,0,35,34,32,2,106,36,34,65,192,0,35,34,107,33,2,32,1,65,192,0,35,34,107,107,33,1,35,29,35,27,65,1,16,12,65,0,36,34,5,35,27,35,34,106,32,0,32,1,252,10,0,0,35,34,32,1,106,36,34,15,11,11,3,64,32,3,32,1,65,192,0,109,72,4,64,35,29,32,0,32,2,106,65,1,16,12,32,3,65,1,106,33,3,32,2,65,64,107,33,2,12,1,11,11,32,1,65,63,113,34,1,4,64,35,27,35,34,106,32,0,32,2,106,32,1,252,10,0,0,35,34,32,1,106,36,34,11,11,235,1,1,2,127,35,27,35,34,106,65,128,1,58,0,0,35,34,65,1,106,36,34,35,34,65,56,74,4,64,35,27,35,34,106,34,1,65,192,0,35,34,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,27,65,1,16,12,65,0,36,34,11,35,27,35,34,106,34,1,65,56,35,34,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,27,35,35,65,128,128,128,128,2,109,16,14,54,2,56,35,27,35,35,65,3,116,16,14,54,2,60,35,29,35,27,65,1,16,12,32,0,35,4,16,14,54,2,0,32,0,35,5,16,14,54,2,4,32,0,35,6,16,14,54,2,8,32,0,35,7,16,14,54,2,12,32,0,35,8,16,14,54,2,16,32,0,35,9,16,14,54,2,20,32,0,35,10,16,14,54,2,24,32,0,35,11,16,14,54,2,28,11,14,0,16,11,35,31,32,0,16,19,35,33,16,20,11,82,0,65,196,10,40,2,0,36,2,65,148,13,40,2,0,36,3,65,224,15,65,224,15,16,2,65,224,15,65,224,15,16,3,65,224,15,36,24,65,192,0,16,10,36,26,35,26,36,27,65,128,8,16,10,36,28,35,28,36,29,65,128,4,16,10,36,30,35,30,36,31,65,32,16,10,36,32,35,32,36,33,11,11,253,6,18,0,65,140,8,11,2,28,1,0,65,152,8,11,136,2,1,0,0,0,0,1,0,0,152,47,138,66,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,241,155,193,193,105,155,228,134,71,190,239,198,157,193,15,204,161,12,36,111,44,233,45,170,132,116,74,220,169,176,92,218,136,249,118,82,81,62,152,109,198,49,168,200,39,3,176,199,127,89,191,243,11,224,198,71,145,167,213,81,99,202,6,103,41,41,20,133,10,183,39,56,33,27,46,252,109,44,77,19,13,56,83,84,115,10,101,187,10,106,118,46,201,194,129,133,44,114,146,161,232,191,162,75,102,26,168,112,139,75,194,163,81,108,199,25,232,146,209,36,6,153,214,133,53,14,244,112,160,106,16,22,193,164,25,8,108,55,30,76,119,72,39,181,188,176,52,179,12,28,57,74,170,216,78,79,202,156,91,243,111,46,104,238,130,143,116,111,99,165,120,20,120,200,132,8,2,199,140,250,255,190,144,235,108,80,164,247,163,249,190,242,120,113,198,0,65,172,10,11,1,44,0,65,184,10,11,21,4,0,0,0,16,0,0,0,32,4,0,0,32,4,0,0,0,1,0,0,64,0,65,220,10,11,2,28,1,0,65,232,10,11,136,2,1,0,0,0,0,1,0,0,152,47,138,194,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,243,155,193,193,105,155,100,134,71,254,240,198,237,225,15,84,242,12,36,111,52,233,79,190,132,201,108,30,65,185,97,250,136,249,22,82,81,198,242,109,90,142,168,101,252,25,176,199,158,217,185,195,49,18,154,160,234,14,231,43,35,177,253,176,62,53,199,213,186,105,48,95,109,151,203,143,17,15,90,253,238,30,220,137,182,53,10,4,122,11,222,157,202,244,88,22,91,93,225,134,62,127,0,128,137,8,55,50,234,7,165,55,149,171,111,16,97,64,23,241,214,140,13,109,59,170,205,55,190,187,192,218,59,97,131,99,163,72,219,49,233,2,11,167,92,209,111,202,250,26,82,49,132,51,49,149,26,212,110,144,120,67,109,242,145,156,195,189,171,204,158,230,160,201,181,60,182,47,83,198,65,199,210,163,126,35,7,104,75,149,164,118,29,25,76,0,65,252,12,11,1,44,0,65,136,13,11,21,4,0,0,0,16,0,0,0,112,5,0,0,112,5,0,0,0,1,0,0,64,0,65,172,13,11,1,44,0,65,184,13,11,35,2,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,220,13,11,1,60,0,65,232,13,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,156,14,11,1,60,0,65,168,14,11,47,2,0,0,0,40,0,0,0,65,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,220,14,11,1,60,0,65,232,14,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,99,0,109,0,115,0,46,0,116,0,115,0,65,156,15,11,1,60,0,65,168,15,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115]);var Qw=Uint8Array.from([0,97,115,109,1,0,0,0,1,37,7,96,2,127,127,0,96,1,127,1,127,96,2,127,127,1,127,96,1,127,0,96,0,0,96,4,127,127,127,127,0,96,3,127,127,126,0,2,13,1,3,101,110,118,5,97,98,111,114,116,0,5,3,30,29,0,0,0,0,0,6,1,2,2,2,1,2,1,1,2,4,4,1,0,3,3,4,0,0,3,3,3,0,4,5,3,1,0,1,6,227,4,61,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,127,1,65,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,4,11,127,0,65,128,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,1,11,7,169,1,13,8,72,65,83,95,83,73,77,68,3,60,22,98,97,116,99,104,72,97,115,104,52,85,105,110,116,65,114,114,97,121,54,52,115,0,20,26,98,97,116,99,104,72,97,115,104,52,72,97,115,104,79,98,106,101,99,116,73,110,112,117,116,115,0,21,12,73,78,80,85,84,95,76,69,78,71,84,72,3,28,15,80,65,82,65,76,76,69,76,95,70,65,67,84,79,82,3,27,5,105,110,112,117,116,3,54,6,111,117,116,112,117,116,3,56,4,105,110,105,116,0,22,6,117,112,100,97,116,101,0,24,5,102,105,110,97,108,0,25,6,100,105,103,101,115,116,0,26,8,100,105,103,101,115,116,54,52,0,28,6,109,101,109,111,114,121,2,0,8,1,29,12,1,38,10,243,111,29,9,0,32,0,32,1,54,2,0,11,9,0,32,0,32,1,54,2,4,11,9,0,32,0,32,1,54,2,8,11,192,1,1,4,127,32,1,40,2,0,65,124,113,34,3,65,128,2,73,4,127,32,3,65,4,118,5,65,31,65,252,255,255,255,3,32,3,32,3,65,252,255,255,255,3,79,27,34,3,103,107,34,4,65,7,107,33,2,32,3,32,4,65,4,107,118,65,16,115,11,33,3,32,1,40,2,8,33,5,32,1,40,2,4,34,4,4,64,32,4,32,5,16,3,11,32,5,4,64,32,5,32,4,16,2,11,32,1,32,0,32,2,65,4,116,32,3,106,65,2,116,106,34,1,40,2,96,70,4,64,32,1,32,5,54,2,96,32,5,69,4,64,32,0,32,2,65,2,116,106,34,1,40,2,4,65,126,32,3,119,113,33,3,32,1,32,3,54,2,4,32,3,69,4,64,32,0,32,0,40,2,0,65,126,32,2,119,113,16,1,11,11,11,11,181,2,1,5,127,32,1,40,2,0,33,3,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,2,65,1,113,4,64,32,0,32,4,16,4,32,1,32,3,65,4,106,32,2,65,124,113,106,34,3,16,1,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,2,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,1,40,2,0,33,6,32,0,32,1,16,4,32,1,32,6,65,4,106,32,3,65,124,113,106,34,3,16,1,11,32,4,32,2,65,2,114,16,1,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,5,65,31,65,252,255,255,255,3,32,2,32,2,65,252,255,255,255,3,79,27,34,2,103,107,34,3,65,7,107,33,5,32,2,32,3,65,4,107,118,65,16,115,11,34,2,32,5,65,4,116,106,65,2,116,106,40,2,96,33,3,32,1,65,0,16,2,32,1,32,3,16,3,32,3,4,64,32,3,32,1,16,2,11,32,0,32,5,65,4,116,32,2,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,5,116,114,16,1,32,0,32,5,65,2,116,106,34,0,32,0,40,2,4,65,1,32,2,116,114,54,2,4,11,130,1,1,3,127,32,1,65,19,106,65,112,113,65,4,107,33,1,32,0,40,2,160,12,34,3,4,64,32,3,32,1,65,16,107,34,5,70,4,64,32,3,40,2,0,33,4,32,5,33,1,11,11,32,2,167,65,112,113,32,1,107,34,3,65,20,73,4,64,15,11,32,1,32,4,65,2,113,32,3,65,8,107,34,3,65,1,114,114,16,1,32,1,65,0,16,2,32,1,65,0,16,3,32,1,65,4,106,32,3,106,34,3,65,2,16,1,32,0,32,3,54,2,160,12,32,0,32,1,16,5,11,29,0,32,0,65,1,65,27,32,0,103,107,116,106,65,1,107,32,0,32,0,65,254,255,255,255,1,73,27,11,142,1,1,2,127,32,1,65,128,2,73,4,127,32,1,65,4,118,5,65,31,32,1,16,7,34,1,103,107,34,3,65,7,107,33,2,32,1,32,3,65,4,107,118,65,16,115,11,33,1,32,0,32,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,148,2,1,3,127,32,1,65,252,255,255,255,3,75,4,64,65,176,14,65,176,15,65,205,3,65,29,16,0,0,11,32,0,65,12,32,1,65,19,106,65,112,113,65,4,107,32,1,65,12,77,27,34,1,16,8,34,2,69,4,64,32,1,65,128,2,79,4,127,32,1,16,7,5,32,1,11,33,2,63,0,34,3,32,2,65,4,32,0,40,2,160,12,32,3,65,16,116,65,4,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,2,32,2,32,3,72,27,64,0,65,0,72,4,64,32,2,64,0,65,0,72,4,64,0,11,11,32,0,32,3,65,16,116,63,0,172,66,16,134,16,6,32,0,32,1,16,8,33,2,11,32,2,40,2,0,26,32,0,32,2,16,4,32,2,40,2,0,34,3,65,124,113,32,1,107,34,4,65,16,79,4,64,32,2,32,1,32,3,65,2,113,114,16,1,32,2,65,4,106,32,1,106,34,1,32,4,65,4,107,65,1,114,16,1,32,0,32,1,16,5,5,32,2,32,3,65,126,113,16,1,32,2,65,4,106,32,2,40,2,0,65,124,113,106,34,0,32,0,40,2,0,65,125,113,16,1,11,32,2,11,133,2,1,2,127,32,0,65,236,255,255,255,3,75,4,64,65,176,14,65,240,14,65,253,0,65,30,16,0,0,11,35,20,69,4,64,63,0,34,3,65,0,76,4,127,65,1,32,3,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,208,21,65,0,16,1,65,240,33,65,0,54,2,0,3,64,32,2,65,23,73,4,64,32,2,65,2,116,65,208,21,106,65,0,54,2,4,65,0,33,3,3,64,32,3,65,16,73,4,64,32,2,65,4,116,32,3,106,65,2,116,65,208,21,106,65,0,54,2,96,32,3,65,1,106,33,3,12,1,11,11,32,2,65,1,106,33,2,12,1,11,11,65,208,21,65,244,33,63,0,172,66,16,134,16,6,65,208,21,36,20,11,35,20,32,0,65,16,106,16,9,34,2,32,1,54,2,12,32,2,32,0,54,2,16,35,21,34,0,40,2,8,33,1,32,2,32,0,16,2,32,2,32,1,16,3,32,1,32,2,32,1,40,2,4,65,3,113,114,16,2,32,0,32,2,16,3,35,22,32,2,40,2,0,65,124,113,65,4,106,106,36,22,32,2,65,20,106,11,46,1,1,127,32,0,65,252,255,255,255,3,75,4,64,65,192,13,65,240,13,65,52,65,43,16,0,0,11,32,0,65,1,16,10,34,1,65,0,32,0,252,11,0,32,1,11,41,0,32,1,32,0,40,2,12,79,4,64,65,144,16,65,208,16,65,242,0,65,42,16,0,0,11,32,0,40,2,4,32,1,65,2,116,106,40,2,0,11,181,1,1,4,127,32,0,69,4,64,65,192,18,15,11,65,0,32,0,107,32,0,32,0,65,31,118,65,1,116,34,1,27,34,0,65,10,79,65,1,106,32,0,65,144,206,0,79,65,3,106,32,0,65,232,7,79,106,32,0,65,228,0,73,27,32,0,65,192,132,61,79,65,6,106,32,0,65,128,148,235,220,3,79,65,8,106,32,0,65,128,194,215,47,79,106,32,0,65,128,173,226,4,73,27,32,0,65,160,141,6,73,27,34,2,65,1,116,32,1,106,65,2,16,10,34,3,32,1,106,33,4,3,64,32,4,32,2,65,1,107,34,2,65,1,116,106,32,0,65,10,112,65,48,106,59,1,0,32,0,65,10,110,34,0,13,0,11,32,1,4,64,32,3,65,45,59,1,0,11,32,3,11,13,0,32,0,65,20,107,40,2,16,65,1,118,11,64,1,3,127,32,0,16,14,65,1,116,34,2,32,1,16,14,65,1,116,34,3,106,34,4,69,4,64,65,160,20,15,11,32,4,65,2,16,10,34,4,32,0,32,2,252,10,0,0,32,2,32,4,106,32,1,32,3,252,10,0,0,32,4,11,145,16,2,2,127,1,123,65,224,15,65,224,15,16,2,65,224,15,65,224,15,16,3,65,224,15,36,21,65,128,8,16,11,36,23,35,23,36,24,2,64,3,64,32,0,65,192,0,72,4,64,35,24,33,1,65,192,10,32,0,16,12,253,17,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,32,0,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,67,11,32,1,32,2,253,11,4,0,12,63,11,32,1,32,2,253,11,4,16,12,62,11,32,1,32,2,253,11,4,32,12,61,11,32,1,32,2,253,11,4,48,12,60,11,32,1,32,2,253,11,4,64,12,59,11,32,1,32,2,253,11,4,80,12,58,11,32,1,32,2,253,11,4,96,12,57,11,32,1,32,2,253,11,4,112,12,56,11,32,1,32,2,253,11,4,128,1,12,55,11,32,1,32,2,253,11,4,144,1,12,54,11,32,1,32,2,253,11,4,160,1,12,53,11,32,1,32,2,253,11,4,176,1,12,52,11,32,1,32,2,253,11,4,192,1,12,51,11,32,1,32,2,253,11,4,208,1,12,50,11,32,1,32,2,253,11,4,224,1,12,49,11,32,1,32,2,253,11,4,240,1,12,48,11,32,1,32,2,253,11,4,128,2,12,47,11,32,1,32,2,253,11,4,144,2,12,46,11,32,1,32,2,253,11,4,160,2,12,45,11,32,1,32,2,253,11,4,176,2,12,44,11,32,1,32,2,253,11,4,192,2,12,43,11,32,1,32,2,253,11,4,208,2,12,42,11,32,1,32,2,253,11,4,224,2,12,41,11,32,1,32,2,253,11,4,240,2,12,40,11,32,1,32,2,253,11,4,128,3,12,39,11,32,1,32,2,253,11,4,144,3,12,38,11,32,1,32,2,253,11,4,160,3,12,37,11,32,1,32,2,253,11,4,176,3,12,36,11,32,1,32,2,253,11,4,192,3,12,35,11,32,1,32,2,253,11,4,208,3,12,34,11,32,1,32,2,253,11,4,224,3,12,33,11,32,1,32,2,253,11,4,240,3,12,32,11,32,1,32,2,253,11,4,128,4,12,31,11,32,1,32,2,253,11,4,144,4,12,30,11,32,1,32,2,253,11,4,160,4,12,29,11,32,1,32,2,253,11,4,176,4,12,28,11,32,1,32,2,253,11,4,192,4,12,27,11,32,1,32,2,253,11,4,208,4,12,26,11,32,1,32,2,253,11,4,224,4,12,25,11,32,1,32,2,253,11,4,240,4,12,24,11,32,1,32,2,253,11,4,128,5,12,23,11,32,1,32,2,253,11,4,144,5,12,22,11,32,1,32,2,253,11,4,160,5,12,21,11,32,1,32,2,253,11,4,176,5,12,20,11,32,1,32,2,253,11,4,192,5,12,19,11,32,1,32,2,253,11,4,208,5,12,18,11,32,1,32,2,253,11,4,224,5,12,17,11,32,1,32,2,253,11,4,240,5,12,16,11,32,1,32,2,253,11,4,128,6,12,15,11,32,1,32,2,253,11,4,144,6,12,14,11,32,1,32,2,253,11,4,160,6,12,13,11,32,1,32,2,253,11,4,176,6,12,12,11,32,1,32,2,253,11,4,192,6,12,11,11,32,1,32,2,253,11,4,208,6,12,10,11,32,1,32,2,253,11,4,224,6,12,9,11,32,1,32,2,253,11,4,240,6,12,8,11,32,1,32,2,253,11,4,128,7,12,7,11,32,1,32,2,253,11,4,144,7,12,6,11,32,1,32,2,253,11,4,160,7,12,5,11,32,1,32,2,253,11,4,176,7,12,4,11,32,1,32,2,253,11,4,192,7,12,3,11,32,1,32,2,253,11,4,208,7,12,2,11,32,1,32,2,253,11,4,224,7,12,1,11,32,1,32,2,253,11,4,240,7,11,32,0,65,1,106,33,0,12,1,11,11,65,128,8,16,11,36,25,35,25,36,26,65,0,33,0,3,64,32,0,65,192,0,72,4,64,35,26,33,1,65,144,13,32,0,16,12,253,17,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,32,0,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,67,11,32,1,32,2,253,11,4,0,12,63,11,32,1,32,2,253,11,4,16,12,62,11,32,1,32,2,253,11,4,32,12,61,11,32,1,32,2,253,11,4,48,12,60,11,32,1,32,2,253,11,4,64,12,59,11,32,1,32,2,253,11,4,80,12,58,11,32,1,32,2,253,11,4,96,12,57,11,32,1,32,2,253,11,4,112,12,56,11,32,1,32,2,253,11,4,128,1,12,55,11,32,1,32,2,253,11,4,144,1,12,54,11,32,1,32,2,253,11,4,160,1,12,53,11,32,1,32,2,253,11,4,176,1,12,52,11,32,1,32,2,253,11,4,192,1,12,51,11,32,1,32,2,253,11,4,208,1,12,50,11,32,1,32,2,253,11,4,224,1,12,49,11,32,1,32,2,253,11,4,240,1,12,48,11,32,1,32,2,253,11,4,128,2,12,47,11,32,1,32,2,253,11,4,144,2,12,46,11,32,1,32,2,253,11,4,160,2,12,45,11,32,1,32,2,253,11,4,176,2,12,44,11,32,1,32,2,253,11,4,192,2,12,43,11,32,1,32,2,253,11,4,208,2,12,42,11,32,1,32,2,253,11,4,224,2,12,41,11,32,1,32,2,253,11,4,240,2,12,40,11,32,1,32,2,253,11,4,128,3,12,39,11,32,1,32,2,253,11,4,144,3,12,38,11,32,1,32,2,253,11,4,160,3,12,37,11,32,1,32,2,253,11,4,176,3,12,36,11,32,1,32,2,253,11,4,192,3,12,35,11,32,1,32,2,253,11,4,208,3,12,34,11,32,1,32,2,253,11,4,224,3,12,33,11,32,1,32,2,253,11,4,240,3,12,32,11,32,1,32,2,253,11,4,128,4,12,31,11,32,1,32,2,253,11,4,144,4,12,30,11,32,1,32,2,253,11,4,160,4,12,29,11,32,1,32,2,253,11,4,176,4,12,28,11,32,1,32,2,253,11,4,192,4,12,27,11,32,1,32,2,253,11,4,208,4,12,26,11,32,1,32,2,253,11,4,224,4,12,25,11,32,1,32,2,253,11,4,240,4,12,24,11,32,1,32,2,253,11,4,128,5,12,23,11,32,1,32,2,253,11,4,144,5,12,22,11,32,1,32,2,253,11,4,160,5,12,21,11,32,1,32,2,253,11,4,176,5,12,20,11,32,1,32,2,253,11,4,192,5,12,19,11,32,1,32,2,253,11,4,208,5,12,18,11,32,1,32,2,253,11,4,224,5,12,17,11,32,1,32,2,253,11,4,240,5,12,16,11,32,1,32,2,253,11,4,128,6,12,15,11,32,1,32,2,253,11,4,144,6,12,14,11,32,1,32,2,253,11,4,160,6,12,13,11,32,1,32,2,253,11,4,176,6,12,12,11,32,1,32,2,253,11,4,192,6,12,11,11,32,1,32,2,253,11,4,208,6,12,10,11,32,1,32,2,253,11,4,224,6,12,9,11,32,1,32,2,253,11,4,240,6,12,8,11,32,1,32,2,253,11,4,128,7,12,7,11,32,1,32,2,253,11,4,144,7,12,6,11,32,1,32,2,253,11,4,160,7,12,5,11,32,1,32,2,253,11,4,176,7,12,4,11,32,1,32,2,253,11,4,192,7,12,3,11,32,1,32,2,253,11,4,208,7,12,2,11,32,1,32,2,253,11,4,224,7,12,1,11,32,1,32,2,253,11,4,240,7,11,32,0,65,1,106,33,0,12,1,11,11,15,11,65,192,19,32,0,16,13,16,15,65,192,20,65,201,1,65,7,16,0,0,11,192,10,2,2,123,2,127,35,0,36,8,35,1,36,9,35,2,36,10,35,3,36,11,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,65,0,36,18,3,64,35,18,65,192,0,72,4,64,35,15,35,12,34,0,65,6,253,173,1,32,0,65,26,253,171,1,253,80,32,0,65,11,253,173,1,32,0,65,21,253,171,1,253,80,253,81,32,0,65,25,253,173,1,32,0,65,7,253,171,1,253,80,253,81,253,174,1,35,12,34,0,35,13,253,78,32,0,253,77,35,14,253,78,253,81,253,174,1,33,1,35,26,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,3,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,2,253,0,4,0,33,0,12,64,11,32,2,253,0,4,16,33,0,12,63,11,32,2,253,0,4,32,33,0,12,62,11,32,2,253,0,4,48,33,0,12,61,11,32,2,253,0,4,64,33,0,12,60,11,32,2,253,0,4,80,33,0,12,59,11,32,2,253,0,4,96,33,0,12,58,11,32,2,253,0,4,112,33,0,12,57,11,32,2,253,0,4,128,1,33,0,12,56,11,32,2,253,0,4,144,1,33,0,12,55,11,32,2,253,0,4,160,1,33,0,12,54,11,32,2,253,0,4,176,1,33,0,12,53,11,32,2,253,0,4,192,1,33,0,12,52,11,32,2,253,0,4,208,1,33,0,12,51,11,32,2,253,0,4,224,1,33,0,12,50,11,32,2,253,0,4,240,1,33,0,12,49,11,32,2,253,0,4,128,2,33,0,12,48,11,32,2,253,0,4,144,2,33,0,12,47,11,32,2,253,0,4,160,2,33,0,12,46,11,32,2,253,0,4,176,2,33,0,12,45,11,32,2,253,0,4,192,2,33,0,12,44,11,32,2,253,0,4,208,2,33,0,12,43,11,32,2,253,0,4,224,2,33,0,12,42,11,32,2,253,0,4,240,2,33,0,12,41,11,32,2,253,0,4,128,3,33,0,12,40,11,32,2,253,0,4,144,3,33,0,12,39,11,32,2,253,0,4,160,3,33,0,12,38,11,32,2,253,0,4,176,3,33,0,12,37,11,32,2,253,0,4,192,3,33,0,12,36,11,32,2,253,0,4,208,3,33,0,12,35,11,32,2,253,0,4,224,3,33,0,12,34,11,32,2,253,0,4,240,3,33,0,12,33,11,32,2,253,0,4,128,4,33,0,12,32,11,32,2,253,0,4,144,4,33,0,12,31,11,32,2,253,0,4,160,4,33,0,12,30,11,32,2,253,0,4,176,4,33,0,12,29,11,32,2,253,0,4,192,4,33,0,12,28,11,32,2,253,0,4,208,4,33,0,12,27,11,32,2,253,0,4,224,4,33,0,12,26,11,32,2,253,0,4,240,4,33,0,12,25,11,32,2,253,0,4,128,5,33,0,12,24,11,32,2,253,0,4,144,5,33,0,12,23,11,32,2,253,0,4,160,5,33,0,12,22,11,32,2,253,0,4,176,5,33,0,12,21,11,32,2,253,0,4,192,5,33,0,12,20,11,32,2,253,0,4,208,5,33,0,12,19,11,32,2,253,0,4,224,5,33,0,12,18,11,32,2,253,0,4,240,5,33,0,12,17,11,32,2,253,0,4,128,6,33,0,12,16,11,32,2,253,0,4,144,6,33,0,12,15,11,32,2,253,0,4,160,6,33,0,12,14,11,32,2,253,0,4,176,6,33,0,12,13,11,32,2,253,0,4,192,6,33,0,12,12,11,32,2,253,0,4,208,6,33,0,12,11,11,32,2,253,0,4,224,6,33,0,12,10,11,32,2,253,0,4,240,6,33,0,12,9,11,32,2,253,0,4,128,7,33,0,12,8,11,32,2,253,0,4,144,7,33,0,12,7,11,32,2,253,0,4,160,7,33,0,12,6,11,32,2,253,0,4,176,7,33,0,12,5,11,32,2,253,0,4,192,7,33,0,12,4,11,32,2,253,0,4,208,7,33,0,12,3,11,32,2,253,0,4,224,7,33,0,12,2,11,32,2,253,0,4,240,7,33,0,12,1,11,65,128,21,32,3,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,32,1,32,0,253,174,1,36,16,35,8,34,0,65,2,253,173,1,32,0,65,30,253,171,1,253,80,32,0,65,13,253,173,1,32,0,65,19,253,171,1,253,80,253,81,32,0,65,22,253,173,1,32,0,65,10,253,171,1,253,80,253,81,35,8,34,0,35,9,34,1,253,78,32,0,35,10,34,0,253,78,253,81,32,1,32,0,253,78,253,81,253,174,1,36,17,35,14,36,15,35,13,36,14,35,12,36,13,35,11,35,16,253,174,1,36,12,35,10,36,11,35,9,36,10,35,8,36,9,35,16,35,17,253,174,1,36,8,35,18,65,1,106,36,18,12,1,11,11,35,0,35,8,253,174,1,36,0,35,1,35,9,253,174,1,36,1,35,2,35,10,253,174,1,36,2,35,3,35,11,253,174,1,36,3,35,4,35,12,253,174,1,36,4,35,5,35,13,253,174,1,36,5,35,6,35,14,253,174,1,36,6,35,7,35,15,253,174,1,36,7,11,25,0,32,0,65,128,254,131,120,113,65,8,119,32,0,65,255,129,252,7,113,65,8,120,114,11,157,57,2,2,123,2,127,253,12,103,230,9,106,103,230,9,106,103,230,9,106,103,230,9,106,36,0,253,12,133,174,103,187,133,174,103,187,133,174,103,187,133,174,103,187,36,1,253,12,114,243,110,60,114,243,110,60,114,243,110,60,114,243,110,60,36,2,253,12,58,245,79,165,58,245,79,165,58,245,79,165,58,245,79,165,36,3,253,12,127,82,14,81,127,82,14,81,127,82,14,81,127,82,14,81,36,4,253,12,140,104,5,155,140,104,5,155,140,104,5,155,140,104,5,155,36,5,253,12,171,217,131,31,171,217,131,31,171,217,131,31,171,217,131,31,36,6,253,12,25,205,224,91,25,205,224,91,25,205,224,91,25,205,224,91,36,7,253,12,103,230,9,106,103,230,9,106,103,230,9,106,103,230,9,106,36,8,253,12,133,174,103,187,133,174,103,187,133,174,103,187,133,174,103,187,36,9,253,12,114,243,110,60,114,243,110,60,114,243,110,60,114,243,110,60,36,10,253,12,58,245,79,165,58,245,79,165,58,245,79,165,58,245,79,165,36,11,253,12,127,82,14,81,127,82,14,81,127,82,14,81,127,82,14,81,36,12,253,12,140,104,5,155,140,104,5,155,140,104,5,155,140,104,5,155,36,13,253,12,171,217,131,31,171,217,131,31,171,217,131,31,171,217,131,31,36,14,253,12,25,205,224,91,25,205,224,91,25,205,224,91,25,205,224,91,36,15,65,0,36,18,2,64,3,64,35,18,65,192,0,72,4,64,35,18,65,16,72,4,123,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,5,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,2,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,34,2,65,17,253,173,1,32,2,65,15,253,171,1,253,80,32,2,65,19,253,173,1,32,2,65,13,253,171,1,253,80,253,81,32,2,65,10,253,173,1,253,81,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,7,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,253,174,1,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,15,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,34,2,65,7,253,173,1,32,2,65,25,253,171,1,253,80,32,2,65,18,253,173,1,32,2,65,14,253,171,1,253,80,253,81,32,2,65,3,253,173,1,253,81,253,174,1,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,16,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,253,174,1,11,36,19,35,18,65,16,78,4,64,35,19,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,0,32,2,253,11,4,0,12,64,11,32,0,32,2,253,11,4,16,12,63,11,32,0,32,2,253,11,4,32,12,62,11,32,0,32,2,253,11,4,48,12,61,11,32,0,32,2,253,11,4,64,12,60,11,32,0,32,2,253,11,4,80,12,59,11,32,0,32,2,253,11,4,96,12,58,11,32,0,32,2,253,11,4,112,12,57,11,32,0,32,2,253,11,4,128,1,12,56,11,32,0,32,2,253,11,4,144,1,12,55,11,32,0,32,2,253,11,4,160,1,12,54,11,32,0,32,2,253,11,4,176,1,12,53,11,32,0,32,2,253,11,4,192,1,12,52,11,32,0,32,2,253,11,4,208,1,12,51,11,32,0,32,2,253,11,4,224,1,12,50,11,32,0,32,2,253,11,4,240,1,12,49,11,32,0,32,2,253,11,4,128,2,12,48,11,32,0,32,2,253,11,4,144,2,12,47,11,32,0,32,2,253,11,4,160,2,12,46,11,32,0,32,2,253,11,4,176,2,12,45,11,32,0,32,2,253,11,4,192,2,12,44,11,32,0,32,2,253,11,4,208,2,12,43,11,32,0,32,2,253,11,4,224,2,12,42,11,32,0,32,2,253,11,4,240,2,12,41,11,32,0,32,2,253,11,4,128,3,12,40,11,32,0,32,2,253,11,4,144,3,12,39,11,32,0,32,2,253,11,4,160,3,12,38,11,32,0,32,2,253,11,4,176,3,12,37,11,32,0,32,2,253,11,4,192,3,12,36,11,32,0,32,2,253,11,4,208,3,12,35,11,32,0,32,2,253,11,4,224,3,12,34,11,32,0,32,2,253,11,4,240,3,12,33,11,32,0,32,2,253,11,4,128,4,12,32,11,32,0,32,2,253,11,4,144,4,12,31,11,32,0,32,2,253,11,4,160,4,12,30,11,32,0,32,2,253,11,4,176,4,12,29,11,32,0,32,2,253,11,4,192,4,12,28,11,32,0,32,2,253,11,4,208,4,12,27,11,32,0,32,2,253,11,4,224,4,12,26,11,32,0,32,2,253,11,4,240,4,12,25,11,32,0,32,2,253,11,4,128,5,12,24,11,32,0,32,2,253,11,4,144,5,12,23,11,32,0,32,2,253,11,4,160,5,12,22,11,32,0,32,2,253,11,4,176,5,12,21,11,32,0,32,2,253,11,4,192,5,12,20,11,32,0,32,2,253,11,4,208,5,12,19,11,32,0,32,2,253,11,4,224,5,12,18,11,32,0,32,2,253,11,4,240,5,12,17,11,32,0,32,2,253,11,4,128,6,12,16,11,32,0,32,2,253,11,4,144,6,12,15,11,32,0,32,2,253,11,4,160,6,12,14,11,32,0,32,2,253,11,4,176,6,12,13,11,32,0,32,2,253,11,4,192,6,12,12,11,32,0,32,2,253,11,4,208,6,12,11,11,32,0,32,2,253,11,4,224,6,12,10,11,32,0,32,2,253,11,4,240,6,12,9,11,32,0,32,2,253,11,4,128,7,12,8,11,32,0,32,2,253,11,4,144,7,12,7,11,32,0,32,2,253,11,4,160,7,12,6,11,32,0,32,2,253,11,4,176,7,12,5,11,32,0,32,2,253,11,4,192,7,12,4,11,32,0,32,2,253,11,4,208,7,12,3,11,32,0,32,2,253,11,4,224,7,12,2,11,32,0,32,2,253,11,4,240,7,12,1,11,65,192,19,32,4,16,13,16,15,65,192,20,65,201,1,65,7,16,0,0,11,11,35,15,35,12,34,2,65,6,253,173,1,32,2,65,26,253,171,1,253,80,32,2,65,11,253,173,1,32,2,65,21,253,171,1,253,80,253,81,32,2,65,25,253,173,1,32,2,65,7,253,171,1,253,80,253,81,253,174,1,35,12,34,2,35,13,253,78,32,2,253,77,35,14,253,78,253,81,253,174,1,33,3,35,24,33,4,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,5,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,4,253,0,4,0,33,2,12,64,11,32,4,253,0,4,16,33,2,12,63,11,32,4,253,0,4,32,33,2,12,62,11,32,4,253,0,4,48,33,2,12,61,11,32,4,253,0,4,64,33,2,12,60,11,32,4,253,0,4,80,33,2,12,59,11,32,4,253,0,4,96,33,2,12,58,11,32,4,253,0,4,112,33,2,12,57,11,32,4,253,0,4,128,1,33,2,12,56,11,32,4,253,0,4,144,1,33,2,12,55,11,32,4,253,0,4,160,1,33,2,12,54,11,32,4,253,0,4,176,1,33,2,12,53,11,32,4,253,0,4,192,1,33,2,12,52,11,32,4,253,0,4,208,1,33,2,12,51,11,32,4,253,0,4,224,1,33,2,12,50,11,32,4,253,0,4,240,1,33,2,12,49,11,32,4,253,0,4,128,2,33,2,12,48,11,32,4,253,0,4,144,2,33,2,12,47,11,32,4,253,0,4,160,2,33,2,12,46,11,32,4,253,0,4,176,2,33,2,12,45,11,32,4,253,0,4,192,2,33,2,12,44,11,32,4,253,0,4,208,2,33,2,12,43,11,32,4,253,0,4,224,2,33,2,12,42,11,32,4,253,0,4,240,2,33,2,12,41,11,32,4,253,0,4,128,3,33,2,12,40,11,32,4,253,0,4,144,3,33,2,12,39,11,32,4,253,0,4,160,3,33,2,12,38,11,32,4,253,0,4,176,3,33,2,12,37,11,32,4,253,0,4,192,3,33,2,12,36,11,32,4,253,0,4,208,3,33,2,12,35,11,32,4,253,0,4,224,3,33,2,12,34,11,32,4,253,0,4,240,3,33,2,12,33,11,32,4,253,0,4,128,4,33,2,12,32,11,32,4,253,0,4,144,4,33,2,12,31,11,32,4,253,0,4,160,4,33,2,12,30,11,32,4,253,0,4,176,4,33,2,12,29,11,32,4,253,0,4,192,4,33,2,12,28,11,32,4,253,0,4,208,4,33,2,12,27,11,32,4,253,0,4,224,4,33,2,12,26,11,32,4,253,0,4,240,4,33,2,12,25,11,32,4,253,0,4,128,5,33,2,12,24,11,32,4,253,0,4,144,5,33,2,12,23,11,32,4,253,0,4,160,5,33,2,12,22,11,32,4,253,0,4,176,5,33,2,12,21,11,32,4,253,0,4,192,5,33,2,12,20,11,32,4,253,0,4,208,5,33,2,12,19,11,32,4,253,0,4,224,5,33,2,12,18,11,32,4,253,0,4,240,5,33,2,12,17,11,32,4,253,0,4,128,6,33,2,12,16,11,32,4,253,0,4,144,6,33,2,12,15,11,32,4,253,0,4,160,6,33,2,12,14,11,32,4,253,0,4,176,6,33,2,12,13,11,32,4,253,0,4,192,6,33,2,12,12,11,32,4,253,0,4,208,6,33,2,12,11,11,32,4,253,0,4,224,6,33,2,12,10,11,32,4,253,0,4,240,6,33,2,12,9,11,32,4,253,0,4,128,7,33,2,12,8,11,32,4,253,0,4,144,7,33,2,12,7,11,32,4,253,0,4,160,7,33,2,12,6,11,32,4,253,0,4,176,7,33,2,12,5,11,32,4,253,0,4,192,7,33,2,12,4,11,32,4,253,0,4,208,7,33,2,12,3,11,32,4,253,0,4,224,7,33,2,12,2,11,32,4,253,0,4,240,7,33,2,12,1,11,65,128,21,32,5,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,32,3,32,2,253,174,1,35,19,253,174,1,36,16,35,8,34,2,65,2,253,173,1,32,2,65,30,253,171,1,253,80,32,2,65,13,253,173,1,32,2,65,19,253,171,1,253,80,253,81,32,2,65,22,253,173,1,32,2,65,10,253,171,1,253,80,253,81,35,8,34,2,35,9,34,3,253,78,32,2,35,10,34,2,253,78,253,81,32,3,32,2,253,78,253,81,253,174,1,36,17,35,14,36,15,35,13,36,14,35,12,36,13,35,11,35,16,253,174,1,36,12,35,10,36,11,35,9,36,10,35,8,36,9,35,16,35,17,253,174,1,36,8,35,18,65,1,106,36,18,12,1,11,11,35,0,35,8,253,174,1,36,0,35,1,35,9,253,174,1,36,1,35,2,35,10,253,174,1,36,2,35,3,35,11,253,174,1,36,3,35,4,35,12,253,174,1,36,4,35,5,35,13,253,174,1,36,5,35,6,35,14,253,174,1,36,6,35,7,35,15,253,174,1,36,7,16,17,32,1,35,0,253,27,0,16,18,54,2,0,32,1,35,1,253,27,0,16,18,54,2,4,32,1,35,2,253,27,0,16,18,54,2,8,32,1,35,3,253,27,0,16,18,54,2,12,32,1,35,4,253,27,0,16,18,54,2,16,32,1,35,5,253,27,0,16,18,54,2,20,32,1,35,6,253,27,0,16,18,54,2,24,32,1,35,7,253,27,0,16,18,54,2,28,32,1,35,0,253,27,1,16,18,54,2,32,32,1,35,1,253,27,1,16,18,54,2,36,32,1,35,2,253,27,1,16,18,54,2,40,32,1,35,3,253,27,1,16,18,54,2,44,32,1,35,4,253,27,1,16,18,54,2,48,32,1,35,5,253,27,1,16,18,54,2,52,32,1,35,6,253,27,1,16,18,54,2,56,32,1,35,7,253,27,1,16,18,54,2,60,32,1,65,64,107,35,0,253,27,2,16,18,54,2,0,32,1,35,1,253,27,2,16,18,54,2,68,32,1,35,2,253,27,2,16,18,54,2,72,32,1,35,3,253,27,2,16,18,54,2,76,32,1,35,4,253,27,2,16,18,54,2,80,32,1,35,5,253,27,2,16,18,54,2,84,32,1,35,6,253,27,2,16,18,54,2,88,32,1,35,7,253,27,2,16,18,54,2,92,32,1,35,0,253,27,3,16,18,54,2,96,32,1,35,1,253,27,3,16,18,54,2,100,32,1,35,2,253,27,3,16,18,54,2,104,32,1,35,3,253,27,3,16,18,54,2,108,32,1,35,4,253,27,3,16,18,54,2,112,32,1,35,5,253,27,3,16,18,54,2,116,32,1,35,6,253,27,3,16,18,54,2,120,32,1,35,7,253,27,3,16,18,54,2,124,15,11,65,128,21,32,4,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,203,2,1,5,127,3,64,32,1,65,16,72,4,64,32,1,65,2,116,34,2,65,1,106,33,3,35,53,32,2,65,2,116,106,32,2,65,3,106,34,4,35,55,34,5,106,45,0,0,32,2,32,5,106,45,0,0,65,24,116,32,3,32,5,106,45,0,0,65,16,116,114,32,2,65,2,106,34,2,32,5,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,3,65,2,116,106,35,55,34,3,32,1,65,16,106,65,2,116,34,5,65,3,106,106,45,0,0,32,3,32,5,106,45,0,0,65,24,116,32,5,65,1,106,32,3,106,45,0,0,65,16,116,114,32,5,65,2,106,32,3,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,2,65,2,116,106,35,55,34,2,32,1,65,32,106,65,2,116,34,3,65,3,106,106,45,0,0,32,2,32,3,106,45,0,0,65,24,116,32,3,65,1,106,32,2,106,45,0,0,65,16,116,114,32,3,65,2,106,32,2,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,4,65,2,116,106,35,55,34,2,32,1,65,48,106,65,2,116,34,3,65,3,106,106,45,0,0,32,2,32,3,106,45,0,0,65,24,116,32,3,65,1,106,32,2,106,45,0,0,65,16,116,114,32,3,65,2,106,32,2,106,45,0,0,65,8,116,114,114,54,2,0,32,1,65,1,106,33,1,12,1,11,11,35,53,32,0,16,19,11,99,1,3,127,3,64,32,2,65,192,0,72,4,64,32,2,65,2,116,34,1,35,53,106,35,55,34,3,32,1,65,3,106,106,45,0,0,32,1,32,3,106,45,0,0,65,24,116,32,1,65,1,106,32,3,106,45,0,0,65,16,116,114,32,1,65,2,106,32,3,106,45,0,0,65,8,116,114,114,54,2,0,32,2,65,1,106,33,2,12,1,11,11,35,53,32,0,16,19,11,74,0,65,231,204,167,208,6,36,31,65,133,221,158,219,123,36,32,65,242,230,187,227,3,36,33,65,186,234,191,170,122,36,34,65,255,164,185,136,5,36,35,65,140,209,149,216,121,36,36,65,171,179,143,252,1,36,37,65,153,154,131,223,5,36,38,65,0,36,58,65,0,36,59,11,227,3,1,2,127,35,31,36,39,35,32,36,40,35,33,36,41,35,34,36,42,35,35,36,43,35,36,36,44,35,37,36,45,35,38,36,46,65,0,36,47,3,64,35,47,65,16,73,4,64,35,47,65,2,116,34,2,32,0,106,32,1,32,2,65,3,106,106,45,0,0,32,1,32,2,106,45,0,0,65,24,116,32,1,32,2,65,1,106,106,45,0,0,65,16,116,114,32,1,32,2,65,2,106,106,45,0,0,65,8,116,114,114,54,2,0,35,47,65,1,106,36,47,12,1,11,11,65,16,36,47,3,64,35,47,65,192,0,73,4,64,32,0,35,47,65,2,116,106,32,0,35,47,65,16,107,65,2,116,106,40,2,0,32,0,35,47,65,7,107,65,2,116,106,40,2,0,32,0,35,47,65,2,107,65,2,116,106,40,2,0,34,1,65,17,120,32,1,65,19,120,115,32,1,65,10,118,115,106,32,0,35,47,65,15,107,65,2,116,106,40,2,0,34,1,65,7,120,32,1,65,18,120,115,32,1,65,3,118,115,106,106,54,2,0,35,47,65,1,106,36,47,12,1,11,11,65,0,36,47,3,64,35,47,65,192,0,73,4,64,35,47,65,2,116,34,1,32,0,106,40,2,0,32,1,35,29,106,40,2,0,35,46,35,43,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,43,34,1,35,44,113,35,45,32,1,65,127,115,113,115,106,106,106,36,48,35,39,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,40,34,2,35,41,34,3,113,35,39,34,1,32,2,113,32,1,32,3,113,115,115,106,36,49,35,45,36,46,35,44,36,45,35,43,36,44,35,42,35,48,106,36,43,35,41,36,42,35,40,36,41,35,39,36,40,35,48,35,49,106,36,39,35,47,65,1,106,36,47,12,1,11,11,35,31,35,39,106,36,31,35,32,35,40,106,36,32,35,33,35,41,106,36,33,35,34,35,42,106,36,34,35,35,35,43,106,36,35,35,36,35,44,106,36,36,35,37,35,45,106,36,37,35,38,35,46,106,36,38,11,174,1,1,2,127,35,59,32,1,106,36,59,35,58,4,64,65,192,0,35,58,107,34,2,32,1,76,4,64,35,51,35,58,106,32,0,32,2,252,10,0,0,35,58,32,2,106,36,58,65,192,0,35,58,107,33,2,32,1,65,192,0,35,58,107,107,33,1,35,53,35,51,16,23,65,0,36,58,5,35,51,35,58,106,32,0,32,1,252,10,0,0,35,58,32,1,106,36,58,15,11,11,3,64,32,3,32,1,65,192,0,109,72,4,64,35,53,32,0,32,2,106,16,23,32,3,65,1,106,33,3,32,2,65,64,107,33,2,12,1,11,11,32,1,65,63,113,34,1,4,64,35,51,35,58,106,32,0,32,2,106,32,1,252,10,0,0,35,58,32,1,106,36,58,11,11,231,1,1,2,127,35,51,35,58,106,65,128,1,58,0,0,35,58,65,1,106,36,58,35,58,65,56,74,4,64,35,51,35,58,106,34,1,65,192,0,35,58,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,53,35,51,16,23,65,0,36,58,11,35,51,35,58,106,34,1,65,56,35,58,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,51,35,59,65,128,128,128,128,2,109,16,18,54,2,56,35,51,35,59,65,3,116,16,18,54,2,60,35,53,35,51,16,23,32,0,35,31,16,18,54,2,0,32,0,35,32,16,18,54,2,4,32,0,35,33,16,18,54,2,8,32,0,35,34,16,18,54,2,12,32,0,35,35,16,18,54,2,16,32,0,35,36,16,18,54,2,20,32,0,35,37,16,18,54,2,24,32,0,35,38,16,18,54,2,28,11,14,0,16,22,35,55,32,0,16,24,35,57,16,25,11,253,1,1,2,127,35,31,36,39,35,32,36,40,35,33,36,41,35,34,36,42,35,35,36,43,35,36,36,44,35,37,36,45,35,38,36,46,65,0,36,47,3,64,35,47,65,192,0,73,4,64,32,0,35,47,65,2,116,106,40,2,0,35,46,35,43,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,43,34,1,35,44,113,35,45,32,1,65,127,115,113,115,106,106,36,48,35,39,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,40,34,2,35,41,34,1,113,32,2,35,39,34,2,113,32,1,32,2,113,115,115,106,36,49,35,45,36,46,35,44,36,45,35,43,36,44,35,42,35,48,106,36,43,35,41,36,42,35,40,36,41,35,39,36,40,35,48,35,49,106,36,39,35,47,65,1,106,36,47,12,1,11,11,35,31,35,39,106,36,31,35,32,35,40,106,36,32,35,33,35,41,106,36,33,35,34,35,42,106,36,34,35,35,35,43,106,36,35,35,36,35,44,106,36,36,35,37,35,45,106,36,37,35,38,35,46,106,36,38,11,86,0,16,22,35,53,32,0,16,23,35,30,16,27,32,1,35,31,16,18,54,2,0,32,1,35,32,16,18,54,2,4,32,1,35,33,16,18,54,2,8,32,1,35,34,16,18,54,2,12,32,1,35,35,16,18,54,2,16,32,1,35,36,16,18,54,2,20,32,1,35,37,16,18,54,2,24,32,1,35,38,16,18,54,2,28,11,63,0,16,16,65,196,10,40,2,0,36,29,65,148,13,40,2,0,36,30,65,192,0,16,11,36,50,35,50,36,51,65,128,8,16,11,36,52,35,52,36,53,65,128,4,16,11,36,54,35,54,36,55,65,32,16,11,36,56,35,56,36,57,11,11,141,12,38,0,65,140,8,11,2,28,1,0,65,152,8,11,136,2,1,0,0,0,0,1,0,0,152,47,138,66,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,241,155,193,193,105,155,228,134,71,190,239,198,157,193,15,204,161,12,36,111,44,233,45,170,132,116,74,220,169,176,92,218,136,249,118,82,81,62,152,109,198,49,168,200,39,3,176,199,127,89,191,243,11,224,198,71,145,167,213,81,99,202,6,103,41,41,20,133,10,183,39,56,33,27,46,252,109,44,77,19,13,56,83,84,115,10,101,187,10,106,118,46,201,194,129,133,44,114,146,161,232,191,162,75,102,26,168,112,139,75,194,163,81,108,199,25,232,146,209,36,6,153,214,133,53,14,244,112,160,106,16,22,193,164,25,8,108,55,30,76,119,72,39,181,188,176,52,179,12,28,57,74,170,216,78,79,202,156,91,243,111,46,104,238,130,143,116,111,99,165,120,20,120,200,132,8,2,199,140,250,255,190,144,235,108,80,164,247,163,249,190,242,120,113,198,0,65,172,10,11,1,44,0,65,184,10,11,21,4,0,0,0,16,0,0,0,32,4,0,0,32,4,0,0,0,1,0,0,64,0,65,220,10,11,2,28,1,0,65,232,10,11,136,2,1,0,0,0,0,1,0,0,152,47,138,194,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,243,155,193,193,105,155,100,134,71,254,240,198,237,225,15,84,242,12,36,111,52,233,79,190,132,201,108,30,65,185,97,250,136,249,22,82,81,198,242,109,90,142,168,101,252,25,176,199,158,217,185,195,49,18,154,160,234,14,231,43,35,177,253,176,62,53,199,213,186,105,48,95,109,151,203,143,17,15,90,253,238,30,220,137,182,53,10,4,122,11,222,157,202,244,88,22,91,93,225,134,62,127,0,128,137,8,55,50,234,7,165,55,149,171,111,16,97,64,23,241,214,140,13,109,59,170,205,55,190,187,192,218,59,97,131,99,163,72,219,49,233,2,11,167,92,209,111,202,250,26,82,49,132,51,49,149,26,212,110,144,120,67,109,242,145,156,195,189,171,204,158,230,160,201,181,60,182,47,83,198,65,199,210,163,126,35,7,104,75,149,164,118,29,25,76,0,65,252,12,11,1,44,0,65,136,13,11,21,4,0,0,0,16,0,0,0,112,5,0,0,112,5,0,0,0,1,0,0,64,0,65,172,13,11,1,44,0,65,184,13,11,35,2,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,220,13,11,1,60,0,65,232,13,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,156,14,11,1,60,0,65,168,14,11,47,2,0,0,0,40,0,0,0,65,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,220,14,11,1,60,0,65,232,14,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,99,0,109,0,115,0,46,0,116,0,115,0,65,156,15,11,1,60,0,65,168,15,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115,0,65,252,15,11,1,60,0,65,136,16,11,43,2,0,0,0,36,0,0,0,73,0,110,0,100,0,101,0,120,0,32,0,111,0,117,0,116,0,32,0,111,0,102,0,32,0,114,0,97,0,110,0,103,0,101,0,65,188,16,11,1,44,0,65,200,16,11,33,2,0,0,0,26,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,46,0,116,0,115,0,65,236,16,11,1,124,0,65,248,16,11,107,2,0,0,0,100,0,0,0,116,0,111,0,83,0,116,0,114,0,105,0,110,0,103,0,40,0,41,0,32,0,114,0,97,0,100,0,105,0,120,0,32,0,97,0,114,0,103,0,117,0,109,0,101,0,110,0,116,0,32,0,109,0,117,0,115,0,116,0,32,0,98,0,101,0,32,0,98,0,101,0,116,0,119,0,101,0,101,0,110,0,32,0,50,0,32,0,97,0,110,0,100,0,32,0,51,0,54,0,65,236,17,11,1,60,0,65,248,17,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,117,0,116,0,105,0,108,0,47,0,110,0,117,0,109,0,98,0,101,0,114,0,46,0,116,0,115,0,65,172,18,11,1,28,0,65,184,18,11,9,2,0,0,0,2,0,0,0,48,0,65,204,18,11,1,92,0,65,216,18,11,79,2,0,0,0,72,0,0,0,48,0,49,0,50,0,51,0,52,0,53,0,54,0,55,0,56,0,57,0,97,0,98,0,99,0,100,0,101,0,102,0,103,0,104,0,105,0,106,0,107,0,108,0,109,0,110,0,111,0,112,0,113,0,114,0,115,0,116,0,117,0,118,0,119,0,120,0,121,0,122,0,65,172,19,11,1,92,0,65,184,19,11,79,2,0,0,0,72,0,0,0,115,0,101,0,116,0,86,0,49,0,50,0,56,0,58,0,32,0,101,0,120,0,112,0,101,0,99,0,116,0,32,0,105,0,32,0,102,0,114,0,111,0,109,0,32,0,48,0,32,0,116,0,111,0,32,0,54,0,51,0,44,0,32,0,103,0,111,0,116,0,32,0,65,140,20,11,1,28,0,65,152,20,11,1,2,0,65,172,20,11,1,60,0,65,184,20,11,51,2,0,0,0,44,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,117,0,116,0,105,0,108,0,115,0,47,0,118,0,49,0,50,0,56,0,46,0,116,0,115,0,65,236,20,11,1,92,0,65,248,20,11,79,2,0,0,0,72,0,0,0,103,0,101,0,116,0,86,0,49,0,50,0,56,0,58,0,32,0,101,0,120,0,112,0,101,0,99,0,116,0,32,0,105,0,32,0,102,0,114,0,111,0,109,0,32,0,48,0,32,0,116,0,111,0,32,0,54,0,51,0,44,0,32,0,103,0,111,0,116,0,32]);var XT={env:{abort:(r,e,t,n)=>{throw Error(`abort: ${r}:${e}:${t}:${n}`)}}};function Jw(r){return(r!==void 0?r:WebAssembly.validate(Qw))?new WebAssembly.Instance(new WebAssembly.Module(Qw),XT).exports:new WebAssembly.Instance(new WebAssembly.Module(YT),XT).exports}var it,dq,Oa,Mu,Ou,fq,QT,pq;function mq(r){it=Jw(r),dq=!!it.HAS_SIMD.valueOf(),Oa=it.input.value,Mu=it.output.value,Ou=new Uint8Array(it.memory.buffer,Oa,it.INPUT_LENGTH),fq=new Uint8Array(it.memory.buffer,Mu,it.PARALLEL_FACTOR*32),QT=new Uint8Array(it.memory.buffer,Mu,32),pq=new Uint32Array(it.memory.buffer,Oa,it.INPUT_LENGTH)}mq();function JT(r){return r.length===64?gq(r):r.length<=it.INPUT_LENGTH?(Ou.set(r),it.digest(r.length),Zw()):(it.init(),yq(r),bq())}function gq(r){if(r.length===64)return Ou.set(r),it.digest64(Oa,Mu),Zw();throw new Error("InvalidLengthForDigest64")}function yq(r){let e=it.INPUT_LENGTH;if(r.length>e)for(let t=0;t<r.length;t+=e){let n=r.subarray(t,t+e);Ou.set(n),it.update(Oa,n.length)}else Ou.set(r),it.update(Oa,r.length)}function bq(){return it.final(Mu),Zw()}function Zw(){let r=jT(32);return r.set(QT),r}Be();var t_=ae(e_(),1),xq=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,r_=(0,t_.default)();var n_=r_&&!xq;var TEe=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!r_,_Ee=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,PEe=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+"_"+"ENV"]==="test",DEe=typeof navigator<"u"&&navigator.product==="ReactNative";function vq(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function E1(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function S1(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function yt(r,e,t=""){let n=vq(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function e6(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function s_(r,e){yt(r,void 0,"output");let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function jn(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Yn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Eq(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var Sq=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function o_(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function i_(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var t6=(r,e)=>{function t(n,...s){if(yt(n,void 0,"key"),!Sq)throw new Error("Non little-endian hardware is not yet supported");if(r.nonceLength!==void 0){let u=s[0];yt(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let o=r.tagLength;o&&s[1]!==void 0&&yt(s[1],void 0,"AAD");let i=e(n,...s),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");yt(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,yt(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(yt(u),o&&u.length<o)throw new Error('"ciphertext" expected length bigger than tagLength='+o);return a(i.decrypt.length,d),i.decrypt(u,d)}}}return Object.assign(t,r),t};function r6(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!Iq(e))throw new Error("invalid output, must be aligned");return e}function a_(r,e,t){E1(t);let n=new Uint8Array(16),s=Eq(n);return s.setBigUint64(0,BigInt(e),t),s.setBigUint64(8,BigInt(r),t),n}function Iq(r){return r.byteOffset%4===0}function Ra(r){return Uint8Array.from(r)}var l_=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),Aq=l_("expand 16-byte k"),Cq=l_("expand 32-byte k"),Tq=jn(Aq),_q=jn(Cq);function $(r,e){return r<<e|r>>>32-e}function n6(r){return r.byteOffset%4===0}var I1=64,Pq=16,u_=2**32-1,c_=Uint32Array.of();function Dq(r,e,t,n,s,o,i,a){let c=s.length,l=new Uint8Array(I1),u=jn(l),d=n6(s)&&n6(o),p=d?jn(s):c_,f=d?jn(o):c_;for(let h=0;h<c;i++){if(r(e,t,n,u,i,a),i>=u_)throw new Error("arx: counter overflow");let m=Math.min(I1,c-h);if(d&&m===I1){let g=h/4;if(h%4!==0)throw new Error("arx: invalid block position");for(let y=0,b;y<Pq;y++)b=g+y,f[b]=p[b]^u[y];h+=I1;continue}for(let g=0,y;g<m;g++)y=h+g,o[y]=s[y]^l[g];h+=m}}function s6(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:s,counterRight:o,rounds:i}=o_({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return S1(s),S1(i),E1(o),E1(t),(a,c,l,u,d=0)=>{yt(a,void 0,"key"),yt(c,void 0,"nonce"),yt(l,void 0,"data");let p=l.length;if(u===void 0&&(u=new Uint8Array(p)),yt(u,void 0,"output"),S1(d),d<0||d>=u_)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);let f=[],h=a.length,m,g;if(h===32)f.push(m=Ra(a)),g=_q;else if(h===16&&t)m=new Uint8Array(32),m.set(a),m.set(a,16),g=Tq,f.push(m);else throw yt(a,32,"arx key"),new Error("invalid key size");n6(c)||f.push(c=Ra(c));let y=jn(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(g,y,jn(c.subarray(0,16)),y),c=c.subarray(16)}let b=16-s;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let w=new Uint8Array(12);w.set(c,o?0:12-c.length),c=w,f.push(c)}let E=jn(c);return Dq(r,g,y,E,l,u,d,i),Yn(...f),u}}function It(r,e){return r[e++]&255|(r[e++]&255)<<8}var o6=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){e=Ra(yt(e,32,"key"));let t=It(e,0),n=It(e,2),s=It(e,4),o=It(e,6),i=It(e,8),a=It(e,10),c=It(e,12),l=It(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|s<<6)&7939,this.r[3]=(s>>>7|o<<9)&8191,this.r[4]=(o>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=It(e,16+2*u)}process(e,t,n=!1){let s=n?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],d=i[4],p=i[5],f=i[6],h=i[7],m=i[8],g=i[9],y=It(e,t+0),b=It(e,t+2),E=It(e,t+4),w=It(e,t+6),v=It(e,t+8),S=It(e,t+10),x=It(e,t+12),I=It(e,t+14),A=o[0]+(y&8191),j=o[1]+((y>>>13|b<<3)&8191),ee=o[2]+((b>>>10|E<<6)&8191),H=o[3]+((E>>>7|w<<9)&8191),L=o[4]+((w>>>4|v<<12)&8191),P=o[5]+(v>>>1&8191),_=o[6]+((v>>>14|S<<2)&8191),M=o[7]+((S>>>11|x<<5)&8191),O=o[8]+((x>>>8|I<<8)&8191),R=o[9]+(I>>>5|s),k=0,N=k+A*a+j*(5*g)+ee*(5*m)+H*(5*h)+L*(5*f);k=N>>>13,N&=8191,N+=P*(5*p)+_*(5*d)+M*(5*u)+O*(5*l)+R*(5*c),k+=N>>>13,N&=8191;let K=k+A*c+j*a+ee*(5*g)+H*(5*m)+L*(5*h);k=K>>>13,K&=8191,K+=P*(5*f)+_*(5*p)+M*(5*d)+O*(5*u)+R*(5*l),k+=K>>>13,K&=8191;let F=k+A*l+j*c+ee*a+H*(5*g)+L*(5*m);k=F>>>13,F&=8191,F+=P*(5*h)+_*(5*f)+M*(5*p)+O*(5*d)+R*(5*u),k+=F>>>13,F&=8191;let ve=k+A*u+j*l+ee*c+H*a+L*(5*g);k=ve>>>13,ve&=8191,ve+=P*(5*m)+_*(5*h)+M*(5*f)+O*(5*p)+R*(5*d),k+=ve>>>13,ve&=8191;let ue=k+A*d+j*u+ee*l+H*c+L*a;k=ue>>>13,ue&=8191,ue+=P*(5*g)+_*(5*m)+M*(5*h)+O*(5*f)+R*(5*p),k+=ue>>>13,ue&=8191;let se=k+A*p+j*d+ee*u+H*l+L*c;k=se>>>13,se&=8191,se+=P*a+_*(5*g)+M*(5*m)+O*(5*h)+R*(5*f),k+=se>>>13,se&=8191;let pe=k+A*f+j*p+ee*d+H*u+L*l;k=pe>>>13,pe&=8191,pe+=P*c+_*a+M*(5*g)+O*(5*m)+R*(5*h),k+=pe>>>13,pe&=8191;let Te=k+A*h+j*f+ee*p+H*d+L*u;k=Te>>>13,Te&=8191,Te+=P*l+_*c+M*a+O*(5*g)+R*(5*m),k+=Te>>>13,Te&=8191;let Qe=k+A*m+j*h+ee*f+H*p+L*d;k=Qe>>>13,Qe&=8191,Qe+=P*u+_*l+M*c+O*a+R*(5*g),k+=Qe>>>13,Qe&=8191;let be=k+A*g+j*m+ee*h+H*f+L*p;k=be>>>13,be&=8191,be+=P*d+_*u+M*l+O*c+R*a,k+=be>>>13,be&=8191,k=(k<<2)+k|0,k=k+N|0,N=k&8191,k=k>>>13,K+=k,o[0]=N,o[1]=K,o[2]=F,o[3]=ve,o[4]=ue,o[5]=se,o[6]=pe,o[7]=Te,o[8]=Qe,o[9]=be}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,n[0]=e[0]+5,s=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+s,s=n[a]>>>13,n[a]&=8191;n[9]-=8192;let o=(s^1)-1;for(let a=0;a<10;a++)n[a]&=o;o=~o;for(let a=0;a<10;a++)e[a]=e[a]&o|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;Yn(n)}update(e){e6(this),yt(e),e=Ra(e);let{buffer:t,blockLen:n}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);if(i===n){for(;n<=s-o;o+=n)this.process(e,o);continue}t.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Yn(this.h,this.r,this.buffer,this.pad)}digestInto(e){e6(this),s_(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:s}=this;if(s){for(t[s++]=1;s<16;s++)t[s]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)e[o++]=n[i]>>>0,e[o++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function kq(r){let e=(n,s)=>r(s).update(n).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var h_=kq(r=>new o6(r));function p_(r,e,t,n,s,o=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],d=e[1],p=e[2],f=e[3],h=e[4],m=e[5],g=e[6],y=e[7],b=s,E=t[0],w=t[1],v=t[2],S=i,x=a,I=c,A=l,j=u,ee=d,H=p,L=f,P=h,_=m,M=g,O=y,R=b,k=E,N=w,K=v;for(let ve=0;ve<o;ve+=2)S=S+j|0,R=$(R^S,16),P=P+R|0,j=$(j^P,12),S=S+j|0,R=$(R^S,8),P=P+R|0,j=$(j^P,7),x=x+ee|0,k=$(k^x,16),_=_+k|0,ee=$(ee^_,12),x=x+ee|0,k=$(k^x,8),_=_+k|0,ee=$(ee^_,7),I=I+H|0,N=$(N^I,16),M=M+N|0,H=$(H^M,12),I=I+H|0,N=$(N^I,8),M=M+N|0,H=$(H^M,7),A=A+L|0,K=$(K^A,16),O=O+K|0,L=$(L^O,12),A=A+L|0,K=$(K^A,8),O=O+K|0,L=$(L^O,7),S=S+ee|0,K=$(K^S,16),M=M+K|0,ee=$(ee^M,12),S=S+ee|0,K=$(K^S,8),M=M+K|0,ee=$(ee^M,7),x=x+H|0,R=$(R^x,16),O=O+R|0,H=$(H^O,12),x=x+H|0,R=$(R^x,8),O=O+R|0,H=$(H^O,7),I=I+L|0,k=$(k^I,16),P=P+k|0,L=$(L^P,12),I=I+L|0,k=$(k^I,8),P=P+k|0,L=$(L^P,7),A=A+j|0,N=$(N^A,16),_=_+N|0,j=$(j^_,12),A=A+j|0,N=$(N^A,8),_=_+N|0,j=$(j^_,7);let F=0;n[F++]=i+S|0,n[F++]=a+x|0,n[F++]=c+I|0,n[F++]=l+A|0,n[F++]=u+j|0,n[F++]=d+ee|0,n[F++]=p+H|0,n[F++]=f+L|0,n[F++]=h+P|0,n[F++]=m+_|0,n[F++]=g+M|0,n[F++]=y+O|0,n[F++]=b+R|0,n[F++]=E+k|0,n[F++]=w+N|0,n[F++]=v+K|0}function Lq(r,e,t,n){let s=r[0],o=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],d=e[3],p=e[4],f=e[5],h=e[6],m=e[7],g=t[0],y=t[1],b=t[2],E=t[3];for(let v=0;v<20;v+=2)s=s+c|0,g=$(g^s,16),p=p+g|0,c=$(c^p,12),s=s+c|0,g=$(g^s,8),p=p+g|0,c=$(c^p,7),o=o+l|0,y=$(y^o,16),f=f+y|0,l=$(l^f,12),o=o+l|0,y=$(y^o,8),f=f+y|0,l=$(l^f,7),i=i+u|0,b=$(b^i,16),h=h+b|0,u=$(u^h,12),i=i+u|0,b=$(b^i,8),h=h+b|0,u=$(u^h,7),a=a+d|0,E=$(E^a,16),m=m+E|0,d=$(d^m,12),a=a+d|0,E=$(E^a,8),m=m+E|0,d=$(d^m,7),s=s+l|0,E=$(E^s,16),h=h+E|0,l=$(l^h,12),s=s+l|0,E=$(E^s,8),h=h+E|0,l=$(l^h,7),o=o+u|0,g=$(g^o,16),m=m+g|0,u=$(u^m,12),o=o+u|0,g=$(g^o,8),m=m+g|0,u=$(u^m,7),i=i+d|0,y=$(y^i,16),p=p+y|0,d=$(d^p,12),i=i+d|0,y=$(y^i,8),p=p+y|0,d=$(d^p,7),a=a+c|0,b=$(b^a,16),f=f+b|0,c=$(c^f,12),a=a+c|0,b=$(b^a,8),f=f+b|0,c=$(c^f,7);let w=0;n[w++]=s,n[w++]=o,n[w++]=i,n[w++]=a,n[w++]=g,n[w++]=y,n[w++]=b,n[w++]=E}var Mq=s6(p_,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Oq=s6(p_,{counterRight:!1,counterLength:8,extendNonceFn:Lq,allowShortKeys:!1});var Rq=new Uint8Array(16),d_=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(Rq.subarray(t))},Nq=new Uint8Array(32);function f_(r,e,t,n,s){s!==void 0&&yt(s,void 0,"AAD");let o=r(e,t,Nq),i=a_(n.length,s?s.length:0,!0),a=h_.create(o);s&&d_(a,s),d_(a,n),a.update(i);let c=a.digest();return Yn(o,i),c}var m_=r=>(e,t,n)=>({encrypt(o,i){let a=o.length;i=r6(a+16,i,!1),i.set(o);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=f_(r,e,t,c,n);return i.set(l,a),Yn(l),i},decrypt(o,i){i=r6(o.length-16,i,!1);let a=o.subarray(0,-16),c=o.subarray(-16),l=f_(r,e,t,a,n);if(!i_(c,l))throw new Error("invalid tag");return i.set(o.subarray(0,-16)),r(e,t,i,i,1),Yn(l),i}}),i6=t6({blockSize:64,nonceLength:12,tagLength:16},m_(Mq)),GEe=t6({blockSize:64,nonceLength:24,tagLength:16},m_(Oq));yi();Wc();E2();yi();var Ru=BigInt(0),Na=BigInt(1),A1=BigInt(2);function Bq(r){return Qs(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function g_(r){let e=Bq(r),{P:t,type:n,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||Qr,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),p=BigInt(a?121665:39081),f=a?A1**BigInt(254):A1**BigInt(447),h=a?BigInt(8)*A1**BigInt(251)-Na:BigInt(4)*A1**BigInt(445)-Na,m=f+h+Na,g=P=>Ut(P,t),y=b(d);function b(P){return qc(g(P),u)}function E(P){let _=td(ge(P,u,"uCoordinate"));return a&&(_[31]&=127),g(mi(_))}function w(P){return mi(s(td(ge(P,u,"scalar"))))}function v(P,_){let M=j(E(_),w(P));if(M===Ru)throw new Error("invalid private or public key received");return b(M)}function S(P){return v(P,y)}let x=S,I=v;function A(P,_,M){let O=g(P*(_-M));return _=g(_-O),M=g(M+O),{x_2:_,x_3:M}}function j(P,_){Vc("u",P,Ru,t),Vc("scalar",_,f,m);let M=_,O=P,R=Na,k=Ru,N=P,K=Na,F=Ru;for(let ue=BigInt(l-1);ue>=Ru;ue--){let se=M>>ue&Na;F^=se,{x_2:R,x_3:N}=A(F,R,N),{x_2:k,x_3:K}=A(F,k,K),F=se;let pe=R+k,Te=g(pe*pe),Qe=R-k,be=g(Qe*Qe),et=Te-be,Wo=N+K,ih=N-K,ac=g(ih*pe),U5=g(Wo*Qe),K5=ac+U5,F5=ac-U5;N=g(K5*K5),K=g(O*g(F5*F5)),R=g(Te*be),k=g(et*(Te+g(p*et)))}({x_2:R,x_3:N}=A(F,R,N)),{x_2:k,x_3:K}=A(F,k,K);let ve=o(k);return g(R*ve)}let ee={secretKey:u,publicKey:u,seed:u},H=(P=c(u))=>(ge(P,ee.seed,"seed"),P),L={randomSecretKey:H};return Object.freeze({keygen:nd(H,x),getSharedSecret:I,getPublicKey:x,scalarMult:v,scalarMultBase:S,utils:L,GuBytes:y.slice(),lengths:ee})}var Uq=BigInt(1),y_=BigInt(2),Kq=BigInt(3),Fq=BigInt(5),rSe=BigInt(8),b_=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function zq(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=b_,a=r*r%o*r%o,c=Me(a,y_,o)*a%o,l=Me(c,Uq,o)*r%o,u=Me(l,Fq,o)*l%o,d=Me(u,e,o)*u%o,p=Me(d,t,o)*d%o,f=Me(p,n,o)*p%o,h=Me(f,s,o)*f%o,m=Me(h,s,o)*f%o,g=Me(m,e,o)*u%o;return{pow_p_5_8:Me(g,y_,o)*r%o,b2:a}}function $q(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Nu=(()=>{let r=b_;return g_({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=zq(e);return Ut(Me(t,Kq,r)*n,r)},adjustScalarBytes:$q})})();S2();Jr();function x_(r,e,t){return js(r),t===void 0&&(t=new Uint8Array(r.outputLen)),wi(r,t,e)}var a6=Uint8Array.of(0),w_=Uint8Array.of();function v_(r,e,t,n=32){js(r),xr(n,"length");let s=r.outputLen;if(n>255*s)throw new Error("Length must be <= 255*HashLen");let o=Math.ceil(n/s);t===void 0?t=w_:ge(t,void 0,"info");let i=new Uint8Array(o*s),a=wi.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)a6[0]=u+1,c.update(u===0?w_:l).update(t).update(a6).digestInto(l),i.set(l,s*u),a._cloneInto(c);return a.destroy(),c.destroy(),kn(l,a6),i.slice(0,n)}Kc();var c6={hashSHA256(r){return Yt(r.subarray())},getHKDF(r,e){let t=x_(Yt,e,r),s=v_(Yt,t,void 0,96),o=s.subarray(0,32),i=s.subarray(32,64),a=s.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){let r=Nu.utils.randomSecretKey();return{publicKey:Nu.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Nu.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return Nu.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return i6(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,s){return i6(n,e,t).decrypt(r.subarray(),s)}};var Hq=(0,_1.newInstance)(),E_=new _1.ChaCha20Poly1305(Hq),S_="chacha20-poly1305",Ba=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Bu=Buffer.from([48,42,48,5,6,3,43,101,110,3,33,0]);var l6={hashSHA256(r){let e=yn.default.createHash("sha256");if(r instanceof Uint8Array)return e.update(r).digest();for(let t of r)e.update(t);return e.digest()},chaCha20Poly1305Encrypt(r,e,t,n){let s=yn.default.createCipheriv(S_,n,e,{authTagLength:16});if(s.setAAD(t,{plaintextLength:r.byteLength}),r instanceof Uint8Array){let a=s.update(r),c=s.final(),l=s.getAuthTag();return Buffer.concat([a,c,l],a.byteLength+c.byteLength+l.byteLength)}let o=new U;for(let a of r)o.append(s.update(a));let i=s.final();return i.byteLength>0&&o.append(i),o.append(s.getAuthTag()),o},chaCha20Poly1305Decrypt(r,e,t,n,s){let o=r.subarray(r.length-16),i=yn.default.createDecipheriv(S_,n,e,{authTagLength:16}),a;if(r instanceof Uint8Array?a=r.subarray(0,r.length-16):a=r.sublist(0,r.length-16),i.setAAD(t,{plaintextLength:a.byteLength}),i.setAuthTag(o),a instanceof Uint8Array){let u=i.update(a),d=i.final();return d.byteLength>0?Buffer.concat([u,d],u.byteLength+d.byteLength):u}let c=new U;for(let u of a)c.append(i.update(u));let l=i.final();return l.byteLength>0&&c.append(l),c}},C1={hashSHA256(r){return JT(r.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return E_.seal(n,e,r.subarray(),t)},chaCha20Poly1305Decrypt(r,e,t,n,s){let o=E_.open(n,e,r.subarray(),t,s);if(!o)throw new Error("Invalid chacha20poly1305 decryption");return o}},T1={...c6,hashSHA256(r){return l6.hashSHA256(r)},chaCha20Poly1305Encrypt(r,e,t,n){return r.byteLength<1200?C1.chaCha20Poly1305Encrypt(r,e,t,n):l6.chaCha20Poly1305Encrypt(r,e,t,n)},chaCha20Poly1305Decrypt(r,e,t,n,s){return r.byteLength<1200?C1.chaCha20Poly1305Decrypt(r,e,t,n,s):l6.chaCha20Poly1305Decrypt(r,e,t,n,s)},generateX25519KeyPair(){let{publicKey:r,privateKey:e}=yn.default.generateKeyPairSync("x25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return{publicKey:r.subarray(Bu.length),privateKey:e.subarray(Ba.length)}},generateX25519KeyPairFromSeed(r){let e=yn.default.createPrivateKey({key:Buffer.concat([Ba,r],Ba.byteLength+r.byteLength),type:"pkcs8",format:"der"});return{publicKey:yn.default.createPublicKey(e).export({type:"spki",format:"der"}).subarray(Bu.length),privateKey:r}},generateX25519SharedKey(r,e){return e instanceof Uint8Array?e=Buffer.concat([Bu,e],Bu.byteLength+e.byteLength):e=new U(Bu,e).subarray(),r instanceof Uint8Array?r=Buffer.concat([Ba,r],Ba.byteLength+r.byteLength):r=new U(Ba,r).subarray(),yn.default.diffieHellman({publicKey:yn.default.createPublicKey({key:Buffer.from(e.buffer,e.byteOffset,e.byteLength),type:"spki",format:"der"}),privateKey:yn.default.createPrivateKey({key:Buffer.from(r.buffer,r.byteOffset,r.byteLength),type:"pkcs8",format:"der"})})}};n_&&(T1.chaCha20Poly1305Encrypt=C1.chaCha20Poly1305Encrypt,T1.chaCha20Poly1305Decrypt=C1.chaCha20Poly1305Decrypt);function I_(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}rt();var Ua=r=>{let e=tt(2);return e[0]=r>>8,e[1]=r,e};Ua.bytes=2;var Ka=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};Ka.bytes=2;function A_(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}ie();function u6(r,e){!e.enabled||!La||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${T(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${T(r.privateKey,"hex")}`)):e("Missing local static keys."))}function h6(r,e){!e.enabled||!La||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${T(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${T(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function C_(r,e){!e.enabled||!La||e(r?`REMOTE_STATIC_PUBLIC_KEY ${T(r.subarray(),"hex")}`:"Missing remote static public key.")}function d6(r,e){!e.enabled||!La||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${T(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function f6(r,e,t){!t.enabled||!La||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&T(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&T(e.k,"hex")}`))}Be();Ne();rt();cc();bt();re();ie();rt();var Fa=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};rt();var qq=0,Vq=4294967295,Gq="Cipherstate has reached maximum n, a new handshake must be performed",P1=class{n;bytes;view;constructor(e=qq){this.n=e,this.bytes=ce(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Vq)throw new Error(Gq)}};var $o=ce(0),za=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new P1(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let s=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),s}},p6=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=D(t,"utf-8");this.h=Wq(e,n),this.ck=this.h,this.cs=new za(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new za(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new U(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,$o);return[new za(this.crypto,e),new za(this.crypto,t)]}},m6=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:s,initiator:o,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new p6(t,n),this.ss.mixHash(s),this.initiator=o,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let s=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(s),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Uu=class extends m6{writeMessageA(e){return new U(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new U(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new U(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new Fa(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new Fa(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new Fa(`handshake stage 2 validation fail: ${t.message}`)}}};function Wq(r,e){if(e.length<=32){let t=ce(32);return t.set(e),t}else return r.hash(e)}Bt();V();Be();bt();re();wr();rt();var D1;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let o of t.webtransportCerthashes)n.uint32(10),n.bytes(o);if(t.streamMuxers!=null)for(let o of t.streamMuxers)n.uint32(18),n.string(o);s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(s.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===s.limits.webtransportCerthashes)throw new _e('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(t.bytes());break}case 2:{if(s.limits?.streamMuxers!=null&&o.streamMuxers.length===s.limits.streamMuxers)throw new _e('Decode error - map field "streamMuxers" had too many elements');o.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(D1||(D1={}));var Ku;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),D1.codec().encode(t.extensions,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={identityKey:ce(0),identitySig:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.identityKey=t.bytes();break}case 2:{o.identitySig=t.bytes();break}case 4:{o.extensions=D1.codec().decode(t,t.uint32(),{limits:s.limits?.extensions});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Ku||(Ku={}));async function y6(r,e,t){let n=await r.sign(__(e));return Ku.encode({identityKey:dt(r.publicKey),identitySig:n,extensions:t})}async function b6(r,e,t){try{let n=Ku.decode(r),s=Ft(n.identityKey);if(t?.equals(s)===!1)throw new Error(`Payload identity key ${s} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let o=__(e);if(!await s.verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new yh(n.message)}}function __(r){let e=D("noise-libp2p-static-key:");return r instanceof Uint8Array?Ee([e,r],e.length+r.length):(r.prepend(e),r)}var g6=class extends Ts{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new Of({lengthDecoder:Ka,maxBufferSize:16*1024*1024,encodingLength:()=>2});let s=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",s);let o=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",o);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new U;for(let n=0;n<e.byteLength;n+=65519){let s=n+65519;s>e.byteLength&&(s=e.byteLength);let o;e instanceof Uint8Array?o=this.handshake.encrypt(e.subarray(n,s)):o=this.handshake.encrypt(e.sublist(n,s)),this.metrics?.encryptedPackets.increment(),t.append(Ua(o.byteLength)),t.append(o)}return t}decrypt(e){let t=new U;for(let n=0;n<e.byteLength;n+=65535){let s=n+65535;if(s>e.byteLength&&(s=e.byteLength),s-Vw<n)throw new Error("Invalid chunk");let o;e instanceof Uint8Array?o=e.subarray(n,s):o=e.sublist(n,s);let i=e.subarray(n,s-Vw);try{let a=this.handshake.decrypt(o,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function w6(r,e,t){return new g6(r,e,t)}async function P_(r,e){let{log:t,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await y6(o,a.publicKey,l),d=new Uu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});u6(d.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA($o),e),t.trace("Stage 0 - Initiator finished sending first message."),h6(d.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let p=d.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),d6(d.re,t),C_(d.rs,t),t.trace("Initiator going to check remote's signature...");let f=await b6(p,d.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[h,m]=d.ss.split();return f6(h,m,t),{payload:f,encrypt:g=>h.encryptWithAd($o,g),decrypt:(g,y)=>m.decryptWithAd($o,g,y)}}async function D_(r,e){let{log:t,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await y6(o,a.publicKey,l),d=new Uu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});u6(d.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),d6(d.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),h6(d.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let p=d.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let f=await b6(p,d.rs,c),[h,m]=d.ss.split();return f6(h,m,t),{payload:f,encrypt:g=>m.encryptWithAd($o,g),decrypt:(g,y)=>h.decryptWithAd($o,g,y)}}var k1=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:s,crypto:o,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=o??T1;this.crypto=I_(c),this.extensions={webtransportCerthashes:[],...s},this.metrics=a?A_(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ce(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[nt]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,s=_s(e,{lengthEncoder:Ua,lengthDecoder:Ka,maxDataLength:65535}),o=await this.performHandshakeInitiator(s,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Ft(o.payload.identityKey);return{connection:w6(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:On(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let s=t.get(n);if(s!=null)return s}if(e.length)throw new bh("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,s=_s(e,{lengthEncoder:Ua,lengthDecoder:Ka,maxDataLength:65535}),o=await this.performHandshakeResponder(s,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Ft(o.payload.identityKey);return{connection:w6(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:On(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await P_({connection:e,privateKey:t,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await D_({connection:e,privateKey:t,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function k_(r={}){return e=>new k1(e,r)}V();function jq(r){return r.reason}async function x6(r,e,t){if(e==null)return r;let n=t?.translateError??jq;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}Be();V();var Fe;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Fe||(Fe={}));var xe;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(xe||(xe={}));var TIe=Object.values(xe).filter(r=>typeof r!="string"),L_=0,at;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(at||(at={}));var bn=12;var Xn=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function M_(r){return r?.reason!==null}var fr=class extends Xn{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,at.ProtocolError),this.name="InvalidFrameError"}},$a=class extends Xn{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,at.ProtocolError),this.name="UnRequestedPingError"}},Ha=class extends Xn{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,at.ProtocolError),this.name="NotMatchingPingError"}};var L1=class extends Xn{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,at.ProtocolError),this.name="StreamAlreadyExistsError"}},M1=class extends Xn{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,at.ProtocolError),this.name="DecodeInvalidVersionError"}},O1=class extends Xn{static name="BothClientsError";constructor(e="Both clients"){super(e,at.ProtocolError),this.name="BothClientsError"}},qa=class extends Xn{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,at.ProtocolError),this.name="ReceiveWindowExceededError"}};var LIe=new Set([fr.name,$a.name,Ha.name,L1.name,M1.name,O1.name,qa.name]),zu=256*1024,R1=16*1024*1024;var $u={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:zu,maxStreamWindowSize:R1,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function O_(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new B("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new B("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new B("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new B("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<zu)throw new B("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new B("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new B("MaxStreamWindowSize must be less than equal MAX_UINT32")}Be();function N_(r){return r.header.type===Fe.Data&&r.data!==null}var R_=2**24;function Yq(r){if(r[0]!==L_)throw new fr("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*R_+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*R_+(r[9]<<16)+(r[10]<<8)+r[11]}}var N1=class{buffer;constructor(){this.buffer=new U}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=bn;if(this.buffer.byteLength<bn)return;let t=Yq(this.buffer.subarray(0,bn));if(t.type===Fe.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(bn,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function v6(r){let e=new Uint8Array(bn);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}Be();var Ht;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(Ht||(Ht={}));var B1=class extends kf{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??zu;super({...e,maxMessageSize:t-bn}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??R1,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=Ht.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,s=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){s=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let o=Math.min(this.sendWindowCapacity,e.byteLength),i=this.getSendFlags(),a=e.sublist(0,o);e.consume(o);let c=this.sendFrame({type:Fe.Data,flag:i,streamID:this.streamId,length:o},a);if(this.sendWindowCapacity-=o,n+=o,!c){s=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:s}}sendReset(){this.sendFrame({type:Fe.WindowUpdate,flag:xe.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|xe.FIN;this.sendFrame({type:Fe.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=Ht.Paused}sendResume(){this.state=Ht.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-bn,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!N_(e))throw new fr("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new qa("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&xe.ACK)===xe.ACK&&this.state===Ht.SYNSent&&(this.state=Ht.Established),(e&xe.FIN)===xe.FIN&&this.onRemoteCloseWrite(),(e&xe.RST)===xe.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case Ht.Init:return this.state=Ht.SYNSent,xe.SYN;case Ht.SYNReceived:return this.state=Ht.Established,xe.ACK;default:return 0}}sendWindowUpdate(){if(this.state===Ht.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let s=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Fe.WindowUpdate,flag:e,streamID:this.streamId,length:s})}};function B_(r){return{type:Fe[r.type],flags:[(r.flag&xe.SYN)===xe.SYN?"SYN":void 0,(r.flag&xe.ACK)===xe.ACK?"ACK":void 0,(r.flag&xe.FIN)===xe.FIN?"FIN":void 0,(r.flag&xe.RST)===xe.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var U_="/yamux/1.0.0",U1=class{protocol=U_;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[nt]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new E6(e,{...this._init})}},E6=class extends Df{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:U_,name:"yamux"}),this.client=e.direction==="outbound",O_(t),this.enableKeepAlive=t.enableKeepAlive??$u.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??$u.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??$u.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??$u.maxOutboundStreams,this.decoder=new N1,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=y8(async n=>{try{await this.ping(n)}catch(s){this.log.error("ping error: %s",s)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new Tn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Tn("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Jo("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,Ht.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new Tn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Tn("Muxer closed locally");if(this.activePing!=null)return x6(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await x6(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??at.NormalTermination;this.log.trace("muxer close reason=%s",at[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=at.InternalError;M_(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(o=>o.streamId===e)!=null)throw new B("Stream already exists with that id");let s=new B1({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return s.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),s}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:s}=e.header;if(this.log.trace("received frame %o",B_(e.header)),t===0)switch(n){case Fe.Ping:{this.handlePing(e.header);return}case Fe.GoAway:{this.handleGoAway(s);return}default:throw new fr("Invalid frame type")}else switch(e.header.type){case Fe.Data:case Fe.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new fr("Invalid frame type")}}handlePing(e){if(e.flag===xe.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,xe.ACK);else if(e.flag===xe.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new fr("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new $a("ping not requested");if(this.activePing.id!==e)throw new Ha("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",at[e]??"unknown"),this.remoteGoAway=e,e===at.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:s}=e.header;(n&xe.SYN)===xe.SYN&&this.incomingStream(t);let o=this.streams.find(i=>i.streamId===t);if(o===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(s){case Fe.WindowUpdate:{o.handleWindowUpdate(e);return}case Fe.Data:{o.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new B("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Fe.WindowUpdate,flag:xe.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Fe.WindowUpdate,flag:xe.RST,streamID:e,length:0});return}let t=this._newStream(e,Ht.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Fe.Data){if(t==null)throw new fr("Invalid frame");n=new U(v6(e),t)}else n=v6(e);return this.log.trace("sending frame %o",B_(e)),this.send(n)}sendPing(e,t=xe.SYN){t===xe.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:Fe.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=at.NormalTermination){this.log("sending GoAway reason=%s",at[e]),this.localGoAway=e,this.sendFrame({type:Fe.GoAway,flag:0,streamID:0,length:e})}};function K_(r={}){return()=>new U1(r)}var F_="0.1.0";var z_="1.0.0";wr();var Hu;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)n.uint32(18),n.bytes(o);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)n.uint32(26),n.string(o);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={listenAddrs:[],protocols:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 5:{o.protocolVersion=t.string();break}case 6:{o.agentVersion=t.string();break}case 1:{o.publicKey=t.bytes();break}case 2:{if(s.limits?.listenAddrs!=null&&o.listenAddrs.length===s.limits.listenAddrs)throw new _e('Decode error - map field "listenAddrs" had too many elements');o.listenAddrs.push(t.bytes());break}case 4:{o.observedAddr=t.bytes();break}case 3:{if(s.limits?.protocols!=null&&o.protocols.length===s.limits.protocols)throw new _e('Decode error - map field "protocols" had too many elements');o.protocols.push(t.string());break}case 8:{o.signedPeerRecord=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(Hu||(Hu={}));Bt();V();ke();re();var wn={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function $_(r){if(r!=null&&r.length>0)try{return q(r)}catch{}}async function H_(r,e,t,n,s){if(t("received identify from %p",n.remotePeer),s==null)throw new Rt("message was null or undefined");let o={};if(s.listenAddrs.length>0&&(o.addresses=s.listenAddrs.map(c=>({isCertified:!1,multiaddr:q(c)}))),s.protocols.length>0&&(o.protocols=s.protocols),s.publicKey!=null){let c=Ft(s.publicKey);if(!On(c).equals(n.remotePeer))throw new Rt("public key did not match remote PeerId");o.publicKey=c}let i;if(s.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",n.remotePeer);let c=s.signedPeerRecord,l=await lr.openAndCertify(c,ur.DOMAIN),u=ur.createFromProtobuf(l.payload),d=en(l.publicKey.toCID());if(!u.peerId.equals(d))throw new Rt("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(u.peerId))throw new Rt("signing key does not match remote PeerId");let p;try{p=await r.get(u.peerId)}catch(f){if(f.name!=="NotFoundError")throw f}if(p!=null&&(o.metadata=p.metadata,p.peerRecordEnvelope!=null)){let f=lr.createFromProtobuf(p.peerRecordEnvelope),h=ur.createFromProtobuf(f.payload);h.seqNumber>=u.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",h.seqNumber,u.seqNumber),u=h,c=p.peerRecordEnvelope)}o.peerRecordEnvelope=c,o.addresses=u.multiaddrs.map(f=>({isCertified:!0,multiaddr:f})),i={seq:u.seqNumber,addresses:u.multiaddrs}}else t("%p did not send a signed peer record",n.remotePeer);if(t.trace("patching %p with",n.remotePeer,o),await r.patch(n.remotePeer,o),s.agentVersion!=null||s.protocolVersion!=null){let c={};s.agentVersion!=null&&(c.AgentVersion=D(s.agentVersion)),s.protocolVersion!=null&&(c.ProtocolVersion=D(s.protocolVersion)),t.trace("merging %p metadata",n.remotePeer,c),await r.merge(n.remotePeer,{metadata:c})}let a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map(c=>q(c)),observedAddr:s.observedAddr==null?void 0:q(s.observedAddr),protocols:s.protocols,signedPeerRecord:i,connection:n};return e.safeDispatchEvent("peer:identify",{detail:a}),a}var K1=class{host;components;protocol;started;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.components=e,this.log=t.log,this.timeout=t.timeout??wn.timeout,this.maxInboundStreams=t.maxInboundStreams??wn.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??wn.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??wn.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??wn.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??wn.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??wn.protocolPrefix}/${F_}`,agentVersion:e.nodeInfo.userAgent},this.handleProtocol=this.handleProtocol.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.merge(this.components.peerId,{metadata:{AgentVersion:D(this.host.agentVersion),ProtocolVersion:D(this.host.protocolVersion)}}),await this.components.registrar.handle(this.protocol,this.handleProtocol,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}};Bt();V();ke();Ue();var F1=class extends K1{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??wn.protocolPrefix}/${"id"}/${z_}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??wn.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let s=n.detail;this.identify(s).catch(()=>{})})}[nt]=["@libp2p/identify"];async _identify(e,t={}){let n,s;if(t.signal==null){let o=AbortSignal.timeout(this.timeout);Y(1/0,o),t={...t,signal:o}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),s=n.log.newScope("identify");let o=zr(n,{maxDataLength:this.maxMessageSize}).pb(Hu),i=await o.read(t);return await o.unwrap().unwrap().close(t),i}catch(o){throw s?.error("identify failed - %e",o),n?.abort(o),o}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:s,protocols:o,observedAddr:i}=n;if(s==null)throw new Rt("Public key was missing from identify message");let a=Ft(s),c=en(a.toCID());if(!e.remotePeer.equals(c))throw new Rt("Identified peer does not match the expected peer");if(this.components.peerId.equals(c))throw new Rt("Identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("completed for peer %p and protocols %o",c,o),H_(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){let t=$_(e);if(t==null||(this.log.trace("our observed address was %a",t),zn(t)))return;let n=t.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!o8(t)){this.log.trace("our observed address was IPv6 but not a global unicast address");return}Fn.exactMatch(t)||(this.log.trace("storing the observed address"),this.components.addressManager.addObservedAddr(t))}async handleProtocol(e,t){let n=e.log.newScope("identify");n("responding to identify");let s=AbortSignal.timeout(this.timeout);Y(1/0,s);let o=await this.components.peerStore.get(this.components.peerId,{signal:s}),i=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),a=o.peerRecordEnvelope;if(i.length>0&&a==null){let u=new ur({peerId:this.components.peerId,multiaddrs:i});a=(await lr.seal(u,this.components.privateKey,{signal:s})).marshal().subarray()}let c=t.remoteAddr.bytes;XA.matches(t.remoteAddr)||(c=void 0);let l=zr(e).pb(Hu);n("send response"),await l.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:dt(this.components.privateKey.publicKey),listenAddrs:i.map(u=>u.bytes),signedPeerRecord:a,observedAddr:c,protocols:o.protocols},{signal:s}),n("close write"),await l.unwrap().unwrap().close({signal:s})}};function q_(r={}){return e=>new F1(e,r)}V();function Zq(r){return r.reason}async function V_(r,e,t){if(e==null)return r;let n=t?.translateError??Zq;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}Be();Ne();var G_="1.0.0",W_="ping",j_="ipfs";var z1=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??j_}/${W_}/${G_}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[nt]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handlePing,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async handlePing(e,t){let n=e.log.newScope("ping");n.trace("ping from %p",t.remotePeer);let s=AbortSignal.timeout(this.timeout);Y(1/0,s),s.addEventListener("abort",()=>{e.abort(new Gr("Ping timed out"))});let o=Date.now();for await(let i of e){if(e.status!=="open"){n("stream status changed to %s",e.status);break}e.send(i)||(n("waiting for stream to drain"),await Re(e,"drain",{rejectionEvents:["close"],signal:s}),n("stream drained"))}n("ping from %p complete in %dms",t.remotePeer,Date.now()-o),await e.close({signal:s})}async ping(e,t={}){let n=fs(32),s=await this.components.connectionManager.openStream(e,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...t}),o=s.log.newScope("ping");try{let i=Date.now(),a=Promise.withResolvers(),c=new U,l=u=>{if(c.append(u.data),c.byteLength===32){s.removeEventListener("message",l);let d=Date.now()-i;Promise.all([s.closeRead(t)]).then(()=>{if(W(n,c.subarray()))a.resolve(d);else throw new Sh(`Received wrong ping ack after ${d}ms`)}).catch(p=>{s.abort(p),a.reject(p)})}};return s.addEventListener("message",l),s.send(n),await s.close(t),await V_(a.promise,t.signal)}catch(i){throw o.error("error while pinging %o - %e",e,i),s?.abort(i),i}finally{s?.close()}}};function X_(r={}){return e=>new z1(e,r)}var S6=Symbol.for("@libp2p/peer-id");var Ho="StrictSign",Va="StrictNoSign",qt;(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(qt||(qt={}));var YAe=Symbol.for("@libp2p/pubsub");var $1=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var H1=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},q1=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};Ue();var Q_=Symbol.for("@libp2p/service-capabilities"),J_=Symbol.for("@libp2p/service-dependencies");var ct=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ga=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var qu=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var _6={};z(_6,{base58btc:()=>Xe,base58flickr:()=>lV});var x8e=new Uint8Array(0);function Z_(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _r(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function eP(r){return new TextEncoder().encode(r)}function tP(r){return new TextDecoder().decode(r)}function nV(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,w=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,x=E-1;(v!==0||S<g)&&x!==-1;x--,S++)v+=256*w[x]>>>0,w[x]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&w[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(w[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var w=t[h.charCodeAt(m)];if(w===255)return;for(var v=0,S=b-1;(w!==0||v<y)&&S!==-1;S--,v++)w+=a*E[S]>>>0,E[S]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var x=b-y;x!==b&&E[x]===0;)x++;for(var I=new Uint8Array(g+(b-x)),A=g;x!==b;)I[A++]=E[x++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var sV=nV,oV=sV,nP=oV;var I6=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},A6=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 sP(this,e)}},C6=class{decoders;constructor(e){this.decoders=e}or(e){return sP(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function sP(r,e){return new C6({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var T6=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new I6(e,t,n),this.decoder=new A6(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Wa({name:r,prefix:e,encode:t,decode:n}){return new T6(r,e,t,n)}function Ms({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=nP(t,r);return Wa({prefix:e,name:r,encode:n,decode:o=>_r(s(o))})}function iV(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function aV(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function cV(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ye({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=cV(n);return Wa({prefix:e,name:r,encode(o){return aV(o,n,t)},decode(o){return iV(o,s,t,r)}})}var Xe=Ms({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),lV=Ms({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var P6={};z(P6,{base32:()=>Os,base32hex:()=>fV,base32hexpad:()=>mV,base32hexpadupper:()=>gV,base32hexupper:()=>pV,base32pad:()=>hV,base32padupper:()=>dV,base32upper:()=>uV,base32z:()=>yV});var Os=Ye({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),uV=Ye({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hV=Ye({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),dV=Ye({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fV=Ye({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pV=Ye({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),mV=Ye({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gV=Ye({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yV=Ye({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var D6={};z(D6,{base36:()=>Vu,base36upper:()=>bV});var Vu=Ms({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bV=Ms({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wV=aP,oP=128,xV=127,vV=~xV,EV=Math.pow(2,31);function aP(r,e,t){e=e||[],t=t||0;for(var n=t;r>=EV;)e[t++]=r&255|oP,r/=128;for(;r&vV;)e[t++]=r&255|oP,r>>>=7;return e[t]=r|0,aP.bytes=t-n+1,e}var SV=k6,IV=128,iP=127;function k6(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw k6.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&iP)<<s:(i&iP)*Math.pow(2,s),s+=7}while(i>=IV);return k6.bytes=o-n,t}var AV=Math.pow(2,7),CV=Math.pow(2,14),TV=Math.pow(2,21),_V=Math.pow(2,28),PV=Math.pow(2,35),DV=Math.pow(2,42),kV=Math.pow(2,49),LV=Math.pow(2,56),MV=Math.pow(2,63),OV=function(r){return r<AV?1:r<CV?2:r<TV?3:r<_V?4:r<PV?5:r<DV?6:r<kV?7:r<LV?8:r<MV?9:10},RV={encode:wV,decode:SV,encodingLength:OV},NV=RV,Gu=NV;function Wu(r,e=0){return[Gu.decode(r,e),Gu.decode.bytes]}function ja(r,e,t=0){return Gu.encode(r,e,t),e}function Ya(r){return Gu.encodingLength(r)}function xn(r,e){let t=e.byteLength,n=Ya(r),s=n+Ya(t),o=new Uint8Array(s+t);return ja(r,o,0),ja(t,o,n),o.set(e,s),new Xa(r,t,e,o)}function Qn(r){let e=_r(r),[t,n]=Wu(e),[s,o]=Wu(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Xa(t,s,i,e)}function cP(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Z_(r.bytes,t.bytes)}}var Xa=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function lP(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return UV(t,L6(r),e??Xe.encoder);default:return KV(t,L6(r),e??Os.encoder)}}var uP=new WeakMap;function L6(r){let e=uP.get(r);if(e==null){let t=new Map;return uP.set(r,t),t}return e}var lt=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==ju)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==FV)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=xn(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&cP(e.multihash,n.multihash)}toString(e){return lP(this,e)}toJSON(){return{"/":lP(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??hP(n,s,o.bytes))}else if(t[zV]===!0){let{version:n,multihash:s,code:o}=t,i=Qn(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ju)throw new Error(`Version 0 CID must use dag-pb (code: ${ju}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=hP(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ju,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=_r(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Xa(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=Wu(e.subarray(t));return t+=p,d},s=n(),o=ju;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=BV(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return L6(o).set(n,e),o}};function BV(r,e){switch(r[0]){case"Q":{let t=e??Xe;return[Xe.prefix,t.decode(`${Xe.prefix}${r}`)]}case Xe.prefix:{let t=e??Xe;return[Xe.prefix,t.decode(r)]}case Os.prefix:{let t=e??Os;return[Os.prefix,t.decode(r)]}case Vu.prefix:{let t=e??Vu;return[Vu.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function UV(r,e,t){let{prefix:n}=t;if(n!==Xe.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function KV(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var ju=112,FV=18;function hP(r,e,t){let n=Ya(r),s=n+Ya(e),o=new Uint8Array(s+t.byteLength);return ja(r,o,0),ja(e,o,n),o.set(t,s),o}var zV=Symbol.for("@ipld/js-cid/CID");var M6={};z(M6,{identity:()=>$r});var dP=0,$V="identity",fP=_r;function HV(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return xn(dP,fP(r))}var $r={code:dP,name:$V,encode:fP,digest:HV};Ne();Be();re();ie();Be();var qV=parseInt("11111",2),O6=parseInt("10000000",2),VV=parseInt("01111111",2),pP={0:Yu,1:Yu,2:GV,3:YV,4:XV,5:jV,6:WV,16:Yu,22:Yu,48:Yu};function Jn(r,e={offset:0}){let t=r[e.offset]&qV;if(e.offset++,pP[t]!=null)return pP[t](r,e);throw new Error("No decoder for tag "+t)}function Xu(r,e){let t=0;if((r[e.offset]&O6)===O6){let n=r[e.offset]&VV,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Yu(r,e){Xu(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Jn(r,e);if(n===null)break;t.push(n)}return t}function GV(r,e){let t=Xu(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function WV(r,e){let t=Xu(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function jV(r,e){return e.offset++,null}function YV(r,e){let t=Xu(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function XV(r,e){let t=Xu(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function QV(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new U;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function R6(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=QV(r.byteLength);return new U(Uint8Array.from([e.byteLength|O6]),e)}function tr(r){let e=new U,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new U(Uint8Array.from([2]),R6(e),e)}function G1(r){let e=Uint8Array.from([0]),t=new U(e,r);return new U(Uint8Array.from([3]),R6(t),t)}function Ns(r,e=48){let t=new U;for(let n of r)t.append(n);return new U(Uint8Array.from([e]),R6(t),t)}async function mP(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var JV=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ZV=Uint8Array.from([6,5,43,129,4,0,34]),eG=Uint8Array.from([6,5,43,129,4,0,35]),tG={ext:!0,kty:"EC",crv:"P-256"},rG={ext:!0,kty:"EC",crv:"P-384"},nG={ext:!0,kty:"EC",crv:"P-521"},N6=32,B6=48,U6=66;function K6(r){let e=Jn(r);return gP(e)}function gP(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===N6*2+1)return n=T(e.subarray(t,t+N6),"base64url"),s=T(e.subarray(t+N6),"base64url"),new Qa({...tG,key_ops:["verify"],x:n,y:s});if(e.byteLength===B6*2+1)return n=T(e.subarray(t,t+B6),"base64url"),s=T(e.subarray(t+B6),"base64url"),new Qa({...rG,key_ops:["verify"],x:n,y:s});if(e.byteLength===U6*2+1)return n=T(e.subarray(t,t+U6),"base64url"),s=T(e.subarray(t+U6),"base64url"),new Qa({...nG,key_ops:["verify"],x:n,y:s});throw new ct(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function yP(r){return Ns([tr(Uint8Array.from([1])),Ns([sG(r.crv)],160),Ns([G1(new U(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function sG(r){if(r==="P-256")return JV;if(r==="P-384")return ZV;if(r==="P-521")return eG;throw new ct(`Invalid curve ${r}`)}var Qa=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=yP(this.jwk)),this._raw}toMultihash(){return $r.digest(Bs(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async verify(e,t,n){return mP(this.jwk,t,e,n)}};var W1=ae(te("crypto"),1);bt();re();ie();var lCe=W1.default.generateKeyPairSync,Qu=32;var oG=64;function bP(r,e,t){if(r.byteLength!==Qu)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==oG)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=W1.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:T(r,"base64url"),kty:"OKP"}});return W1.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}Ne();bt();re();function xP(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var j1=class{type="Ed25519";raw;constructor(e){this.raw=F6(e,Qu)}toMultihash(){return $r.digest(Bs(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=bP(this.raw,t,e);return xP(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function z6(r){return r=F6(r,Qu),new j1(r)}function F6(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new ct(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}wr();var Ze;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ze||(Ze={}));var $6;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})($6||($6={}));(function(r){r.codec=()=>sr($6)})(Ze||(Ze={}));var vn;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ze.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Ze.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(vn||(vn={}));var H6;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ze.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Ze.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(H6||(H6={}));var X1=ae(te("node:crypto"),1),PP=te("node:util");re();Jr();function Y1(r){if(isNaN(r)||r<=0)throw new ct("random bytes length must be a Number bigger than 0");return Qr(r)}var Zu={};z(Zu,{MAX_RSA_KEY_SIZE:()=>q6,generateRSAKeyPair:()=>AP,jwkToJWKKeyPair:()=>CP,jwkToPkcs1:()=>uG,jwkToPkix:()=>j6,jwkToRSAPrivateKey:()=>J6,pkcs1MessageToJwk:()=>G6,pkcs1MessageToRSAPrivateKey:()=>Y6,pkcs1ToJwk:()=>lG,pkcs1ToRSAPrivateKey:()=>IP,pkixMessageToJwk:()=>W6,pkixMessageToRSAPublicKey:()=>Q6,pkixToJwk:()=>hG,pkixToRSAPublicKey:()=>X6});Kc();re();ie();Ne();var Ja=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Zu.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return lt.createV1(114,this._multihash)}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return SP(this.jwk,t,e,n)}},Ju=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Zu.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return EP(this.jwk,e,t)}};var q6=8192,V6=18,aG=1062,cG=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function lG(r){let e=Jn(r);return G6(e)}function G6(r){return{n:T(r[1],"base64url"),e:T(r[2],"base64url"),d:T(r[3],"base64url"),p:T(r[4],"base64url"),q:T(r[5],"base64url"),dp:T(r[6],"base64url"),dq:T(r[7],"base64url"),qi:T(r[8],"base64url"),kty:"RSA"}}function uG(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new ct("JWK was missing components");return Ns([tr(Uint8Array.from([0])),tr(D(r.n,"base64url")),tr(D(r.e,"base64url")),tr(D(r.d,"base64url")),tr(D(r.p,"base64url")),tr(D(r.q,"base64url")),tr(D(r.dp,"base64url")),tr(D(r.dq,"base64url")),tr(D(r.qi,"base64url"))]).subarray()}function hG(r){let e=Jn(r,{offset:0});return W6(e)}function W6(r){let e=Jn(r[1],{offset:0});return{kty:"RSA",n:T(e[0],"base64url"),e:T(e[1],"base64url")}}function j6(r){if(r.n==null||r.e==null)throw new ct("JWK was missing components");return Ns([cG,G1(Ns([tr(D(r.n,"base64url")),tr(D(r.e,"base64url"))]))]).subarray()}function IP(r){let e=Jn(r);return Y6(e)}function Y6(r){let e=G6(r);return J6(e)}function X6(r,e){if(r.byteLength>=aG)throw new Ga("Key size is too large");let t=Jn(r,{offset:0});return Q6(t,r,e)}function Q6(r,e,t){let n=W6(r);if(t==null){let s=Yt(vn.encode({Type:Ze.RSA,Data:e}));t=xn(V6,s)}return new Ja(n,t)}function J6(r){if(_P(r)>q6)throw new ct("Key size is too large");let e=CP(r),t=Yt(vn.encode({Type:Ze.RSA,Data:j6(e.publicKey)})),n=xn(V6,t);return new Ju(e.privateKey,new Ja(e.publicKey,n))}async function AP(r){if(r>q6)throw new ct("Key size is too large");let e=await TP(r),t=Yt(vn.encode({Type:Ze.RSA,Data:j6(e.publicKey)})),n=xn(V6,t);return new Ju(e.privateKey,new Ja(e.publicKey,n))}function CP(r){if(r==null)throw new ct("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var dG=(0,PP.promisify)(X1.default.generateKeyPair);async function TP(r,e){let t=await dG("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function EP(r,e,t){t?.signal?.throwIfAborted();let n=X1.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)n.update(e);else for(let s of e)n.update(s);return n.sign({format:"jwk",key:r})}function SP(r,e,t,n){n?.signal?.throwIfAborted();let s=X1.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)s.update(t);else for(let o of t)s.update(o);return s.verify({format:"jwk",key:r},e)}function _P(r){if(r.kty!=="RSA")throw new ct("Invalid key type");if(r.n==null)throw new ct("Invalid key modulus");return D(r.n,"base64url").length*8}var DP=ae(te("node:crypto"),1);eo();var Q1=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function kP(r,e,t,n){n?.signal?.throwIfAborted();let s=DP.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return st.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new Q1(String(i))}}eo();Ne();var J1=class{type="secp256k1";raw;_key;constructor(e){this._key=MP(e),this.raw=LP(this._key)}toMultihash(){return $r.digest(Bs(this))}toCID(){return lt.createV1(114,this.toMultihash())}toString(){return Xe.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return kP(this._key,t,e,n)}};function Z6(r){return new J1(r)}function LP(r){return st.Point.fromBytes(r).toBytes()}function MP(r){try{return st.Point.fromBytes(r),r}catch(e){throw new Ga(String(e))}}function e5(r,e){let{Type:t,Data:n}=vn.decode(r),s=n??new Uint8Array;switch(t){case Ze.RSA:return X6(s,e);case Ze.Ed25519:return z6(s);case Ze.secp256k1:return Z6(s);case Ze.ECDSA:return K6(s);default:throw new qu}}function OP(r){let{Type:e,Data:t}=vn.decode(r.digest),n=t??new Uint8Array;switch(e){case Ze.Ed25519:return z6(n);case Ze.secp256k1:return Z6(n);case Ze.ECDSA:return K6(n);default:throw new qu}}function Bs(r){return vn.encode({Type:Ze[r.type],Data:r.raw})}var s5={};z(s5,{sha256:()=>eh,sha512:()=>pG});var n5=ae(te("crypto"),1);var fG=20;function r5({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new t5(r,e,t,n,s)}var t5=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??fG,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?RP(n,this.code,t?.truncate):n.then(s=>RP(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function RP(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return xn(e,r)}var eh=r5({name:"sha2-256",code:18,encode:r=>_r(n5.default.createHash("sha256").update(r).digest())}),pG=r5({name:"sha2-512",code:19,encode:r=>_r(n5.default.createHash("sha512").update(r).digest())});ie();Ne();re();ie();var BP=Symbol.for("nodejs.util.inspect.custom"),mG=114,th=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[S6]=!0;toString(){return this.string==null&&(this.string=Xe.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return lt.createV1(mG,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[BP](){return`PeerId(${this.toString()})`}},Z1=class extends th{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},em=class extends th{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},tm=class extends th{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},gG=2336,rh=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=$r.digest(D(this.url))}[BP](){return`PeerId(${this.url})`}[S6]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return lt.createV1(gG,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=T(e)),e.toString()===this.toString())}};var yG=114,UP=2336;function qo(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Qn(Xe.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return bG(lt.parse(r));if(e==null)throw new $1('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Qn(e.decode(r))}return Za(t)}function Za(r){if(xG(r))return new Z1({multihash:r});if(wG(r))try{let e=OP(r);if(e.type==="Ed25519")return new em({multihash:r,publicKey:e});if(e.type==="secp256k1")return new tm({multihash:r,publicKey:e})}catch{let t=T(r.digest);return new rh(new URL(t))}throw new q1("Supplied PeerID Multihash is invalid")}function bG(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==yG&&r.code!==UP)throw new H1("Supplied PeerID CID is invalid");if(r.code===UP){let e=T(r.multihash.digest);return new rh(new URL(e))}return Za(r.multihash)}function wG(r){return r.code===$r.code}function xG(r){return r.code===eh.code}gr();Be();rt();function rm(r){return r[Symbol.asyncIterator]!=null}var nm=r=>{let e=Ae(r),t=tt(e);return Vr(r,t),nm.bytes=e,t};nm.bytes=0;function ec(r,e){e=e??{};let t=e.lengthEncoder??nm;function*n(s){let o=t(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return rm(r)?(async function*(){for await(let s of r)yield*n(s)})():(function*(){for(let s of r)yield*n(s)})()}ec.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??nm;return new U(t(r.byteLength),r)};gr();Be();var sm=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},om=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},im=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},nh=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var vG=8,EG=1024*1024*4,Vo;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Vo||(Vo={}));var o5=r=>{let e=jt(r);return o5.bytes=Ae(e),e};o5.bytes=0;function sh(r,e){let t=new U,n=Vo.LENGTH,s=-1,o=e?.lengthDecoder??o5,i=e?.maxLengthLength??vG,a=e?.maxDataLength??EG;function*c(){for(;t.byteLength>0;){if(n===Vo.LENGTH)try{if(s=o(t),s<0)throw new sm("Invalid message length");if(s>a)throw new om("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Vo.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new im("Message length length too long");break}throw l}if(n===Vo.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Vo.LENGTH}}}return rm(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new nh("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new nh("Unexpected end of input")})()}sh.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return sh(n,{...e??{},onLength:o=>{t=o}})};var i5="/floodsub/1.0.0",a5="/meshsub/1.0.0",KP="/meshsub/1.1.0",am="/meshsub/1.2.0";var FP="ERR_TOPIC_VALIDATOR_REJECT",zP="ERR_TOPIC_VALIDATOR_IGNORE";var $P={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};wr();var Zn;(function(r){let e;(function(d){let p;d.codec=()=>(p==null&&(p=Z((f,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),f.subscribe!=null&&(h.uint32(8),h.bool(f.subscribe)),f.topic!=null&&(h.uint32(18),h.string(f.topic)),m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.subscribe=f.bool();break}case 2:{g.topic=f.string();break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>J(f,d.codec()),d.decode=(f,h)=>Q(f,d.codec(),h)})(e=r.SubOpts||(r.SubOpts={}));let t;(function(d){let p;d.codec=()=>(p==null&&(p=Z((f,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),f.from!=null&&(h.uint32(10),h.bytes(f.from)),f.data!=null&&(h.uint32(18),h.bytes(f.data)),f.seqno!=null&&(h.uint32(26),h.bytes(f.seqno)),f.topic!=null&&f.topic!==""&&(h.uint32(34),h.string(f.topic)),f.signature!=null&&(h.uint32(42),h.bytes(f.signature)),f.key!=null&&(h.uint32(50),h.bytes(f.key)),m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={topic:""},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.from=f.bytes();break}case 2:{g.data=f.bytes();break}case 3:{g.seqno=f.bytes();break}case 4:{g.topic=f.string();break}case 5:{g.signature=f.bytes();break}case 6:{g.key=f.bytes();break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>J(f,d.codec()),d.decode=(f,h)=>Q(f,d.codec(),h)})(t=r.Message||(r.Message={}));let n;(function(d){let p;d.codec=()=>(p==null&&(p=Z((f,h,m={})=>{if(m.lengthDelimited!==!1&&h.fork(),f.ihave!=null)for(let g of f.ihave)h.uint32(10),r.ControlIHave.codec().encode(g,h);if(f.iwant!=null)for(let g of f.iwant)h.uint32(18),r.ControlIWant.codec().encode(g,h);if(f.graft!=null)for(let g of f.graft)h.uint32(26),r.ControlGraft.codec().encode(g,h);if(f.prune!=null)for(let g of f.prune)h.uint32(34),r.ControlPrune.codec().encode(g,h);if(f.idontwant!=null)for(let g of f.idontwant)h.uint32(42),r.ControlIDontWant.codec().encode(g,h);m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.ihave!=null&&g.ihave.length===m.limits.ihave)throw new _e('Decode error - map field "ihave" had too many elements');g.ihave.push(r.ControlIHave.codec().decode(f,f.uint32(),{limits:m.limits?.ihave$}));break}case 2:{if(m.limits?.iwant!=null&&g.iwant.length===m.limits.iwant)throw new _e('Decode error - map field "iwant" had too many elements');g.iwant.push(r.ControlIWant.codec().decode(f,f.uint32(),{limits:m.limits?.iwant$}));break}case 3:{if(m.limits?.graft!=null&&g.graft.length===m.limits.graft)throw new _e('Decode error - map field "graft" had too many elements');g.graft.push(r.ControlGraft.codec().decode(f,f.uint32(),{limits:m.limits?.graft$}));break}case 4:{if(m.limits?.prune!=null&&g.prune.length===m.limits.prune)throw new _e('Decode error - map field "prune" had too many elements');g.prune.push(r.ControlPrune.codec().decode(f,f.uint32(),{limits:m.limits?.prune$}));break}case 5:{if(m.limits?.idontwant!=null&&g.idontwant.length===m.limits.idontwant)throw new _e('Decode error - map field "idontwant" had too many elements');g.idontwant.push(r.ControlIDontWant.codec().decode(f,f.uint32(),{limits:m.limits?.idontwant$}));break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>J(f,d.codec()),d.decode=(f,h)=>Q(f,d.codec(),h)})(n=r.ControlMessage||(r.ControlMessage={}));let s;(function(d){let p;d.codec=()=>(p==null&&(p=Z((f,h,m={})=>{if(m.lengthDelimited!==!1&&h.fork(),f.topicID!=null&&(h.uint32(10),h.string(f.topicID)),f.messageIDs!=null)for(let g of f.messageIDs)h.uint32(18),h.bytes(g);m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={messageIDs:[]},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}case 2:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new _e('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>J(f,d.codec()),d.decode=(f,h)=>Q(f,d.codec(),h)})(s=r.ControlIHave||(r.ControlIHave={}));let o;(function(d){let p;d.codec=()=>(p==null&&(p=Z((f,h,m={})=>{if(m.lengthDelimited!==!1&&h.fork(),f.messageIDs!=null)for(let g of f.messageIDs)h.uint32(10),h.bytes(g);m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={messageIDs:[]},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new _e('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>J(f,d.codec()),d.decode=(f,h)=>Q(f,d.codec(),h)})(o=r.ControlIWant||(r.ControlIWant={}));let i;(function(d){let p;d.codec=()=>(p==null&&(p=Z((f,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),f.topicID!=null&&(h.uint32(10),h.string(f.topicID)),m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>J(f,d.codec()),d.decode=(f,h)=>Q(f,d.codec(),h)})(i=r.ControlGraft||(r.ControlGraft={}));let a;(function(d){let p;d.codec=()=>(p==null&&(p=Z((f,h,m={})=>{if(m.lengthDelimited!==!1&&h.fork(),f.topicID!=null&&(h.uint32(10),h.string(f.topicID)),f.peers!=null)for(let g of f.peers)h.uint32(18),r.PeerInfo.codec().encode(g,h);f.backoff!=null&&(h.uint32(24),h.uint64Number(f.backoff)),m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={peers:[]},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}case 2:{if(m.limits?.peers!=null&&g.peers.length===m.limits.peers)throw new _e('Decode error - map field "peers" had too many elements');g.peers.push(r.PeerInfo.codec().decode(f,f.uint32(),{limits:m.limits?.peers$}));break}case 3:{g.backoff=f.uint64Number();break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>J(f,d.codec()),d.decode=(f,h)=>Q(f,d.codec(),h)})(a=r.ControlPrune||(r.ControlPrune={}));let c;(function(d){let p;d.codec=()=>(p==null&&(p=Z((f,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),f.peerID!=null&&(h.uint32(10),h.bytes(f.peerID)),f.signedPeerRecord!=null&&(h.uint32(18),h.bytes(f.signedPeerRecord)),m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.peerID=f.bytes();break}case 2:{g.signedPeerRecord=f.bytes();break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>J(f,d.codec()),d.decode=(f,h)=>Q(f,d.codec(),h)})(c=r.PeerInfo||(r.PeerInfo={}));let l;(function(d){let p;d.codec=()=>(p==null&&(p=Z((f,h,m={})=>{if(m.lengthDelimited!==!1&&h.fork(),f.messageIDs!=null)for(let g of f.messageIDs)h.uint32(10),h.bytes(g);m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={messageIDs:[]},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new _e('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>J(f,d.codec()),d.decode=(f,h)=>Q(f,d.codec(),h)})(l=r.ControlIDontWant||(r.ControlIDontWant={}));let u;r.codec=()=>(u==null&&(u=Z((d,p,f={})=>{if(f.lengthDelimited!==!1&&p.fork(),d.subscriptions!=null)for(let h of d.subscriptions)p.uint32(10),r.SubOpts.codec().encode(h,p);if(d.messages!=null)for(let h of d.messages)p.uint32(18),r.Message.codec().encode(h,p);d.control!=null&&(p.uint32(26),r.ControlMessage.codec().encode(d.control,p)),f.lengthDelimited!==!1&&p.ldelim()},(d,p,f={})=>{let h={subscriptions:[],messages:[]},m=p==null?d.len:d.pos+p;for(;d.pos<m;){let g=d.uint32();switch(g>>>3){case 1:{if(f.limits?.subscriptions!=null&&h.subscriptions.length===f.limits.subscriptions)throw new _e('Decode error - map field "subscriptions" had too many elements');h.subscriptions.push(r.SubOpts.codec().decode(d,d.uint32(),{limits:f.limits?.subscriptions$}));break}case 2:{if(f.limits?.messages!=null&&h.messages.length===f.limits.messages)throw new _e('Decode error - map field "messages" had too many elements');h.messages.push(r.Message.codec().decode(d,d.uint32(),{limits:f.limits?.messages$}));break}case 3:{h.control=r.ControlMessage.codec().decode(d,d.uint32(),{limits:f.limits?.control});break}default:{d.skipType(g&7);break}}}return h})),u),r.encode=d=>J(d,r.codec()),r.decode=(d,p)=>Q(d,r.codec(),p)})(Zn||(Zn={}));var cm=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,n){this.gossip=e,this.msgIdToStrFn=n;for(let s=0;s<t;s++)this.history[s]=[]}get size(){return this.msgs.size}put(e,t,n=!1){let{msgIdStr:s}=e;return this.msgs.has(s)?!1:(this.msgs.set(s,{message:t,validated:n,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),n||this.notValidatedCount++,!0)}observeDuplicate(e,t){let n=this.msgs.get(e);n!=null&&!n.validated&&n.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let n=this.msgs.get(e);if(n==null)return null;let s=(n.iwantCounts.get(t)??0)+1;return n.iwantCounts.set(t,s),{msg:n.message,count:s}}getGossipIDs(e){let t=new Map;for(let n=0;n<this.gossip;n++)this.history[n].forEach(s=>{if((this.msgs.get(s.msgIdStr)?.validated??!1)&&e.has(s.topic)){let i=t.get(s.topic);i==null&&(i=[],t.set(s.topic,i)),i.push(s.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:n,originatingPeers:s}=t;return t.validated=!0,t.originatingPeers=new Set,{message:n,originatingPeers:s}}shift(){this.history[this.history.length-1].forEach(t=>{let n=this.msgs.get(t.msgIdStr);n!=null&&(this.msgs.delete(t.msgIdStr),n.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t==null?null:(this.msgs.delete(e),t)}};var HP;(function(r){r.StrictSign="StrictSign",r.StrictNoSign="StrictNoSign"})(HP||(HP={}));var Us;(function(r){r[r.Signing=0]="Signing",r[r.Anonymous=1]="Anonymous"})(Us||(Us={}));var Vt;(function(r){r.Error="error",r.Ignore="ignore",r.Reject="reject",r.Blacklisted="blacklisted"})(Vt||(Vt={}));var Lt;(function(r){r.InvalidSignature="invalid_signature",r.InvalidSeqno="invalid_seqno",r.InvalidPeerId="invalid_peerid",r.SignaturePresent="signature_present",r.SeqnoPresent="seqno_present",r.FromPresent="from_present",r.TransformFailed="transform_failed"})(Lt||(Lt={}));var Mt;(function(r){r.duplicate="duplicate",r.invalid="invalid",r.valid="valid"})(Mt||(Mt={}));function c5(r){switch(r){case qt.Ignore:return Vt.Ignore;case qt.Reject:return Vt.Reject;default:throw new Error("Unreachable")}}var qP;(function(r){r.forward="forward",r.publish="publish"})(qP||(qP={}));var Gt;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(Gt||(Gt={}));var Hr;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Excess="excess"})(Hr||(Hr={}));var rc;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(rc||(rc={}));var nc;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(nc||(nc={}));var tc;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(tc||(tc={}));function VP(r,e,t){return{protocolsEnabled:r.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:r.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:r.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:r.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:r.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:r.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:r.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:r.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:r.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:r.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:r.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:r.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:r.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:r.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:r.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:r.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:r.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:r.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:r.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:r.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:r.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:r.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:r.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:r.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:r.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:r.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:r.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:r.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:r.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:r.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:r.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:r.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:r.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:r.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:r.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:r.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:r.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:r.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:r.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:r.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:r.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),rpcSentIDontWant:r.gauge({name:"gossipsub_rpc_sent_idontwant_total",help:"RPC sent"}),msgPublishCount:r.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:r.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:r.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:r.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:r.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:r.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:r.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:r.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:r.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:r.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:r.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:r.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:r.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:r.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:r.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:r.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:r.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:r.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:r.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,Number(t.maxMeshMessageDeliveriesWindowSec),2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:r.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:r.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:r.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:r.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:r.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:r.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:r.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:r.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:r.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:r.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:r.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,Number(t.behaviourPenaltyThreshold),2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:r.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:r.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:r.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:r.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),idontwantRcvMsgids:r.gauge({name:"gossipsub_idontwant_rcv_msgids_total",help:"Total received IDONTWANT messages"}),idontwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_idontwant_rcv_dont_have_msgids_total",help:"Total received IDONTWANT messageIDs that we do not have in mcache"}),iwantPromiseStarted:r.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:r.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:r.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:r.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:r.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:r.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:r.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,Number(t.gossipPromiseExpireSec),2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:r.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:r.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:r.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:r.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:r.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:r.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:r.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(n){return this.topicStrToLabel.get(n)??n},onJoin(n){this.topicSubscriptionStatus.set({topicStr:n},1),this.meshPeerCounts.set({topicStr:n},0)},onLeave(n){this.topicSubscriptionStatus.set({topicStr:n},0),this.meshPeerCounts.set({topicStr:n},0)},onAddToMesh(n,s,o){let i=this.toTopic(n);switch(s){case Gt.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case Gt.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case Gt.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case Gt.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case Gt.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case Gt.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:i},o);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:i},o);break}},onRemoveFromMesh(n,s,o){let i=this.toTopic(n);switch(s){case Hr.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:i},o);break;case Hr.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:i},o);break;case Hr.Prune:this.meshPeerChurnEventsPrune.inc({topic:i},o);break;case Hr.Excess:this.meshPeerChurnEventsExcess.inc({topic:i},o);break;default:this.meshPeerChurnEventsUnknown.inc({topic:i},o);break}},onReportValidation(n,s,o){if(this.asyncValidationMcacheHit.inc({hit:n!=null?"hit":"miss"}),n!=null){let i=this.toTopic(n.message.topic);switch(s){case qt.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case qt.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case qt.Reject:this.rejectedMessagesTotal.inc({topic:i});break;default:this.unknownValidationResultsTotal.inc({topic:i});break}}o!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-o)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(n){this.scoringPenalties.inc({penalty:n},1)},onIhaveRcv(n,s,o){let i=this.toTopic(n);this.ihaveRcvMsgids.inc({topic:i},s),this.ihaveRcvNotSeenMsgids.inc({topic:i},o)},onIwantRcv(n,s){for(let[o,i]of n){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},i)}this.iwantRcvDonthaveMsgids.inc(s)},onIdontwantRcv(n,s){this.idontwantRcvMsgids.inc(n),this.idontwantRcvDonthaveMsgids.inc(s)},onForwardMsg(n,s){let o=this.toTopic(n);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},s)},onPublishMsg(n,s,o,i,a){let c=this.toTopic(n);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},o*i),this.msgPublishPeersByTopic.inc({topic:c},o),this.directPeersPublishedTotal.inc({topic:c},s.direct),this.floodsubPeersPublishedTotal.inc({topic:c},s.floodsub),this.meshPeersPublishedTotal.inc({topic:c},s.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},s.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(n){let s=this.toTopic(n);this.msgReceivedPreValidation.inc({topic:s},1)},onMsgRecvError(n){let s=this.toTopic(n);this.msgReceivedError.inc({topic:s},1)},onPrevalidationResult(n,s){let o=this.toTopic(n);switch(s){case Mt.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case Mt.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case Mt.valid:this.prevalidationValidTotal.inc({topic:o});break;default:this.prevalidationUnknownTotal.inc({topic:o});break}},onMsgRecvInvalid(n,s){let o=this.toTopic(n),i=s.reason===Vt.Error?s.error:s.reason;this.msgReceivedInvalid.inc({error:i},1),this.msgReceivedInvalidByTopic.inc({topic:o},1)},onDuplicateMsgDelivery(n,s,o){let i=this.toTopic(n);this.duplicateMsgDeliveryDelay.observe({topic:i},s/1e3),o&&this.duplicateMsgLateDelivery.inc({topic:i},1)},onPublishDuplicateMsg(n){let s=this.toTopic(n);this.duplicateMsgIgnored.inc({topic:s},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(n,s){this.rpcRecvBytes.inc(s),this.rpcRecvCount.inc(1),n.subscriptions!=null&&this.rpcRecvSubscription.inc(n.subscriptions.length),n.messages!=null&&this.rpcRecvMessage.inc(n.messages.length),n.control!=null&&(this.rpcRecvControl.inc(1),n.control.ihave!=null&&this.rpcRecvIHave.inc(n.control.ihave.length),n.control.iwant!=null&&this.rpcRecvIWant.inc(n.control.iwant.length),n.control.graft!=null&&this.rpcRecvGraft.inc(n.control.graft.length),n.control.prune!=null&&this.rpcRecvPrune.inc(n.control.prune.length))},onRpcSent(n,s){if(this.rpcSentBytes.inc(s),this.rpcSentCount.inc(1),n.subscriptions!=null&&this.rpcSentSubscription.inc(n.subscriptions.length),n.messages!=null&&this.rpcSentMessage.inc(n.messages.length),n.control!=null){let o=n.control.ihave?.length??0,i=n.control.iwant?.length??0,a=n.control.graft?.length??0,c=n.control.prune?.length??0,l=n.control.idontwant?.length??0;o>0&&this.rpcSentIHave.inc(o),i>0&&this.rpcSentIWant.inc(i),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),l>0&&this.rpcSentIDontWant.inc(l),(o>0||i>0||a>0||c>0||l>0)&&this.rpcSentControl.inc(1)}},registerScores(n,s){let o=0,i=0,a=0,c=0;for(let l of n)l>=s.graylistThreshold&&o++,l>=s.publishThreshold&&i++,l>=s.gossipThreshold&&a++,l>=0&&c++;this.peersByScoreThreshold.set({threshold:tc.graylist},o),this.peersByScoreThreshold.set({threshold:tc.publish},i),this.peersByScoreThreshold.set({threshold:tc.gossip},a),this.peersByScoreThreshold.set({threshold:tc.mesh},c),this.score.set(n)},registerScoreWeights(n){for(let[s,o]of n.byTopic)this.scoreWeights.set({topic:s,p:"p1"},o.p1w),this.scoreWeights.set({topic:s,p:"p2"},o.p2w),this.scoreWeights.set({topic:s,p:"p3"},o.p3w),this.scoreWeights.set({topic:s,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:s,p:"p4"},o.p4w);this.scoreWeights.set({p:"p5"},n.p5w),this.scoreWeights.set({p:"p6"},n.p6w),this.scoreWeights.set({p:"p7"},n.p7w)},registerScorePerMesh(n,s){let o=new Map;n.forEach((i,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",l=o.get(c);l==null&&(l=new Set,o.set(c,l)),i.forEach(u=>l?.add(u))});for(let[i,a]of o){let c=[];a.forEach(l=>{c.push(s.get(l)??0)}),this.scorePerMesh.set({topic:i},c)}}}}var Ie=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var IG={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},AG={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function GP(r={}){return{...IG,...r,topics:r.topics!=null?Object.entries(r.topics).reduce((e,[t,n])=>(e[t]=CG(n),e),{}):{}}}function CG(r={}){return{...AG,...r}}function WP(r){for(let[e,t]of Object.entries(r.topics))try{TG(t)}catch(n){throw new Ie(`invalid score parameters for topic ${e}: ${n.message}`)}if(r.topicScoreCap<0)throw new Ie("invalid topic score cap; must be positive (or 0 for no cap)");if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new Ie("missing application specific score function");if(r.IPColocationFactorWeight>0)throw new Ie("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new Ie("invalid IPColocationFactorThreshold; must be at least 1");if(r.behaviourPenaltyWeight>0)throw new Ie("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new Ie("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(r.decayInterval<1e3)throw new Ie("invalid DecayInterval; must be at least 1s");if(r.decayToZero<=0||r.decayToZero>=1)throw new Ie("invalid DecayToZero; must be between 0 and 1")}function TG(r){if(r.topicWeight<0)throw new Ie("invalid topic weight; must be >= 0");if(r.timeInMeshQuantum===0)throw new Ie("invalid TimeInMeshQuantum; must be non zero");if(r.timeInMeshWeight<0)throw new Ie("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new Ie("invalid TimeInMeshQuantum; must be positive");if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new Ie("invalid TimeInMeshCap; must be positive");if(r.firstMessageDeliveriesWeight<0)throw new Ie("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new Ie("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new Ie("invalid FirstMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight>0)throw new Ie("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new Ie("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new Ie("invalid MeshMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new Ie("invalid MeshMessageDeliveriesThreshold; must be positive");if(r.meshMessageDeliveriesWindow<0)throw new Ie("invalid MeshMessageDeliveriesWindow; must be non-negative");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new Ie("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(r.meshFailurePenaltyWeight>0)throw new Ie("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new Ie("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(r.invalidMessageDeliveriesWeight>0)throw new Ie("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new Ie("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var _G={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function jP(r={}){return{..._G,...r}}function um(r,e,t=()=>!0){let n=new Set;if(e<=0)return n;for(let s of r){if(n.size>=e)break;t(s)&&(n.add(s),r.delete(s))}return n}function YP(r,e){return um(r,e,()=>!0)}var lm=class extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};function XP(r,e,t,n){let s=0;Object.entries(e.topics).forEach(([i,a])=>{let c=t.topics[i];if(c===void 0)return;let l=0;if(a.inMesh){let f=a.meshTime/c.timeInMeshQuantum;f>c.timeInMeshCap&&(f=c.timeInMeshCap),l+=f*c.timeInMeshWeight}let u=a.firstMessageDeliveries;if(u>c.firstMessageDeliveriesCap&&(u=c.firstMessageDeliveriesCap),l+=u*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let f=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,h=f*f;l+=h*c.meshMessageDeliveriesWeight}let d=a.meshFailurePenalty;l+=d*c.meshFailurePenaltyWeight;let p=a.invalidMessageDeliveries*a.invalidMessageDeliveries;l+=p*c.invalidMessageDeliveriesWeight,s+=l*c.topicWeight}),t.topicScoreCap>0&&s>t.topicScoreCap&&(s=t.topicScoreCap);let o=t.appSpecificScore(r);if(s+=o*t.appSpecificWeight,e.knownIPs.forEach(i=>{if(t.IPColocationFactorWhitelist.has(i))return;let a=n.get(i),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let l=c-t.IPColocationFactorThreshold,u=l*l;s+=u*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let i=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=i*i;s+=a*t.behaviourPenaltyWeight}return s}var ZP=ae(JP(),1);var Wt;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(Wt||(Wt={}));var hm=class{records;queue;constructor(){this.records=new Map,this.queue=new ZP.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Wt.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let n={msgId:e,expire:Date.now()+12e4};return this.queue.push(n),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t!=null&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};var dm=class{params;metrics;peerStats=new Map;peerIPs=new lm(()=>new Set);scoreCache=new Map;deliveryRecords=new hm;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,n,s){this.params=e,this.metrics=t,WP(e),this.scoreCacheValidityMs=s.scoreCacheValidityMs,this.computeScore=s.computeScore??XP,this.log=n.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(this._backgroundInterval!=null){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(this._backgroundInterval==null){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return t!=null?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((n,s)=>{if(!n.connected){e>n.expire&&(this.removeIPsForPeer(s,n.knownIPs),this.peerStats.delete(s),this.scoreCache.delete(s));return}Object.entries(n.topics).forEach(([o,i])=>{let a=this.params.topics[o];a!==void 0&&(i.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,i.firstMessageDeliveries<t&&(i.firstMessageDeliveries=0),i.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,i.meshMessageDeliveries<t&&(i.meshMessageDeliveries=0),i.meshFailurePenalty*=a.meshFailurePenaltyDecay,i.meshFailurePenalty<t&&(i.meshFailurePenalty=0),i.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,i.invalidMessageDeliveries<t&&(i.invalidMessageDeliveries=0),i.inMesh&&(i.meshTime=e-i.graftTime,i.meshTime>a.meshMessageDeliveriesActivation&&(i.meshMessageDeliveriesActive=!0)))}),n.behaviourPenalty*=this.params.behaviourPenaltyDecay,n.behaviourPenalty<t&&(n.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let n=Date.now(),s=this.scoreCache.get(e);if(s!=null&&s.cacheUntil>n)return s.score;this.metrics?.scoreFnRuns.inc();let o=this.computeScore(e,t,this.params,this.peerIPs),i=n+this.scoreCacheValidityMs;return s!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(o-s.score)),s.score=o,s.cacheUntil=i):this.scoreCache.set(e,{score:o,cacheUntil:i}),o}addPenalty(e,t,n){let s=this.peerStats.get(e);s!=null&&(s.behaviourPenalty+=t,this.metrics?.onScorePenalty(n))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let n=this.peerStats.get(e);n?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let n=this.peerStats.get(e);n?.knownIPs.delete(t);let s=this.peerIPs.get(t);s!=null&&(s.delete(e),s.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t!=null){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([n,s])=>{s.firstMessageDeliveries=0;let o=this.params.topics[n].meshMessageDeliveriesThreshold;if(s.inMesh&&s.meshMessageDeliveriesActive&&s.meshMessageDeliveries<o){let i=o-s.meshMessageDeliveries;s.meshFailurePenalty+=i*i}s.inMesh=!1,s.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);s!=null&&(s.inMesh=!0,s.graftTime=Date.now(),s.meshTime=0,s.meshMessageDeliveriesActive=!1)}}prune(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);if(s!=null){let o=this.params.topics[t].meshMessageDeliveriesThreshold;if(s.meshMessageDeliveriesActive&&s.meshMessageDeliveries<o){let i=o-s.meshMessageDeliveries;s.meshFailurePenalty+=i*i}s.meshMessageDeliveriesActive=!1,s.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,n){this.markFirstMessageDelivery(e,n);let s=this.deliveryRecords.ensureRecord(t),o=Date.now();if(s.status!==Wt.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-s.firstSeenTsMs,Wt[s.status]);return}s.status=Wt.valid,s.validated=o,s.peers.forEach(i=>{i!==e.toString()&&this.markDuplicateMessageDelivery(i,n)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,n,s){switch(s){case Vt.Error:this.markInvalidMessageDelivery(e,n);return;case Vt.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==Wt.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,Wt[o.status]);return}if(s===Vt.Ignore){o.status=Wt.ignored,o.peers.clear();return}o.status=Wt.invalid,this.markInvalidMessageDelivery(e,n),o.peers.forEach(i=>{this.markInvalidMessageDelivery(i,n)}),o.peers.clear()}duplicateMessage(e,t,n){let s=this.deliveryRecords.ensureRecord(t);if(!s.peers.has(e))switch(s.status){case Wt.unknown:s.peers.add(e);break;case Wt.valid:s.peers.add(e),this.markDuplicateMessageDelivery(e,n,s.validated);break;case Wt.invalid:this.markInvalidMessageDelivery(e,n);break;case Wt.ignored:break}}markInvalidMessageDelivery(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);s!=null&&(s.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);if(s!=null){let o=this.params.topics[t].firstMessageDeliveriesCap;s.firstMessageDeliveries=Math.min(o,s.firstMessageDeliveries+1),s.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,s.meshMessageDeliveries=Math.min(o,s.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,n){let s=this.peerStats.get(e);if(s!=null){let o=n!==void 0?Date.now():0,i=this.getPtopicStats(s,t);if(i!=null&&i.inMesh){let a=this.params.topics[t];if(n!==void 0){let l=o-n,u=l>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,l,u),u)return}let c=a.meshMessageDeliveriesCap;i.meshMessageDeliveries=Math.min(c,i.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let n of t){let s=this.peerIPs.get(n);s!=null&&(s.delete(e),s.size===0&&this.peerIPs.delete(n))}}getPtopicStats(e,t){let n=e.topics[t];return n!==void 0?n:this.params.topics[t]!==void 0?(n={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=n,n):null}};function PG(r,e,t,n,s){let o=0,i=new Map;if(Object.entries(e.topics).forEach(([p,f])=>{let h=s.get(p)??"unknown",m=t.topics[p];if(m===void 0)return;let g=i.get(h);g==null&&(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(h,g));let y=0,b=0,E=0,w=0,v=0;if(f.inMesh){let A=Math.max(f.meshTime/m.timeInMeshQuantum,m.timeInMeshCap);y+=A*m.timeInMeshWeight}let S=f.firstMessageDeliveries;if(S>m.firstMessageDeliveriesCap&&(S=m.firstMessageDeliveriesCap),b+=S*m.firstMessageDeliveriesWeight,f.meshMessageDeliveriesActive&&f.meshMessageDeliveries<m.meshMessageDeliveriesThreshold){let A=m.meshMessageDeliveriesThreshold-f.meshMessageDeliveries,j=A*A;E+=j*m.meshMessageDeliveriesWeight}let x=f.meshFailurePenalty;w+=x*m.meshFailurePenaltyWeight;let I=f.invalidMessageDeliveries*f.invalidMessageDeliveries;v+=I*m.invalidMessageDeliveriesWeight,o+=(y+b+E+w+v)*m.topicWeight,g.p1w+=y,g.p2w+=b,g.p3w+=E,g.p3bw+=w,g.p4w+=v}),t.topicScoreCap>0&&o>t.topicScoreCap){o=t.topicScoreCap;let p=t.topicScoreCap/o;for(let f of i.values())f.p1w*=p,f.p2w*=p,f.p3w*=p,f.p3bw*=p,f.p4w*=p}let a=0,c=0,l=0,u=t.appSpecificScore(r);a+=u*t.appSpecificWeight,e.knownIPs.forEach(p=>{if(t.IPColocationFactorWhitelist.has(p))return;let f=n.get(p),h=f!=null?f.size:0;if(h>t.IPColocationFactorThreshold){let m=h-t.IPColocationFactorThreshold,g=m*m;c+=g*t.IPColocationFactorWeight}});let d=e.behaviourPenalty*e.behaviourPenalty;return l+=d*t.behaviourPenaltyWeight,o+=a+c+l,{byTopic:i,p5w:a,p6w:c,p7w:l,score:o}}function eD(r,e,t,n,s){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let i of r){let a=e.get(i);if(a!=null){let c=PG(i,a,t,n,s);for(let[l,u]of c.byTopic){let d=o.byTopic.get(l);d==null&&(d={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(l,d)),d.p1w.push(u.p1w),d.p2w.push(u.p2w),d.p3w.push(u.p3w),d.p3bw.push(u.p3bw),d.p4w.push(u.p4w)}o.p5w.push(c.p5w),o.p6w.push(c.p6w),o.p7w.push(c.p7w),o.score.push(c.score)}else o.p5w.push(0),o.p6w.push(0),o.p7w.push(0),o.score.push(0)}return o}var fm=class{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,n){this.rawStream=e,this.pushable=Ot(),this.closeController=new AbortController,this.maxBufferSize=n.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(s=>{e.abort(s)})}),ht(this.pushable,this.rawStream).catch(t)}get protocol(){return this.rawStream.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(ec.single(e))}pushPrefixed(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}async close(){this.closeController.abort(),await this.pushable.return()}},pm=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(n=>{e.abort(n)})}),this.source=ht(this.rawStream,n=>sh(n,t))}async close(){this.closeController.abort()}};var mm=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,n){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=n,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let n=Math.floor(Math.random()*t.length),s=t[n],o=this.msgIdToStrFn(s),i=this.promises.get(o);i==null&&(i=new Map,this.promises.set(o,i));let a=Date.now();i.has(e)||(i.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(o)||this.requestMsByMsg.set(o,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,n=0;return this.promises.forEach((s,o)=>{s.forEach((i,a)=>{i<e&&(t.set(a,(t.get(a)??0)+1),s.delete(a),n++)}),s.size===0&&this.promises.delete(o)}),this.metrics?.iwantPromiseBroken.inc(n),t}deliverMessage(e,t=!1){this.trackMessage(e);let n=this.promises.get(e);n!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(n.size)))}rejectMessage(e,t){switch(this.trackMessage(e),t){case Vt.Error:return;default:break}this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[n,s]of this.requestMsByMsg.entries())if(s<e)this.requestMsByMsg.delete(n),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var u5={};z(u5,{base64:()=>DG,base64pad:()=>kG,base64url:()=>l5,base64urlpad:()=>LG});var DG=Ye({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),kG=Ye({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),l5=Ye({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),LG=Ye({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});bt();re();ie();var tD=D("libp2p-pubsub:");async function rD(r,e,t,n){switch(r.type){case Us.Signing:{let s={from:r.author.toMultihash().bytes,data:n,seqno:Y1(8),topic:e,signature:void 0,key:void 0},o=Ee([tD,Zn.Message.encode(s)]);s.signature=await r.privateKey.sign(o),s.key=r.key;let i={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${T(s.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:s.signature,key:e5(s.key)};return{raw:s,msg:i}}case Us.Anonymous:return{raw:{from:void 0,data:n,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}};default:throw new Error("Unreachable")}}async function nD(r,e){switch(r){case Va:return e.signature!=null?{valid:!1,error:Lt.SignaturePresent}:e.seqno!=null?{valid:!1,error:Lt.SeqnoPresent}:e.from!=null?{valid:!1,error:Lt.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case Ho:{if(e.seqno==null)return{valid:!1,error:Lt.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:Lt.InvalidSeqno};if(e.signature==null)return{valid:!1,error:Lt.InvalidSignature};if(e.from==null)return{valid:!1,error:Lt.InvalidPeerId};let t;try{t=Za(Qn(e.from))}catch{return{valid:!1,error:Lt.InvalidPeerId}}let n;if(e.key!=null){if(n=e5(e.key),t.publicKey!==void 0&&!n.equals(t.publicKey))return{valid:!1,error:Lt.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:Lt.InvalidPeerId};n=t.publicKey}let s={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=Ee([tD,Zn.Message.encode(s)]);return await n.verify(o,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${T(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:n}}:{valid:!1,error:Lt.InvalidSignature}}default:throw new Error("Unreachable")}}function qr(r=[],e){return{subscriptions:[],messages:r,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function h5(r){return r.control===void 0&&(r.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),r}function En(r){if(r.length<=1)return r;let e=()=>Math.floor(Math.random()*Math.floor(r.length));for(let t=0;t<r.length;t++){let n=e(),s=r[t];r[t]=r[n],r[n]=s}return r}ie();function sD(r){return T(r,"base64")}function oD(r,e,t){switch(r){case Ho:return{type:Us.Signing,author:e,key:Bs(t.publicKey),privateKey:t};case Va:return{type:Us.Anonymous};default:throw new Error(`Unknown signature policy "${r}"`)}}var aPe=new Uint8Array(0);function gm(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var MG=cD,iD=128,OG=127,RG=~OG,NG=Math.pow(2,31);function cD(r,e,t){e=e||[],t=t||0;for(var n=t;r>=NG;)e[t++]=r&255|iD,r/=128;for(;r&RG;)e[t++]=r&255|iD,r>>>=7;return e[t]=r|0,cD.bytes=t-n+1,e}var BG=d5,UG=128,aD=127;function d5(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw d5.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&aD)<<s:(i&aD)*Math.pow(2,s),s+=7}while(i>=UG);return d5.bytes=o-n,t}var KG=Math.pow(2,7),FG=Math.pow(2,14),zG=Math.pow(2,21),$G=Math.pow(2,28),HG=Math.pow(2,35),qG=Math.pow(2,42),VG=Math.pow(2,49),GG=Math.pow(2,56),WG=Math.pow(2,63),jG=function(r){return r<KG?1:r<FG?2:r<zG?3:r<$G?4:r<HG?5:r<qG?6:r<VG?7:r<GG?8:r<WG?9:10},YG={encode:MG,decode:BG,encodingLength:jG},XG=YG,f5=XG;function p5(r,e,t=0){return f5.encode(r,e,t),e}function m5(r){return f5.encodingLength(r)}function lD(r,e){let t=e.byteLength,n=m5(r),s=n+m5(t),o=new Uint8Array(s+t);return p5(r,o,0),p5(t,o,n),o.set(e,s),new g5(r,t,e,o)}var g5=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};wr();var Sn;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Sn||(Sn={}));var y5;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(y5||(y5={}));(function(r){r.codec=()=>sr(y5)})(Sn||(Sn={}));var ym;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Sn.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Sn.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(ym||(ym={}));var b5;(function(r){let e;r.codec=()=>(e==null&&(e=Z((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Sn.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Sn.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>J(t,r.codec()),r.decode=(t,n)=>Q(t,r.codec(),n)})(b5||(b5={}));function hD(r){return ym.encode({Type:Sn[r.type],Data:r.raw})}var v5=ae(te("crypto"),1);var ZG=20;function x5({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new w5(r,e,t,n,s)}var w5=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??ZG,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?dD(n,this.code,t?.truncate):n.then(s=>dD(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function dD(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return lD(e,r)}var eW=x5({name:"sha2-256",code:18,encode:r=>gm(v5.default.createHash("sha256").update(r).digest())}),wPe=x5({name:"sha2-512",code:19,encode:r=>gm(v5.default.createHash("sha512").update(r).digest())});re();ie();var fD=(r,e)=>{let t=D(e.toString(16).padStart(16,"0"),"base16"),n=hD(r),s=new Uint8Array(n.byteLength+t.length);return s.set(n,0),s.set(t,n.byteLength),s};function pD(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return fD(r.from.publicKey??r.key,r.sequenceNumber)}async function mD(r){return eh.encode(r.data)}re();ie();var es=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ts=class extends Error{static name="ValidationError";name="ValidationError"};var bm=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var E5={};z(E5,{base10:()=>tW});var tW=Ms({prefix:"9",name:"base10",alphabet:"0123456789"});var S5={};z(S5,{base16:()=>rW,base16upper:()=>nW});var rW=Ye({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),nW=Ye({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var I5={};z(I5,{base2:()=>sW});var sW=Ye({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var A5={};z(A5,{base256emoji:()=>lW});var gD=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}"),oW=gD.reduce((r,e,t)=>(r[t]=e,r),[]),iW=gD.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function aW(r){return r.reduce((e,t)=>(e+=oW[t],e),"")}function cW(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=iW[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var lW=Wa({prefix:"\u{1F680}",name:"base256emoji",encode:aW,decode:cW});var C5={};z(C5,{base8:()=>uW});var uW=Ye({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var T5={};z(T5,{identity:()=>hW});var hW=Wa({prefix:"\0",name:"identity",encode:r=>tP(r),decode:r=>eP(r)});var jPe=new TextEncoder,YPe=new TextDecoder;var yD={...T5,...I5,...C5,...E5,...S5,...P6,...D6,..._6,...u5,...A5},JPe={...s5,...M6};bt();re();ie();function P5(r){return e=>T(e,r)}function D5(r){return e=>D(e,r)}function sc(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Go(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function bD(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Go(n);return Ee([t,s],t.length+s.length)}function wD(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Os.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 s=Go(n);return Ee([t,s],t.length+s.length)}function k5(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=T(e,"base32"),s=sc(t);return`${n}:${s}`}var L5=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new es("Invalid byte value in IP address");e[n]=s}),e},xD=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,fe.isIPv4)(t[n]),i;o&&(i=L5(t[n]),t[n]=T(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,T(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new es("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},vD=function(r){if(r.byteLength!==4)throw new es("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},ED=function(r){if(r.byteLength!==16)throw new es("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new es(`Invalid IPv6 address "${t}"`)}};function SD(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new es(`Invalid IPv6 address "${r}"`)}}var _5=Object.values(yD).map(r=>r.decoder),pW=(function(){let r=_5[0].or(_5[1]);return _5.slice(2).forEach(e=>r=r.or(e)),r})();function ID(r){return pW.decode(r)}function AD(r){return e=>r.encoder.encode(e)}function mW(r){if(parseInt(r).toString()!==r)throw new ts("Value must be an integer")}function gW(r){if(r<0)throw new ts("Value must be a positive integer, or zero")}function yW(r){return e=>{if(e>r)throw new ts(`Value must be smaller than or equal to ${r}`)}}function bW(...r){return e=>{for(let t of r)t(e)}}var oh=bW(mW,gW,yW(65535));var pr=-1,M5=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new bm(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},O5=new M5,oj=[{code:4,name:"ip4",size:32,valueToBytes:L5,bytesToValue:vD,validate:r=>{if(!(0,fe.isIPv4)(r))throw new ts(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Go,bytesToValue:sc,validate:oh},{code:273,name:"udp",size:16,valueToBytes:Go,bytesToValue:sc,validate:oh},{code:33,name:"dccp",size:16,valueToBytes:Go,bytesToValue:sc,validate:oh},{code:41,name:"ip6",size:128,valueToBytes:xD,bytesToValue:ED,stringToValue:SD,validate:r=>{if(!(0,fe.isIPv6)(r))throw new ts(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:pr},{code:43,name:"ipcidr",size:8,bytesToValue:P5("base10"),valueToBytes:D5("base10")},{code:53,name:"dns",size:pr,resolvable:!0},{code:54,name:"dns4",size:pr,resolvable:!0},{code:55,name:"dns6",size:pr,resolvable:!0},{code:56,name:"dnsaddr",size:pr,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Go,bytesToValue:sc,validate:oh},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:pr,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:pr,bytesToValue:P5("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?D5("base58btc")(r):lt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:k5,valueToBytes:bD},{code:445,name:"onion3",size:296,bytesToValue:k5,valueToBytes:wD},{code:446,name:"garlic64",size:pr},{code:447,name:"garlic32",size:pr},{code:448,name:"tls"},{code:449,name:"sni",size:pr},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:pr,bytesToValue:AD(l5),valueToBytes:ID},{code:480,name:"http"},{code:481,name:"http-path",size:pr,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:pr}];oj.forEach(r=>{O5.addProtocol(r)});function CD(r,e){return O5.getProtocol(r).bytesToValue?.(e)??T(e,"base16")}var wm;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(wm||(wm={}));function TD(r){for(let e of r.tuples())switch(e[0]){case wm.ip4:case wm.ip6:return CD(e[0],e[1]);default:break}return null}var oc=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,n]of this.entries.entries())if(n.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var mr;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(mr||(mr={}));var R5=class extends me{globalSignaturePolicy;multicodecs=[am,KP,a5];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Ot({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=am;opts;decodeRpcLimits;metrics;status={code:mr.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let n={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,tagMeshPeers:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,gossipFactor:.25,idontwantMinDataSize:512,idontwantMaxMessages:512,...t,scoreParams:GP(t.scoreParams),scoreThresholds:jP(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=n.decodeRpcLimits??$P,this.globalSignaturePolicy=n.globalSignaturePolicy??Ho,n.fallbackToFloodsub&&this.multicodecs.push(i5),this.log=e.logger.forComponent(n.debugName??"libp2p:gossipsub"),this.opts=n,this.direct=new Set(n.directPeers.map(s=>s.id.toString())),this.seenCache=new oc({validityMs:n.seenTTL}),this.publishedMessageIds=new oc({validityMs:n.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Ho:this.msgIdFn=pD;break;case Va:this.msgIdFn=mD;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new oc({validityMs:n.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??sD,this.mcache=t.messageCache??new cm(n.mcacheGossip,n.mcacheLength,this.msgIdToStrFn),t.dataTransform!=null&&(this.dataTransform=t.dataTransform),t.metricsRegister!=null){if(t.metricsTopicStrToLabel==null)throw Error("Must set metricsTopicStrToLabel with metrics");let s=Math.max(...Object.values(n.scoreParams.topics).map(i=>i.meshMessageDeliveriesWindow),1e3),o=VP(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:n.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:s/1e3});o.mcacheSize.addCollect(()=>{this.onScrapeMetrics(o)});for(let i of this.multicodecs)o.protocolsEnabled.set({protocol:i},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new mm(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new dm(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:n.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=n.allowedTopics!=null?new Set(n.allowedTopics):null}[Symbol.toStringTag]="@chainsafe/libp2p-gossipsub";[Q_]=["@libp2p/pubsub"];[J_]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===mr.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=oD(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Ot({objectMode:!0}),ht(this.outboundInflightQueue,async o=>{for await(let{peerId:i,connection:a}of o)await this.createOutboundStream(i,a)}).catch(o=>{this.log.error("outbound inflight queue error",o)}),await Promise.all(this.opts.directPeers.map(async o=>{await this.components.peerStore.merge(o.id,{multiaddrs:o.addrs})}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(async o=>e.handle(o,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnLimitedConnection:this.runOnLimitedConnection},n=await Promise.all(this.multicodecs.map(async o=>e.register(o,t))),s=setTimeout(this.runHeartbeat,100);this.status={code:mr.started,registrarTopologyIds:n,heartbeatTimeout:s,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async o=>this.connect(o)))}).catch(o=>{this.log(o)})},1e3),this.opts.tagMeshPeers&&(this.addEventListener("gossipsub:graft",this.tagMeshPeer),this.addEventListener("gossipsub:prune",this.untagMeshPeer)),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==mr.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:mr.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.multicodecs.map(async s=>t.unhandle(s))),e.forEach(s=>{t.unregister(s)}),this.outboundInflightQueue.end();let n=[];for(let s of this.streamsOutbound.values())n.push(s.close());this.streamsOutbound.clear();for(let s of this.streamsInbound.values())n.push(s.close());this.streamsInbound.clear(),await Promise.all(n),this.peers.clear(),this.subscriptions.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;let n=t.remotePeer;this.addPeer(n,t.direction,t.remoteAddr),this.createInboundStream(n,e),this.outboundInflightQueue.push({peerId:n,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(this.peers.has(n)&&!this.streamsOutbound.has(n))try{let s=new fm(await t.newStream(this.multicodecs,{runOnLimitedConnection:this.runOnLimitedConnection}),i=>{this.log.error("outbound pipe error",i)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(n,s);let o=s.protocol;o===i5&&this.floodsubPeers.add(n),this.metrics?.peersPerProtocol.inc({protocol:o},1),this.subscriptions.size>0&&(this.log("send subscriptions to",n),this.sendSubscriptions(n,Array.from(this.subscriptions),!0))}catch(s){this.log.error("createOutboundStream error",s)}}createInboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(!this.peers.has(n))return;let s=this.streamsInbound.get(n);s!==void 0&&(this.log("replacing existing inbound steam %s",n),s.close().catch(i=>{this.log.error(i)})),this.log("create inbound stream %s",n);let o=new pm(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(n,o),this.pipePeerReadStream(e,o.source).catch(i=>{this.log(i)})}addPeer(e,t,n){let s=e.toString();if(!this.peers.has(s)){this.log("new peer %p",e),this.peers.set(s,e),this.score.addPeer(s);let o=TD(n);o!==null?this.score.addIP(s,o):this.log("Added peer has no IP in current address %s %s",s,n.toString()),this.outbound.has(s)||this.outbound.set(s,t==="outbound")}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let n=this.streamsOutbound.get(t),s=this.streamsInbound.get(t);n!=null&&this.metrics?.peersPerProtocol.inc({protocol:n.protocol},-1),n?.close().catch(o=>{this.log.error(o)}),s?.close().catch(o=>{this.log.error(o)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let o of this.topics.values())o.delete(t);for(let[o,i]of this.mesh)i.delete(t)&&this.metrics?.onRemoveFromMesh(o,Hr.Dc,1);for(let o of this.fanout.values())o.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.idontwantCounts.delete(t),this.idontwants.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===mr.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(n=>this.peers.get(n)??qo(n))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await ht(t,async n=>{for await(let s of n)try{let o=s.subarray(),i=Zn.decode(o,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant:this.decodeRpcLimits.maxIwantMessageIDs,graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}});if(this.metrics?.onRpcRecv(i,o.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,i)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,i).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(o){this.metrics?.onRpcDataError(),this.log(o)}})}catch(n){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(n,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let n=t.subscriptions!=null?t.subscriptions.length:0,s=t.messages!=null?t.messages.length:0,o=0,i=0,a=0,c=0;if(t.control!=null&&(t.control.ihave!=null&&(o=t.control.ihave.length),t.control.iwant!=null&&(i=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${n} messages ${s} ihave ${o} iwant ${i} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let l=[];t.subscriptions.forEach(u=>{let d=u.topic,p=u.subscribe===!0;if(d!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(d))return;this.handleReceivedSubscription(e,d,p),l.push({topic:d,subscribe:p})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:l}})}for(let l of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(l.topic))continue;let u=this.handleReceivedMessage(e,l).catch(d=>{this.metrics?.onMsgRecvError(l.topic),this.log(d)});this.opts.awaitRpcMessageHandler&&await u}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,n){this.log("subscription update from %p topic %s",e,t);let s=this.topics.get(t);s==null&&(s=new Set,this.topics.set(t,s)),n?s.add(e.toString()):s.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let n=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,n.code);let s=n.code;switch(s){case Mt.duplicate:this.score.duplicateMessage(e.toString(),n.msgIdStr,t.topic),this.gossipTracer.deliverMessage(n.msgIdStr,!0),this.mcache.observeDuplicate(n.msgIdStr,e.toString());return;case Mt.invalid:if(n.msgIdStr!=null){let o=n.msgIdStr;this.score.rejectMessage(e.toString(),o,t.topic,n.reason),this.gossipTracer.rejectMessage(o,n.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,n);return;case Mt.valid:this.score.validateMessage(n.messageId.msgIdStr),this.gossipTracer.deliverMessage(n.messageId.msgIdStr),this.mcache.put(n.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:n.messageId.msgIdStr,msg:n.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:n.msg}))),this.opts.asyncValidation||this.forwardMessage(n.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${s}`)}}async validateReceivedMessage(e,t){let n=this.fastMsgIdFn?.(t),s=n!==void 0?this.fastMsgIdCache?.get(n):void 0;if(s!=null)return{code:Mt.duplicate,msgIdStr:s};let o=await nD(this.globalSignaturePolicy,t);if(!o.valid)return{code:Mt.invalid,reason:Vt.Error,error:o.error};let i=o.message;try{this.dataTransform!=null&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(d){return this.log("Invalid message, transform failed",d),{code:Mt.invalid,reason:Vt.Error,error:Lt.TransformFailed}}let a=await this.msgIdFn(i),c=this.msgIdToStrFn(a),l={msgId:a,msgIdStr:c};if(n!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(n,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:Mt.duplicate,msgIdStr:c};this.seenCache.put(c),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let u=this.topicValidators.get(t.topic);if(u!=null){let d;try{d=await u(e,i)}catch(p){let f=p.code;f===zP&&(d=qt.Ignore),f===FP?d=qt.Reject:d=qt.Ignore}if(d!==qt.Accept)return{code:Mt.invalid,reason:c5(d),msgIdStr:c}}return{code:Mt.valid,messageId:l,msg:i}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,n){this.sendRpc(e,{subscriptions:t.map(s=>({topic:s,subscribe:n})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let n=t.ihave?.length>0?this.handleIHave(e,t.ihave):[],s=t.iwant?.length>0?this.handleIWant(e,t.iwant):[],o=t.graft?.length>0?await this.handleGraft(e,t.graft):[];if(t.prune?.length>0&&await this.handlePrune(e,t.prune),t.idontwant?.length>0&&this.handleIdontwant(e,t.idontwant),n.length===0&&s.length===0&&o.length===0)return;let i=this.sendRpc(e,qr(s,{iwant:n,prune:o})),a=n[0]?.messageIDs;a!=null&&(i?this.gossipTracer.addPromise(e,a):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),n=this.acceptFromWhitelist.get(e);if(n!=null&&n.messagesAccepted<128&&n.acceptUntil>=t)return n.messagesAccepted+=1,!0;let s=this.score.score(e);return s>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),s>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:nc.LowScore}),[];let s=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,s),s>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:nc.MaxIhave}),[];let o=this.iasked.get(e)??0;if(o>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,o),this.metrics?.ihaveRcvIgnored.inc({reason:nc.MaxIasked}),[];let i=new Map;if(t.forEach(({topicID:l,messageIDs:u})=>{if(l==null||u==null||!this.mesh.has(l))return;let d=0;u.forEach(p=>{let f=this.msgIdToStrFn(p);this.seenCache.has(f)||(i.set(f,p),d++)}),this.metrics?.onIhaveRcv(l,u.length,d)}),i.size===0)return[];let a=i.size;a+o>5e3&&(a=5e3-o),this.log("IHAVE: Asking for %d out of %d messages from %s",a,i.size,e);let c=Array.from(i.values());return En(c),c=c.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:c}]}handleIWant(e,t){if(t.length===0)return[];let n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,n),[];let s=new Map,o=new Map,i=0;return t.forEach(({messageIDs:a})=>{a?.forEach(c=>{let l=this.msgIdToStrFn(c),u=this.mcache.getWithIWantCount(l,e);if(u==null){i++;return}if(o.set(u.msg.topic,1+(o.get(u.msg.topic)??0)),u.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c);return}s.set(l,u.msg)})}),this.metrics?.onIwantRcv(o,i),s.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",s.size,e),Array.from(s.values()))}async handleGraft(e,t){let n=[],s=this.score.score(e),o=Date.now(),i=this.opts.doPX;if(t.forEach(({topicID:c})=>{if(c==null)return;let l=this.mesh.get(c);if(l==null){i=!1;return}if(l.has(e))return;let u=this.backoff.get(c)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),n.push(c),i=!1;else if(typeof u=="number"&&o<u){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,rc.GraftBackoff),i=!1;let d=u+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<d&&this.score.addPenalty(e,1,rc.GraftBackoff),this.addBackoff(e,c),n.push(c)}else s<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,s,c),n.push(c),i=!1,this.addBackoff(e,c)):l.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(n.push(c),this.addBackoff(e,c)):(this.log("GRAFT: Add mesh link from %s in %s",e,c),this.score.graft(e,c),l.add(e),this.metrics?.onAddToMesh(c,Gt.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),n.length===0)return[];let a=!1;return Promise.all(n.map(async c=>this.makePrune(e,c,i,a)))}async handlePrune(e,t){let n=this.score.score(e);for(let{topicID:s,backoff:o,peers:i}of t){if(s==null)continue;let a=this.mesh.get(s);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,s),this.score.prune(e,s),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(s,Hr.Prune,1)),typeof o=="number"&&o>0?this.doAddBackoff(e,s,o*1e3):this.addBackoff(e,s),i!=null&&i.length>0&&(n<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,n,s):await this.pxConnect(i)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:s,direction:"inbound"}})}}handleIdontwant(e,t){let n=this.idontwantCounts.get(e)??0;if(n>=this.opts.idontwantMaxMessages)return;let s=n,o=this.idontwants.get(e);o==null&&(o=new Map,this.idontwants.set(e,o));let i=0;e:for(let{messageIDs:c}of t)for(let l of c){if(n>=this.opts.idontwantMaxMessages)break e;n++;let u=this.msgIdToStrFn(l);o.set(u,this.heartbeatTicks),this.mcache.msgs.has(u)||i++}this.idontwantCounts.set(e,n);let a=n-s;this.metrics?.onIdontwantRcv(a,i)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,n){let s=this.backoff.get(t);s==null&&(s=new Map,this.backoff.set(t,s));let o=Date.now()+n;(s.get(e)??0)<o&&s.set(e,o)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,rc.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,n)=>{t.forEach((s,o)=>{s+1*this.opts.heartbeatInterval<e&&t.delete(o)}),t.size===0&&this.backoff.delete(n)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(En(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async n=>{if(n.peerID==null)return;let s=Za(Qn(n.peerID)),o=s.toString();if(!this.peers.has(o)){if(n.signedPeerRecord==null){t.push(o);return}try{if(!await this.components.peerStore.consumePeerRecord(n.signedPeerRecord,s)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(o)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length!==0&&await Promise.all(t.map(async n=>this.connect(n)))}async connect(e){this.log("Initiating connection with %s",e);let t=qo(e),n=await this.components.connectionManager.openConnection(t);for(let s of this.multicodecs)for(let o of this.components.registrar.getTopologies(s))o.onConnect?.(t,n)}subscribe(e){if(this.status.code!==mr.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==mr.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let n of this.peers.keys())this.sendSubscriptions(n,[e],!1);this.leave(e)}join(e){if(this.status.code!==mr.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,n=this.backoff.get(e),s=this.fanout.get(e);if(s!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),s.forEach(o=>{!this.direct.has(o)&&this.score.score(o)>=0&&n?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,Gt.Fanout,t.size)),t.size<this.opts.D){let o=t.size;this.getRandomGossipPeers(e,this.opts.D,a=>!t.has(a)&&!this.direct.has(a)&&this.score.score(a)>=0&&n?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,Gt.Random,t.size-o)}this.mesh.set(e,t),t.forEach(o=>{this.log("JOIN: Add mesh link to %s in %s",o,e),this.sendGraft(o,e)})}leave(e){if(this.status.code!==mr.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async n=>{this.log("LEAVE: Remove mesh link to %s in %s",n,e),await this.sendPrune(n,e)})).catch(n=>{this.log("Error sending prunes to mesh peers",n)}),this.mesh.delete(e))}selectPeersToForward(e,t,n){let s=new Set,o=this.topics.get(e);o!=null&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(n?.has(a)??!1)&&s.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(n?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&s.add(a)}));let i=this.mesh.get(e);return i!=null&&i.size>0&&i.forEach(a=>{t!==a&&!(n?.has(a)??!1)&&s.add(a)}),s}selectPeersToPublish(e){let t=new Set,n={direct:0,floodsub:0,mesh:0,fanout:0},s=this.topics.get(e);if(s!=null)if(this.opts.floodPublish)s.forEach(o=>{this.direct.has(o)?(t.add(o),n.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),n.floodsub++)});else{this.direct.forEach(i=>{s.has(i)&&(t.add(i),n.direct++)}),this.floodsubPeers.forEach(i=>{s.has(i)&&this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),n.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(i=>{t.add(i),n.mesh++}),o.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-o.size,a=>!o.has(a)&&!this.direct.has(a)&&!this.floodsubPeers.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold).forEach(a=>{t.add(a),n.mesh++});else{let i=this.fanout.get(e);if(i!=null&&i.size>0)i.forEach(a=>{t.add(a),n.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),n.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:n}}forwardMessage(e,t,n,s){n!=null&&this.score.deliverMessage(n,e,t.topic);let o=this.selectPeersToForward(t.topic,n,s);o.forEach(i=>{this.sendRpc(i,qr([t]))}),this.metrics?.onForwardMsg(t.topic,o.size)}async publish(e,t,n){let s=Date.now(),o=this.dataTransform!=null?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:i,msg:a}=await rD(this.publishConfig,e,t,o),c=await this.msgIdFn(a),l=this.msgIdToStrFn(c),u=n?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(l)){if(u)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:d,tosendCount:p}=this.selectPeersToPublish(e),f=this.opts.emitSelf&&this.subscriptions.has(e),h=n?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(d.size===0&&!h&&!f)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(l),this.mcache.put({msgId:c,msgIdStr:l},i,!0),this.gossipTracer.deliverMessage(l),this.publishedMessageIds.put(l);let m=n?.batchPublish??this.opts.batchPublish,g=qr([i]);if(m)this.sendRpcInBatch(d,g);else for(let b of d)this.sendRpc(b,g)||d.delete(b);let y=Date.now()-s;return this.metrics?.onPublishMsg(e,p,d.size,i.data!=null?i.data.length:0,y),f&&(d.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:l,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(d.values()).map(b=>this.peers.get(b)??qo(b))}}sendRpcInBatch(e,t){let n=Zn.encode(t),s=ec.single(n);for(let o of e){let i=this.streamsOutbound.get(o);if(i==null){this.log(`Cannot send RPC to ${o} as there is no open stream to it available`),e.delete(o);continue}try{i.pushPrefixed(s)}catch(a){e.delete(o),this.log.error(`Cannot send rpc to ${o}`,a)}this.metrics?.onRpcSent(t,n.length)}}reportMessageValidationResult(e,t,n){let s;if(n===qt.Accept){if(s=this.mcache.validate(e),s!=null){let{message:i,originatingPeers:a}=s;this.score.deliverMessage(t,e,i.topic),this.forwardMessage(e,s.message,t,a)}}else if(s=this.mcache.remove(e),s!=null){let i=c5(n),{message:a,originatingPeers:c}=s;this.score.rejectMessage(t,e,a.topic,i);for(let l of c)this.score.rejectMessage(l,e,a.topic,i)}let o=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(s,n,o)}sendGraft(e,t){let s=qr([],{graft:[{topicID:t}]});this.sendRpc(e,s)}async sendPrune(e,t){let s=[await this.makePrune(e,t,this.opts.doPX,!0)],o=qr([],{prune:s});this.sendRpc(e,o)}sendIDontWants(e,t,n){let s=this.mesh.get(t);if(s==null)return;let o=new Set(s);o.delete(n);for(let a of o)this.streamsOutbound.get(a)?.protocol!==am&&o.delete(a);let i=qr([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(o,i)}sendRpc(e,t){let n=this.streamsOutbound.get(e);if(n==null)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let s=this.control.get(e);s!=null&&(this.piggybackControl(e,t,s),this.control.delete(e));let o=this.gossip.get(e);o!=null&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let i=Zn.encode(t);try{n.push(i)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),s!=null&&this.control.set(e,s),o!=null&&this.gossip.set(e,o),!1}if(this.metrics?.onRpcSent(t,i.length),t.control?.graft!=null)for(let a of t.control?.graft)a.topicID!=null&&this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});if(t.control?.prune!=null)for(let a of t.control?.prune)a.topicID!=null&&this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});return!0}piggybackControl(e,t,n){let s=h5(t);for(let o of n.graft)o.topicID!=null&&(this.mesh.get(o.topicID)?.has(e)??!1)&&s.control.graft.push(o);for(let o of n.prune)o.topicID!=null&&!(this.mesh.get(o.topicID)?.has(e)??!1)&&s.control.prune.push(o)}piggybackGossip(e,t,n){let s=h5(t);s.control.ihave=n}async sendGraftPrune(e,t,n){let s=this.opts.doPX,o=!1;for(let[i,a]of e){let c=a.map(d=>({topicID:d})),l=[],u=t.get(i);u!=null&&(l=await Promise.all(u.map(async d=>this.makePrune(i,d,s&&!(n.get(i)??!1),o))),t.delete(i)),this.sendRpc(i,qr([],{graft:c,prune:l}))}for(let[i,a]of t){let c=await Promise.all(a.map(async l=>this.makePrune(i,l,s&&!(n.get(i)??!1),o)));this.sendRpc(i,qr([],{prune:c}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[n,s]of e)this.doEmitGossip(n,s,t.get(n)??[])}doEmitGossip(e,t,n){if(n.length===0||(En(n),n.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",n.length),t.size===0))return;let s=this.opts.Dlazy,i=this.opts.gossipFactor*t.size,a=t;i>s&&(s=i),s>a.size?s=a.size:a=En(Array.from(a)).slice(0,s),a.forEach(c=>{let l=n;n.length>5e3&&(l=En(l.slice()).slice(0,5e3)),this.pushGossip(c,{topicID:e,messageIDs:l})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,qr([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let n=qr([],{graft:t.graft,prune:t.prune});this.sendRpc(e,n)}}pushGossip(e,t){this.log("Add gossip to %s",e);let n=this.gossip.get(e)??[];this.gossip.set(e,n.concat(t))}async makePrune(e,t,n,s){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===a5)return{topicID:t,peers:[]};let o=s?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=o/1e3;if(this.doAddBackoff(e,t,o),!n)return{topicID:t,peers:[],backoff:i};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,l=>l!==e&&this.score.score(l)>=0),c=await Promise.all(Array.from(a).map(async l=>{let u=this.peers.get(l)??qo(l),d;try{d=await this.components.peerStore.get(u)}catch(p){if(p.name!=="NotFoundError")throw p}return{peerID:u.toMultihash().bytes,signedPeerRecord:d?.peerRecordEnvelope}}));return{topicID:t,peers:c,backoff:i}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===mr.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:n,Dscore:s,Dout:o,fanoutTTL:i}=this.opts;this.heartbeatTicks++;let a=new Map,c=h=>{let m=a.get(h);return m===void 0&&(m=this.score.score(h),a.set(h,m)),m},l=new Map,u=new Map,d=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let h of this.idontwants.values())for(let[m,g]of h)this.heartbeatTicks-g>=this.opts.mcacheLength&&h.delete(m);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let p=new Map;this.mesh.forEach((h,m)=>{let g=this.topics.get(m),y=new Set,b=new Set;if(p.set(m,b),g!=null){let v=En(Array.from(g)),S=this.backoff.get(m);for(let x of v){let I=this.streamsOutbound.get(x);if(I!=null&&this.multicodecs.includes(I.protocol)&&!h.has(x)&&!this.direct.has(x)){let A=c(x);S?.has(x)!==!0&&A>=0&&y.add(x),A>=this.opts.scoreThresholds.gossipThreshold&&b.add(x)}}}let E=(v,S)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",v,m),this.addBackoff(v,m),h.delete(v),c(v)>=this.opts.scoreThresholds.gossipThreshold&&b.add(v),this.metrics?.onRemoveFromMesh(m,S,1);let x=u.get(v);x==null?u.set(v,[m]):x.push(m)},w=(v,S)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",v,m),this.score.graft(v,m),h.add(v),b.delete(v),this.metrics?.onAddToMesh(m,S,1);let x=l.get(v);x==null?l.set(v,[m]):x.push(m)};if(h.forEach(v=>{let S=c(v);S<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",v,S,m),E(v,Hr.BadScore),d.set(v,!0))}),h.size<t){let v=e-h.size;YP(y,v).forEach(x=>{w(x,Gt.NotEnough)})}if(h.size>n){let v=Array.from(h);v.sort((x,I)=>c(I)-c(x)),v=v.slice(0,s).concat(En(v.slice(s)));let S=0;if(v.slice(0,e).forEach(x=>{(this.outbound.get(x)??!1)&&S++}),S<o){let x=A=>{let j=v[A];for(let ee=A;ee>0;ee--)v[ee]=v[ee-1];v[0]=j};if(S>0){let A=S;for(let j=1;j<e&&A>0;j++)(this.outbound.get(v[j])??!1)&&(x(j),A--)}let I=e-S;for(let A=e;A<v.length&&I>0;A++)(this.outbound.get(v[A])??!1)&&(x(A),I--)}v.slice(e).forEach(x=>{E(x,Hr.Excess)})}if(h.size>=t){let v=0;if(h.forEach(S=>{(this.outbound.get(S)??!1)&&v++}),v<o){let S=o-v;um(y,S,I=>this.outbound.get(I)===!0).forEach(I=>{w(I,Gt.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&h.size>1){let v=Array.from(h).sort((I,A)=>c(I)-c(A)),S=Math.floor(h.size/2),x=c(v[S]);if(x<this.opts.scoreThresholds.opportunisticGraftThreshold){let I=this.opts.opportunisticGraftPeers,A=um(y,I,j=>c(j)>x);for(let j of A)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",j,m),w(j,Gt.Opportunistic)}}});let f=Date.now();this.fanoutLastpub.forEach((h,m)=>{h+i<f&&(this.fanout.delete(m),this.fanoutLastpub.delete(m))}),this.fanout.forEach((h,m)=>{let g=this.topics.get(m);h.forEach(w=>{(!(g?.has(w)??!1)||c(w)<this.opts.scoreThresholds.publishThreshold)&&h.delete(w)});let y=this.topics.get(m),b=[],E=new Set;if(p.set(m,E),y!=null){let w=En(Array.from(y));for(let v of w){let S=this.streamsOutbound.get(v);if(S!=null&&this.multicodecs.includes(S.protocol)&&!h.has(v)&&!this.direct.has(v)){let x=c(v);x>=this.opts.scoreThresholds.publishThreshold&&b.push(v),x>=this.opts.scoreThresholds.gossipThreshold&&E.add(v)}}}if(h.size<e){let w=e-h.size;b.slice(0,w).forEach(v=>{h.add(v),E?.delete(v)})}}),this.emitGossip(p),await this.sendGraftPrune(l,u,d),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,n=()=>!0){let s=this.topics.get(e);if(s==null)return new Set;let o=[];return s.forEach(i=>{let a=this.streamsOutbound.get(i);a!=null&&this.multicodecs.includes(a.protocol)&&n(i)&&o.push(i)}),o=En(o),t>0&&o.length>t&&(o=o.slice(0,t)),new Set(o)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,n=Date.now();e.connectedPeersBackoffSec.reset();for(let c of this.backoff.values()){t+=c.size;for(let[l,u]of c.entries())this.peers.has(l)&&e.connectedPeersBackoffSec.observe(Math.max(0,u-n)/1e3)}e.cacheSize.set({cache:"backoff"},t);let s=0;for(let c of this.idontwants.values())s+=c.size;e.cacheSize.set({cache:"idontwants"},s);for(let[c,l]of this.topics)e.topicPeersCount.set({topicStr:c},l.size);for(let[c,l]of this.mesh)e.meshPeerCounts.set({topicStr:c},l.size);let o=[],i=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let l=this.score.score(c);o.push(l),i.set(c,l),e.behaviourPenalty.observe(this.score.peerStats.get(c)?.behaviourPenalty??0)}e.registerScores(o,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let a=eD(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:n}=e.detail;this.components.peerStore.merge(this.peers.get(t)??qo(t),{tags:{[n]:{value:100}}}).catch(s=>{this.log.error("Error tagging peer %s with topic %s",t,n,s)})};untagMeshPeer=e=>{let{peerId:t,topic:n}=e.detail;this.components.peerStore.merge(this.peers.get(t)??qo(t),{tags:{[n]:void 0}}).catch(s=>{this.log.error("Error untagging peer %s with topic %s",t,n,s)})}};function PD(r={}){return e=>new R5(e,r)}V();ke();Ue();var Mj="bootstrap",Oj=50,Rj=1e3,N5=class extends me{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??Rj,this.list=t.list.map(n=>q(n)).filter(n=>vf.matches(n)?n.getComponents().findLast(o=>o.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:de(n.getComponents().findLast(s=>s.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[pc]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[nt]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??Mj]:{value:this._init.tagValue??Oj,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function DD(r){return e=>new N5(e,r)}ke();ie();var xm=class{components;running=!1;log;cfg;readyPromise=null;coordinatorCache=new Map;clusterCache=new Map;lastEstimate=null;blacklist=new Map;libp2pRef;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("db-p2p:network-manager"),this.cfg={clusterSize:t.clusterSize??1,seedKeys:t.seedKeys??[],estimation:t.estimation??{samples:8,kth:5,timeoutMs:1e3,ttlMs:6e4},readiness:t.readiness??{minPeers:1,maxWaitMs:2e3},cacheTTLs:t.cacheTTLs??{coordinatorMs:30*6e4,clusterMs:5*6e4},expectedRemotes:t.expectedRemotes??!1,allowClusterDownsize:t.allowClusterDownsize??!0,clusterSizeTolerance:t.clusterSizeTolerance??.5}}setLibp2p(e){this.libp2pRef=e}getLibp2p(){return this.libp2pRef??this.components.libp2p}getFret(){let e=this.getLibp2p();if(e)return e.services?.fret}get[Symbol.toStringTag](){return"@libp2p/network-manager"}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}async ready(){return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{let t=(await Promise.allSettled((this.cfg.seedKeys??[]).map(n=>this.seedKey(n)))).filter(n=>n.status==="rejected");t.length>0&&this.log("Failed to seed %d keys",t.length),await new Promise(n=>setTimeout(n,50))})(),this.readyPromise)}async seedKey(e){let t=this.getFret();if(!t)throw new Error("FRET service not available for seeding keys");let n=await ir(e),s=t.getNeighbors(n,"both",1)}toCacheKey(e){return T(e,"base64url")}getKnownPeers(){let e=this.getLibp2p();if(!e)return[];let t=e.peerId,n=e.peerStore?.getPeers?.()??[],s=(e.getConnections?.()??[]).map(a=>a.remotePeer),o=[...n.map(a=>a.id),...s];return o.filter((a,c)=>o.findIndex(l=>l.toString()===a.toString())===c).filter(a=>a.toString()!==t.toString())}getStatus(){let e=this.getLibp2p();if(!e)return{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0};let n=(e.peerStore?.getPeers?.()??[]).filter(s=>s.id.toString()!==e.peerId.toString()).length;return n===0?{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0}:{mode:"healthy",connections:n}}async awaitHealthy(e,t){let n=Date.now();for(;Date.now()-n<t;){let o=this.getLibp2p();if(o){let i=o.getConnections?.()??[],a=new Set(i.map(c=>c.remotePeer.toString()));if(a.size>=e)return this.log("awaitHealthy: satisfied with %d connections",a.size),!0}await new Promise(i=>setTimeout(i,100))}let s=this.getLibp2p();if(s){let o=s.getConnections?.()??[],i=new Set(o.map(c=>c.remotePeer.toString())),a=i.size>=e;return this.log("awaitHealthy: timeout - %d connections (needed %d)",i.size,e),a}return!1}reportBadPeer(e,t=1,n=10*6e4){let s=e.toString(),i=(this.blacklist.get(s)?.score??0)+Math.max(1,t);this.blacklist.set(s,{score:i,expires:Date.now()+n})}isBlacklisted(e){let t=e.toString(),n=this.blacklist.get(t);return n?n.expires<=Date.now()?(this.blacklist.delete(t),!1):n.score>=3:!1}recordCoordinator(e,t){let n=this.toCacheKey(e);this.coordinatorCache.set(n,{id:t,expires:Date.now()+this.cfg.cacheTTLs.coordinatorMs})}async findNearestPeerToKey(e){let t=this.getFret(),n=this.getLibp2p();if(!n)throw new Error("Libp2p not initialized");if(t){let a=await ir(e),c=t.getNeighbors(a,"both",1);if(c.length>0){let l=c[0];if(l){let{peerIdFromString:u}=await Promise.resolve().then(()=>(ke(),V2)),d=u(l);if(!this.isBlacklisted(d))return d}}}let s=(n.getConnections?.()??[]).map(a=>a.remotePeer),o=[n.peerId,...s,...this.getKnownPeers()].filter((a,c,l)=>l.findIndex(u=>u.toString()===a.toString())===c).filter(a=>!this.isBlacklisted(a));return o.length===0?n.peerId:o.reduce((a,c)=>this.lexLess(this.xor(a.toMultihash().bytes,e),this.xor(c.toMultihash().bytes,e))?a:c,o[0])}async getCluster(e){let t=this.toCacheKey(e),n=this.clusterCache.get(t);if(n&&n.expires>Date.now())return n.ids;let s=this.getFret(),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");if(s){let f=await ir(e),h=s.getDiagnostics?.()??{},m=typeof h.estimate=="number"?h.estimate:typeof h.n=="number"?h.n:void 0,g=Math.max(1,Math.min(this.cfg.clusterSize,Number.isFinite(m)?m:this.cfg.clusterSize)),y=s.assembleCohort(f,g),{peerIdFromString:b}=await Promise.resolve().then(()=>(ke(),V2)),E=y.map(w=>{try{return b(w)}catch(v){return this.log("Invalid peer ID in cohort: %s, %o",w,v),null}}).filter(w=>w!==null&&!this.isBlacklisted(w));if(E.length>0)return this.clusterCache.set(t,{ids:E,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),this.lastEstimate=m!=null?{estimate:m,samples:h.samples??0,updated:Date.now()}:this.lastEstimate,E}let i=await this.findNearestPeerToKey(e),a=i.toMultihash().bytes,c=(o.getConnections?.()??[]).map(f=>f.remotePeer),u=[i,o.peerId,...c,...this.getKnownPeers()].filter((f,h,m)=>!this.isBlacklisted(f)&&m.findIndex(g=>g.toString()===f.toString())===h).sort((f,h)=>this.lexLess(this.xor(f.toMultihash().bytes,a),this.xor(h.toMultihash().bytes,a))?-1:1),d=Math.min(this.cfg.clusterSize,u.length),p=u.slice(0,d);return this.clusterCache.set(t,{ids:p,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),p}async getCoordinator(e){let t=this.toCacheKey(e),n=this.coordinatorCache.get(t);if(n){if(n.expires>Date.now())return n.id;this.coordinatorCache.delete(t)}let s=await this.getCluster(e),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");let i=s.find(a=>!this.isBlacklisted(a))??o.peerId;return this.recordCoordinator(e,i),i}xor(e,t){let n=Math.max(e.length,t.length),s=new Uint8Array(n);for(let o=0;o<n;o++){let i=e[e.length-1-o]??0,a=t[t.length-1-o]??0;s[n-1-o]=i^a}return s}lexLess(e,t){let n=Math.max(e.length,t.length);for(let s=0;s<n;s++){let o=e[s]??0,i=t[s]??0;if(o<i)return!0;if(o>i)return!1}return!1}};function B5(r={}){return e=>new xm(e,r)}var vm=class{peerStatuses=new Map;unreachableThreshold=3;rapidChurnThreshold=5;rapidChurnWindow=1e4;peerTimeoutMs=6e4;recordSuccess(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastSeen=t,n.consecutiveFailures=0):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:0}),this.cleanupOldPeers()}recordFailure(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.consecutiveFailures++,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:1})}recordGoodbye(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastGoodbye=t,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,lastGoodbye:t,consecutiveFailures:0})}detectPartition(){let e=Date.now(),t=this.getRecentGoodbyes(this.rapidChurnWindow),n=Array.from(this.peerStatuses.values()).filter(o=>o.consecutiveFailures>=this.unreachableThreshold&&!o.lastGoodbye);return t.length+n.length>=this.rapidChurnThreshold}getUnreachablePeers(){return Array.from(this.peerStatuses.values()).filter(e=>e.consecutiveFailures>=this.unreachableThreshold&&!e.lastGoodbye).map(e=>e.peerId)}getRecentGoodbyes(e){let t=Date.now()-e;return Array.from(this.peerStatuses.values()).filter(n=>n.lastGoodbye&&n.lastGoodbye>t)}cleanupOldPeers(){let e=Date.now()-this.peerTimeoutMs;for(let[t,n]of this.peerStatuses.entries())n.lastSeen<e&&this.peerStatuses.delete(t)}getStatistics(){let e=this.getUnreachablePeers().length,t=this.getRecentGoodbyes(this.rapidChurnWindow).length;return{totalPeers:this.peerStatuses.size,unreachable:e,recentGoodbyes:t}}reset(){this.peerStatuses.clear()}};function Nj(r){return r?typeof r=="function"?r():r:new gl}async function kD(r,e){let t=Nj(r.storage),n=async(S,x)=>{},s=new yl(S=>new Bi(S,t,n)),o,i,a={async update(S){if(!o)throw new Error("ClusterMember not initialized");return await o.update(S)}},c={async get(S,x){return await(i??s).get(S,x)},async pend(S,x){return await(i??s).pend(S,x)},async cancel(S,x){return await(i??s).cancel(S,x)},async commit(S,x){return await(i??s).commit(S,x)}},l=r.id?await de(r.id):void 0,u=r.listenAddrs??e.listenAddrs,d=r.transports??e.transports,p={start:!1,...l?{peerId:l}:{},addresses:{listen:u},connectionManager:{autoDial:!0,minConnections:1,maxConnections:16,inboundConnectionUpgradeTimeout:1e4,dialQueue:{concurrency:2,attempts:2}},transports:d,connectionEncrypters:[k_()],streamMuxers:[K_()],services:{identify:q_({protocolPrefix:`/optimystic/${r.networkName}`}),ping:X_(),pubsub:PD({allowPublishToZeroTopicPeers:!0,heartbeatInterval:7e3}),...r.relay?{relay:gC()}:{},cluster:S=>Yg({protocolPrefix:`/optimystic/${r.networkName}`,configuredClusterSize:r.clusterSize??10,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5,responsibilityK:r.responsibilityK??1})({logger:S.logger,registrar:S.registrar,cluster:a}),repo:S=>Jg({protocolPrefix:`/optimystic/${r.networkName}`,responsibilityK:r.responsibilityK??1})({logger:S.logger,registrar:S.registrar,repo:c}),sync:S=>l3({protocolPrefix:`/optimystic/${r.networkName}`})({logger:S.logger,registrar:S.registrar,repo:c}),networkManager:S=>{let I=B5({clusterSize:r.clusterSize??10,expectedRemotes:(r.bootstrapNodes?.length??0)>0,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})(S);try{I.setLibp2p?.(S.libp2p)}catch{}return I},fret:S=>{let I=c3({k:15,m:8,capacity:2048,profile:r.fretProfile??((r.bootstrapNodes?.length??0)>0?"core":"edge"),networkName:r.networkName,bootstraps:r.bootstrapNodes??[]})(S);try{I.setLibp2p(S.libp2p)}catch{}return I}},peerDiscovery:[...r.bootstrapNodes?.length?[DD({list:r.bootstrapNodes})]:[]]},f=await FT(p);try{f.services?.fret?.setLibp2p?.(f)}catch{}try{f.services?.networkManager?.setLibp2p?.(f)}catch{}await f.start();let h=new Xl(f),m=`/optimystic/${r.networkName}`,g=S=>ro.create(S,h,m),y=new vm,b=f.services?.fret;o=jg({storageRepo:s,peerNetwork:h,peerId:f.peerId,protocolPrefix:m,partitionDetector:y,fretService:b,validator:r.validator});let E=Qg(h,g,{clusterSize:r.clusterSize??10,superMajorityThreshold:r.clusterPolicy?.superMajorityThreshold??.67,simpleMajorityThreshold:.51,minAbsoluteClusterSize:2,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5,partitionDetectionWindow:6e4},b),w=async(S,x)=>{let I=new ho(S,h,m);try{let A=await I.requestBlock({blockId:x,rev:void 0});if(A.success&&A.archive){let j=Object.keys(A.archive.revisions).map(Number);if(j.length>0){let ee=Math.max(...j),H=A.archive.revisions[ee];if(H?.action)return{actionId:H.action.actionId,rev:ee}}}}catch{}};if(i=E({storageRepo:s,localCluster:o,localPeerId:f.peerId,clusterLatestCallback:w}),r.arachnode?.enableRingZulu??!0){let S=f.logger?.forComponent?.("db-p2p:arachnode"),x=f.services?.fret;if(x){let I=new $l(x),A=new zl(t,r.arachnode?.storage??{}),j=new Fl(I,A,{minCapacity:100*1024*1024,thresholds:{moveOut:.85,moveIn:.4}}),ee=f.peerId.toString(),H=await j.createArachnodeInfo(ee);I.setArachnodeInfo(H),S?.("Announced Arachnode membership: Ring %d",H.ringDepth);let L=new Kl(I,{connect:(O,R)=>f.dialProtocol(O,[R])},`/optimystic/${r.networkName}`),P=async(O,R)=>await L.restore(O,R);s.createBlockStorage=O=>new Bi(O,t,P);let _=setInterval(async()=>{let O=await j.shouldTransition();if(O.shouldMove){S?.("Ring transition needed: moving %s to Ring %d",O.direction,O.newRingDepth);let R=await j.createArachnodeInfo(ee);I.setArachnodeInfo(R)}},6e4),M=f.stop.bind(f);f.stop=async()=>{clearInterval(_),await M()}}else S?.("FRET service not available, Arachnode disabled")}return f.coordinatedRepo=i,f.storageRepo=s,f.keyNetwork=h,f}async function Bj(r){let e=r.port??0;return await kD(r,{listenAddrs:[`/ip4/0.0.0.0/tcp/${e}`],transports:[E8(),yC()]})}function LD(r,e){let t=Math.max(r.length,e.length),n=new Uint8Array(t);for(let s=0;s<t;s++){let o=r[r.length-1-s]??0,i=e[e.length-1-s]??0;n[t-1-s]=o^i}return n}function MD(r,e){let t=Math.max(r.length,e.length);for(let n=0;n<t;n++){let s=r[n]??0,o=e[n]??0;if(s<o)return!0;if(s>o)return!1}return!1}function OD(r,e){return r.map(t=>({p:t,d:LD(t.id.toMultihash().bytes,e)})).sort((t,n)=>MD(t.d,n.d)?-1:1).map(t=>t.p)}function Uj(r,e,t,n){let s=[e,...t],o=OD(s,r);if(s.length<=3)return{inCluster:o[0].id.equals(e.id),nearest:o};let i=Math.min(n,Math.max(1,Math.floor(s.length/2))),a=o.slice(0,i);return{inCluster:a.some(l=>l.id.equals(e.id)),nearest:a}}function Kj(r){let e={id:r.peerId,addrs:r.getMultiaddrs().map(o=>o.toString())},t=r.getConnections(),n={};for(let o of t){let i=o.remotePeer,a=i.toString(),c=n[a]??(n[a]={id:i,addrs:new Set}),l=o.remoteAddr?.toString?.();l&&c.addrs.add(l)}let s=Object.values(n).map(o=>({id:o.id,addrs:Array.from(o.addrs)}));return[e,...s]}var Fj=Sr("network:get-manager");function zj(r){let e=r.services?.networkManager;if(e==null)throw new Error("networkManager service is not registered on this libp2p node");try{e.setLibp2p?.(r)}catch(t){Fj("getNetworkManager setLibp2p failed - %o",t)}return e}return $5($j);})();
25
+ `).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let s=t.pop();s!=null&&n.push(s.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function mz(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var Xr="/multistream/1.0.0";var gz=P(`
26
+ `);async function ou(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==gz[0])throw new At("Missing newline");return C(n).trimEnd()}async function ua(r,e,t={}){if(e=Array.isArray(e)?[...e]:[e],e.length===0)throw new Error("At least one protocol must be specified");let n=r.log.newScope("mss:select"),s=ds(r,{...t,maxDataLength:1024});for(let o=0;o<e.length;o++){let i=e[o],a;if(o===0){n.trace('write ["%s", "%s"]',Xr,i);let c=P(`${Xr}
27
+ `),l=P(`${i}
28
+ `);if(await s.writeV([c,l],t),n.trace("reading multistream-select header"),a=await ou(s,t),n.trace('read "%s"',a),a!==Xr){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await s.write(P(`${i}
29
+ `),t);if(n.trace("reading protocol response"),a=await ou(s,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),s.unwrap(),i}throw new Yu(`Protocol selection failed - could not negotiate ${e}`)}async function ha(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),s=ds(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let o=await ou(s,t);if(n.trace('read "%s"',o),o===Xr){n.trace('respond with "%s" for "%s"',Xr,o),await s.write(P(`${Xr}
30
+ `),t),n.trace('responded with "%s" for "%s"',Xr,o);continue}if(e.includes(o))return n.trace('respond with "%s" for "%s"',o,o),await s.write(P(`${o}
31
+ `),t),n.trace('responded with "%s" for "%s"',o,o),s.unwrap(),o;if(o==="ls"){let i=new B(...e.map(a=>or.single(P(`${a}
32
+ `))),P(`
33
+ `));n.trace('respond with "%s" for %s',e,o),await s.write(i,t),n.trace('responded with "%s" for %s',e,o);continue}n.trace('respond with "na" for "%s"',o),await s.write(P(`na
34
+ `),t),n('responded with "na" for "%s"',o)}}var Rb=class extends he{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=bb(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new qn(n.local,n.error))})}[Symbol.toStringTag]="Connection";[z6]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new ms("Connection is not multiplexed");if(this.muxer.status!=="open")throw new As(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new As(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Ga("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);W(1/0,a),t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await ua(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let s=wz(n.protocol,this.components.registrar,t),o=l8(n.protocol,"outbound",this);if(o>s){let a=new Ro(`Too many outbound protocol streams for protocol "${n.protocol}" - ${o}/${s}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(s){throw n.status==="open"?n.abort(s):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,s),s}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);W(1/0,n),t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await ha(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let s=bz(t.protocol,this.components.registrar);if(l8(t.protocol,"inbound",this)>s)throw new Ju(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${s}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Ga("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,d)=>{await i(l,u),d(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(s){t.abort(s)}}async runMiddlewareChain(e,t,n){for(let s=0;s<n.length;s++){let o=n[s];e.log.trace("running middleware",s,o),await new Promise((i,a)=>{try{let c=o(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",s,o)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);W(1/0,t),e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function u8(r,e){return new Rb(r,e)}function bz(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Lb}function wz(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Mb}function l8(r,e,t){let n=0;return t.streams.forEach(s=>{s.direction===e&&s.protocol===r&&n++}),n}var Op=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=xt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=xt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new hp(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Dt([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return W(1/0,t),t}async upgradeInbound(e,t){let n=!1,s=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new dp("Connection denied");await su(this.shouldBlockConnection("denyInboundConnection",e),s),await this._performUpgrade(e,"inbound",{...t,signal:s})}catch(o){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[o.name??"Error"]:!0}),o}finally{s.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,s;n!=null&&(s=oe(n),await su(this.shouldBlockConnection("denyOutboundConnection",s,e),t.signal));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let s=e,o,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),s=await d.protect(s,n))}try{if(xz(n)){if(n.remotePeer==null)throw new zn(`${t} connection that skipped encryption must have a peer id`);c="native",o=n.remotePeer}else{let d=e.remoteAddr.getComponents().findLast(f=>f.code===421)?.value,p;d!=null&&(p=oe(d)),n?.onProgress?.(new Te(`upgrader:encrypt-${t}-connection`)),{connection:s,remotePeer:o,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(s,{...n,remotePeer:p}):this._encryptOutbound(s,{...n,remotePeer:p}))}if(o.equals(this.components.peerId)){let d=new Oo("Can not dial self");throw e.abort(d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new Te(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(s,this.streamMuxers,n):this._multiplexOutbound(s,this.streamMuxers,n)))}catch(d){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,d),d}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(s)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:s,muxer:a,remotePeer:o,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=u8(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let s=await ha(e,n,t),o=this.connectionEncrypters.get(s);if(o==null)throw new Io(`no crypto module found for ${s}`);return e.log("encrypting inbound connection using %s",s),{...await o.secureInbound(e,t),protocol:s}}catch(s){throw new Io(s.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let s=await ua(e,n,t),o=this.connectionEncrypters.get(s);if(o==null)throw new Io(`no crypto module found for ${s}`);return e.log("encrypting outbound connection using %s",s),{...await o.secureOutbound(e,t),protocol:s}}catch(s){throw new Io(s.message)}}async _multiplexOutbound(e,t,n){let s=Array.from(t.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);let o=await ua(e,s,n),i=t.get(o);if(i==null)throw new ms(`No muxer configured for protocol "${o}"`);return e.log("selected %s as muxer protocol",o),i}catch(o){throw e.log.error("error multiplexing outbound connection - %e",o),new ms(String(o))}}async _multiplexInbound(e,t,n){let s=Array.from(t.keys());e.log("inbound handling muxers %s",s);try{e.log.trace("selecting stream muxer from %s",s);let o=await ha(e,s,n),i=t.get(o);if(i==null)throw new ms(`No muxer configured for protocol "${o}"`);return e.log("selected %s as muxer protocol",o),i}catch(o){throw e.log.error("error multiplexing inbound connection - %e",o),o}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function xz(r){return r.skipEncryption===!0}var gs=ne(Z("node:process"),1);var Rp="3.1.3",Np="js-libp2p";function d8(r,e){let t="node",n=gs.default.versions.node;return gs.default.versions.deno!=null&&(t="deno",n=gs.default.versions.deno),gs.default.versions.bun!=null&&(t="bun",n=gs.default.versions.bun),gs.default.versions.electron!=null&&(t="electron",n=gs.default.versions.electron),`${r??Np}/${e??Rp} ${t}/${n.replaceAll("v","")}`}var Bp=class extends he{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new he,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},W(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Lf(),this.log=this.logger.forComponent("libp2p"),this.services={};let s=e.nodeInfo?.name??Np,o=e.nodeInfo?.version??Rp,i=this.components=$A({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:s,version:o,userAgent:e.nodeInfo?.userAgent??d8(s,o)},logger:this.logger,events:t,datastore:e.datastore??new Qf,connectionGater:qA(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",NA(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Op(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Mp(this.components,e.transportManager)),this.configureComponent("connectionManager",new Cp(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Tp(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Lp(this.components)),this.configureComponent("addressManager",new rp(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Dp(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new _p(this.components,{routers:c})),this.configureComponent("randomWalk",new kp(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",p=>{this.#e(p)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[em]!=null&&(this.log("registering service %s for content routing",l),c.push(d[em])),d[tm]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[tm])),d[Wa]!=null&&(this.log("registering service %s for peer discovery",l),d[Wa].addEventListener?.("peer",p=>{this.#e(p)}))}HA(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new io;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new N("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new N("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){ls(e)&&(e=oe(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=be([P("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(n,t),o=Pt(s);return await this.peerStore.patch(e,{publicKey:o},t),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function f8(r={}){r.privateKey??=await Gx("Ed25519");let e=new Bp({...await VI(r),peerId:d4(r.privateKey)});return r.start!==!1&&await e.start(),e}var da=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Nb=16;var en=ne(Z("node:crypto"),1),Yp=ne(x8(),1);var Uz=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,v8=Uz?Fz:Kz;function Kz(r=0){return new Uint8Array(r)}function Fz(r=0){let e=Buffer.allocUnsafe(r);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var E8=Uint8Array.from([0,97,115,109,1,0,0,0,1,43,8,96,2,127,127,0,96,1,127,0,96,1,127,1,127,96,2,127,127,1,127,96,0,0,96,3,127,127,127,0,96,4,127,127,127,127,0,96,3,127,127,126,0,2,13,1,3,101,110,118,5,97,98,111,114,116,0,6,3,23,22,0,0,0,0,0,7,2,3,3,2,4,5,1,2,5,0,1,1,0,1,1,4,5,3,1,0,1,6,187,1,37,127,0,65,4,11,127,0,65,128,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,0,11,7,169,1,13,8,72,65,83,95,83,73,77,68,3,36,22,98,97,116,99,104,72,97,115,104,52,85,105,110,116,65,114,114,97,121,54,52,115,0,17,26,98,97,116,99,104,72,97,115,104,52,72,97,115,104,79,98,106,101,99,116,73,110,112,117,116,115,0,18,12,73,78,80,85,84,95,76,69,78,71,84,72,3,1,15,80,65,82,65,76,76,69,76,95,70,65,67,84,79,82,3,0,5,105,110,112,117,116,3,30,6,111,117,116,112,117,116,3,32,4,105,110,105,116,0,11,6,117,112,100,97,116,101,0,19,5,102,105,110,97,108,0,20,6,100,105,103,101,115,116,0,21,8,100,105,103,101,115,116,54,52,0,16,6,109,101,109,111,114,121,2,0,8,1,22,12,1,18,10,153,23,22,9,0,32,0,32,1,54,2,0,11,9,0,32,0,32,1,54,2,4,11,9,0,32,0,32,1,54,2,8,11,192,1,1,4,127,32,1,40,2,0,65,124,113,34,3,65,128,2,73,4,127,32,3,65,4,118,5,65,31,65,252,255,255,255,3,32,3,32,3,65,252,255,255,255,3,79,27,34,3,103,107,34,4,65,7,107,33,2,32,3,32,4,65,4,107,118,65,16,115,11,33,3,32,1,40,2,8,33,5,32,1,40,2,4,34,4,4,64,32,4,32,5,16,3,11,32,5,4,64,32,5,32,4,16,2,11,32,1,32,0,32,2,65,4,116,32,3,106,65,2,116,106,34,1,40,2,96,70,4,64,32,1,32,5,54,2,96,32,5,69,4,64,32,0,32,2,65,2,116,106,34,1,40,2,4,65,126,32,3,119,113,33,3,32,1,32,3,54,2,4,32,3,69,4,64,32,0,32,0,40,2,0,65,126,32,2,119,113,16,1,11,11,11,11,181,2,1,5,127,32,1,40,2,0,33,3,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,2,65,1,113,4,64,32,0,32,4,16,4,32,1,32,3,65,4,106,32,2,65,124,113,106,34,3,16,1,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,2,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,1,40,2,0,33,6,32,0,32,1,16,4,32,1,32,6,65,4,106,32,3,65,124,113,106,34,3,16,1,11,32,4,32,2,65,2,114,16,1,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,5,65,31,65,252,255,255,255,3,32,2,32,2,65,252,255,255,255,3,79,27,34,2,103,107,34,3,65,7,107,33,5,32,2,32,3,65,4,107,118,65,16,115,11,34,2,32,5,65,4,116,106,65,2,116,106,40,2,96,33,3,32,1,65,0,16,2,32,1,32,3,16,3,32,3,4,64,32,3,32,1,16,2,11,32,0,32,5,65,4,116,32,2,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,5,116,114,16,1,32,0,32,5,65,2,116,106,34,0,32,0,40,2,4,65,1,32,2,116,114,54,2,4,11,130,1,1,3,127,32,1,65,19,106,65,112,113,65,4,107,33,1,32,0,40,2,160,12,34,3,4,64,32,3,32,1,65,16,107,34,5,70,4,64,32,3,40,2,0,33,4,32,5,33,1,11,11,32,2,167,65,112,113,32,1,107,34,3,65,20,73,4,64,15,11,32,1,32,4,65,2,113,32,3,65,8,107,34,3,65,1,114,114,16,1,32,1,65,0,16,2,32,1,65,0,16,3,32,1,65,4,106,32,3,106,34,3,65,2,16,1,32,0,32,3,54,2,160,12,32,0,32,1,16,5,11,29,0,32,0,65,1,65,27,32,0,103,107,116,106,65,1,107,32,0,32,0,65,254,255,255,255,1,73,27,11,142,1,1,2,127,32,1,65,128,2,73,4,127,32,1,65,4,118,5,65,31,32,1,16,7,34,1,103,107,34,3,65,7,107,33,2,32,1,32,3,65,4,107,118,65,16,115,11,33,1,32,0,32,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,148,2,1,3,127,32,1,65,252,255,255,255,3,75,4,64,65,176,14,65,176,15,65,205,3,65,29,16,0,0,11,32,0,65,12,32,1,65,19,106,65,112,113,65,4,107,32,1,65,12,77,27,34,1,16,8,34,2,69,4,64,32,1,65,128,2,79,4,127,32,1,16,7,5,32,1,11,33,2,63,0,34,3,32,2,65,4,32,0,40,2,160,12,32,3,65,16,116,65,4,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,2,32,2,32,3,72,27,64,0,65,0,72,4,64,32,2,64,0,65,0,72,4,64,0,11,11,32,0,32,3,65,16,116,63,0,172,66,16,134,16,6,32,0,32,1,16,8,33,2,11,32,2,40,2,0,26,32,0,32,2,16,4,32,2,40,2,0,34,3,65,124,113,32,1,107,34,4,65,16,79,4,64,32,2,32,1,32,3,65,2,113,114,16,1,32,2,65,4,106,32,1,106,34,1,32,4,65,4,107,65,1,114,16,1,32,0,32,1,16,5,5,32,2,32,3,65,126,113,16,1,32,2,65,4,106,32,2,40,2,0,65,124,113,106,34,0,32,0,40,2,0,65,125,113,16,1,11,32,2,11,169,2,1,3,127,32,0,65,252,255,255,255,3,75,4,64,65,192,13,65,240,13,65,52,65,43,16,0,0,11,32,0,65,236,255,255,255,3,75,4,64,65,176,14,65,240,14,65,253,0,65,30,16,0,0,11,35,23,69,4,64,63,0,34,2,65,0,76,4,127,65,1,32,2,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,128,16,65,0,16,1,65,160,28,65,0,54,2,0,3,64,32,1,65,23,73,4,64,32,1,65,2,116,65,128,16,106,65,0,54,2,4,65,0,33,2,3,64,32,2,65,16,73,4,64,32,1,65,4,116,32,2,106,65,2,116,65,128,16,106,65,0,54,2,96,32,2,65,1,106,33,2,12,1,11,11,32,1,65,1,106,33,1,12,1,11,11,65,128,16,65,164,28,63,0,172,66,16,134,16,6,65,128,16,36,23,11,35,23,32,0,65,16,106,16,9,34,2,65,1,54,2,12,32,2,32,0,54,2,16,35,24,34,3,40,2,8,33,1,32,2,32,3,16,2,32,2,32,1,16,3,32,1,32,2,32,1,40,2,4,65,3,113,114,16,2,32,3,32,2,16,3,35,25,32,2,40,2,0,65,124,113,65,4,106,106,36,25,32,2,65,20,106,34,1,65,0,32,0,252,11,0,32,1,11,74,0,65,231,204,167,208,6,36,4,65,133,221,158,219,123,36,5,65,242,230,187,227,3,36,6,65,186,234,191,170,122,36,7,65,255,164,185,136,5,36,8,65,140,209,149,216,121,36,9,65,171,179,143,252,1,36,10,65,153,154,131,223,5,36,11,65,0,36,34,65,0,36,35,11,233,3,1,1,127,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,35,8,36,16,35,9,36,17,35,10,36,18,35,11,36,19,65,0,36,20,3,64,35,20,65,16,73,4,64,32,0,35,20,65,2,116,106,32,1,35,20,32,2,108,65,2,116,34,3,65,3,106,106,45,0,0,32,1,32,3,106,45,0,0,65,24,116,32,1,32,3,65,1,106,106,45,0,0,65,16,116,114,32,1,32,3,65,2,106,106,45,0,0,65,8,116,114,114,54,2,0,35,20,65,1,106,36,20,12,1,11,11,65,16,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,106,32,0,35,20,65,16,107,65,2,116,106,40,2,0,32,0,35,20,65,7,107,65,2,116,106,40,2,0,32,0,35,20,65,2,107,65,2,116,106,40,2,0,34,1,65,17,120,32,1,65,19,120,115,32,1,65,10,118,115,106,32,0,35,20,65,15,107,65,2,116,106,40,2,0,34,1,65,7,120,32,1,65,18,120,115,32,1,65,3,118,115,106,106,54,2,0,35,20,65,1,106,36,20,12,1,11,11,65,0,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,34,1,106,40,2,0,32,1,35,2,106,40,2,0,35,19,35,16,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,16,34,1,35,17,113,35,18,32,1,65,127,115,113,115,106,106,106,36,21,35,12,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,13,34,1,35,14,34,2,113,32,1,35,12,34,1,113,32,1,32,2,113,115,115,106,36,22,35,18,36,19,35,17,36,18,35,16,36,17,35,15,35,21,106,36,16,35,14,36,15,35,13,36,14,35,12,36,13,35,21,35,22,106,36,12,35,20,65,1,106,36,20,12,1,11,11,35,4,35,12,106,36,4,35,5,35,13,106,36,5,35,6,35,14,106,36,6,35,7,35,15,106,36,7,35,8,35,16,106,36,8,35,9,35,17,106,36,9,35,10,35,18,106,36,10,35,11,35,19,106,36,11,11,253,1,1,2,127,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,35,8,36,16,35,9,36,17,35,10,36,18,35,11,36,19,65,0,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,106,40,2,0,35,19,35,16,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,16,34,1,35,17,113,35,18,32,1,65,127,115,113,115,106,106,36,21,35,12,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,13,34,2,35,14,34,1,113,32,2,35,12,34,2,113,32,1,32,2,113,115,115,106,36,22,35,18,36,19,35,17,36,18,35,16,36,17,35,15,35,21,106,36,16,35,14,36,15,35,13,36,14,35,12,36,13,35,21,35,22,106,36,12,35,20,65,1,106,36,20,12,1,11,11,35,4,35,12,106,36,4,35,5,35,13,106,36,5,35,6,35,14,106,36,6,35,7,35,15,106,36,7,35,8,35,16,106,36,8,35,9,35,17,106,36,9,35,10,35,18,106,36,10,35,11,35,19,106,36,11,11,25,0,32,0,65,128,254,131,120,113,65,8,119,32,0,65,255,129,252,7,113,65,8,120,114,11,88,0,16,11,35,29,32,0,32,2,16,12,35,3,16,13,32,1,35,4,16,14,54,2,0,32,1,35,5,16,14,54,2,4,32,1,35,6,16,14,54,2,8,32,1,35,7,16,14,54,2,12,32,1,35,8,16,14,54,2,16,32,1,35,9,16,14,54,2,20,32,1,35,10,16,14,54,2,24,32,1,35,11,16,14,54,2,28,11,10,0,32,0,32,1,65,1,16,15,11,42,1,1,127,3,64,32,1,65,4,72,4,64,35,31,32,1,65,6,116,106,32,0,32,1,65,5,116,106,16,16,32,1,65,1,106,33,1,12,1,11,11,11,44,1,1,127,3,64,32,1,65,4,72,4,64,35,31,32,1,65,2,116,106,32,0,32,1,65,5,116,106,65,4,16,15,32,1,65,1,106,33,1,12,1,11,11,11,178,1,1,2,127,35,35,32,1,106,36,35,35,34,4,64,65,192,0,35,34,107,34,2,32,1,76,4,64,35,27,35,34,106,32,0,32,2,252,10,0,0,35,34,32,2,106,36,34,65,192,0,35,34,107,33,2,32,1,65,192,0,35,34,107,107,33,1,35,29,35,27,65,1,16,12,65,0,36,34,5,35,27,35,34,106,32,0,32,1,252,10,0,0,35,34,32,1,106,36,34,15,11,11,3,64,32,3,32,1,65,192,0,109,72,4,64,35,29,32,0,32,2,106,65,1,16,12,32,3,65,1,106,33,3,32,2,65,64,107,33,2,12,1,11,11,32,1,65,63,113,34,1,4,64,35,27,35,34,106,32,0,32,2,106,32,1,252,10,0,0,35,34,32,1,106,36,34,11,11,235,1,1,2,127,35,27,35,34,106,65,128,1,58,0,0,35,34,65,1,106,36,34,35,34,65,56,74,4,64,35,27,35,34,106,34,1,65,192,0,35,34,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,27,65,1,16,12,65,0,36,34,11,35,27,35,34,106,34,1,65,56,35,34,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,27,35,35,65,128,128,128,128,2,109,16,14,54,2,56,35,27,35,35,65,3,116,16,14,54,2,60,35,29,35,27,65,1,16,12,32,0,35,4,16,14,54,2,0,32,0,35,5,16,14,54,2,4,32,0,35,6,16,14,54,2,8,32,0,35,7,16,14,54,2,12,32,0,35,8,16,14,54,2,16,32,0,35,9,16,14,54,2,20,32,0,35,10,16,14,54,2,24,32,0,35,11,16,14,54,2,28,11,14,0,16,11,35,31,32,0,16,19,35,33,16,20,11,82,0,65,196,10,40,2,0,36,2,65,148,13,40,2,0,36,3,65,224,15,65,224,15,16,2,65,224,15,65,224,15,16,3,65,224,15,36,24,65,192,0,16,10,36,26,35,26,36,27,65,128,8,16,10,36,28,35,28,36,29,65,128,4,16,10,36,30,35,30,36,31,65,32,16,10,36,32,35,32,36,33,11,11,253,6,18,0,65,140,8,11,2,28,1,0,65,152,8,11,136,2,1,0,0,0,0,1,0,0,152,47,138,66,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,241,155,193,193,105,155,228,134,71,190,239,198,157,193,15,204,161,12,36,111,44,233,45,170,132,116,74,220,169,176,92,218,136,249,118,82,81,62,152,109,198,49,168,200,39,3,176,199,127,89,191,243,11,224,198,71,145,167,213,81,99,202,6,103,41,41,20,133,10,183,39,56,33,27,46,252,109,44,77,19,13,56,83,84,115,10,101,187,10,106,118,46,201,194,129,133,44,114,146,161,232,191,162,75,102,26,168,112,139,75,194,163,81,108,199,25,232,146,209,36,6,153,214,133,53,14,244,112,160,106,16,22,193,164,25,8,108,55,30,76,119,72,39,181,188,176,52,179,12,28,57,74,170,216,78,79,202,156,91,243,111,46,104,238,130,143,116,111,99,165,120,20,120,200,132,8,2,199,140,250,255,190,144,235,108,80,164,247,163,249,190,242,120,113,198,0,65,172,10,11,1,44,0,65,184,10,11,21,4,0,0,0,16,0,0,0,32,4,0,0,32,4,0,0,0,1,0,0,64,0,65,220,10,11,2,28,1,0,65,232,10,11,136,2,1,0,0,0,0,1,0,0,152,47,138,194,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,243,155,193,193,105,155,100,134,71,254,240,198,237,225,15,84,242,12,36,111,52,233,79,190,132,201,108,30,65,185,97,250,136,249,22,82,81,198,242,109,90,142,168,101,252,25,176,199,158,217,185,195,49,18,154,160,234,14,231,43,35,177,253,176,62,53,199,213,186,105,48,95,109,151,203,143,17,15,90,253,238,30,220,137,182,53,10,4,122,11,222,157,202,244,88,22,91,93,225,134,62,127,0,128,137,8,55,50,234,7,165,55,149,171,111,16,97,64,23,241,214,140,13,109,59,170,205,55,190,187,192,218,59,97,131,99,163,72,219,49,233,2,11,167,92,209,111,202,250,26,82,49,132,51,49,149,26,212,110,144,120,67,109,242,145,156,195,189,171,204,158,230,160,201,181,60,182,47,83,198,65,199,210,163,126,35,7,104,75,149,164,118,29,25,76,0,65,252,12,11,1,44,0,65,136,13,11,21,4,0,0,0,16,0,0,0,112,5,0,0,112,5,0,0,0,1,0,0,64,0,65,172,13,11,1,44,0,65,184,13,11,35,2,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,220,13,11,1,60,0,65,232,13,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,156,14,11,1,60,0,65,168,14,11,47,2,0,0,0,40,0,0,0,65,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,220,14,11,1,60,0,65,232,14,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,99,0,109,0,115,0,46,0,116,0,115,0,65,156,15,11,1,60,0,65,168,15,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115]);var $b=Uint8Array.from([0,97,115,109,1,0,0,0,1,37,7,96,2,127,127,0,96,1,127,1,127,96,2,127,127,1,127,96,1,127,0,96,0,0,96,4,127,127,127,127,0,96,3,127,127,126,0,2,13,1,3,101,110,118,5,97,98,111,114,116,0,5,3,30,29,0,0,0,0,0,6,1,2,2,2,1,2,1,1,2,4,4,1,0,3,3,4,0,0,3,3,3,0,4,5,3,1,0,1,6,227,4,61,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,127,1,65,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,4,11,127,0,65,128,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,1,11,7,169,1,13,8,72,65,83,95,83,73,77,68,3,60,22,98,97,116,99,104,72,97,115,104,52,85,105,110,116,65,114,114,97,121,54,52,115,0,20,26,98,97,116,99,104,72,97,115,104,52,72,97,115,104,79,98,106,101,99,116,73,110,112,117,116,115,0,21,12,73,78,80,85,84,95,76,69,78,71,84,72,3,28,15,80,65,82,65,76,76,69,76,95,70,65,67,84,79,82,3,27,5,105,110,112,117,116,3,54,6,111,117,116,112,117,116,3,56,4,105,110,105,116,0,22,6,117,112,100,97,116,101,0,24,5,102,105,110,97,108,0,25,6,100,105,103,101,115,116,0,26,8,100,105,103,101,115,116,54,52,0,28,6,109,101,109,111,114,121,2,0,8,1,29,12,1,38,10,243,111,29,9,0,32,0,32,1,54,2,0,11,9,0,32,0,32,1,54,2,4,11,9,0,32,0,32,1,54,2,8,11,192,1,1,4,127,32,1,40,2,0,65,124,113,34,3,65,128,2,73,4,127,32,3,65,4,118,5,65,31,65,252,255,255,255,3,32,3,32,3,65,252,255,255,255,3,79,27,34,3,103,107,34,4,65,7,107,33,2,32,3,32,4,65,4,107,118,65,16,115,11,33,3,32,1,40,2,8,33,5,32,1,40,2,4,34,4,4,64,32,4,32,5,16,3,11,32,5,4,64,32,5,32,4,16,2,11,32,1,32,0,32,2,65,4,116,32,3,106,65,2,116,106,34,1,40,2,96,70,4,64,32,1,32,5,54,2,96,32,5,69,4,64,32,0,32,2,65,2,116,106,34,1,40,2,4,65,126,32,3,119,113,33,3,32,1,32,3,54,2,4,32,3,69,4,64,32,0,32,0,40,2,0,65,126,32,2,119,113,16,1,11,11,11,11,181,2,1,5,127,32,1,40,2,0,33,3,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,2,65,1,113,4,64,32,0,32,4,16,4,32,1,32,3,65,4,106,32,2,65,124,113,106,34,3,16,1,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,2,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,1,40,2,0,33,6,32,0,32,1,16,4,32,1,32,6,65,4,106,32,3,65,124,113,106,34,3,16,1,11,32,4,32,2,65,2,114,16,1,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,5,65,31,65,252,255,255,255,3,32,2,32,2,65,252,255,255,255,3,79,27,34,2,103,107,34,3,65,7,107,33,5,32,2,32,3,65,4,107,118,65,16,115,11,34,2,32,5,65,4,116,106,65,2,116,106,40,2,96,33,3,32,1,65,0,16,2,32,1,32,3,16,3,32,3,4,64,32,3,32,1,16,2,11,32,0,32,5,65,4,116,32,2,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,5,116,114,16,1,32,0,32,5,65,2,116,106,34,0,32,0,40,2,4,65,1,32,2,116,114,54,2,4,11,130,1,1,3,127,32,1,65,19,106,65,112,113,65,4,107,33,1,32,0,40,2,160,12,34,3,4,64,32,3,32,1,65,16,107,34,5,70,4,64,32,3,40,2,0,33,4,32,5,33,1,11,11,32,2,167,65,112,113,32,1,107,34,3,65,20,73,4,64,15,11,32,1,32,4,65,2,113,32,3,65,8,107,34,3,65,1,114,114,16,1,32,1,65,0,16,2,32,1,65,0,16,3,32,1,65,4,106,32,3,106,34,3,65,2,16,1,32,0,32,3,54,2,160,12,32,0,32,1,16,5,11,29,0,32,0,65,1,65,27,32,0,103,107,116,106,65,1,107,32,0,32,0,65,254,255,255,255,1,73,27,11,142,1,1,2,127,32,1,65,128,2,73,4,127,32,1,65,4,118,5,65,31,32,1,16,7,34,1,103,107,34,3,65,7,107,33,2,32,1,32,3,65,4,107,118,65,16,115,11,33,1,32,0,32,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,148,2,1,3,127,32,1,65,252,255,255,255,3,75,4,64,65,176,14,65,176,15,65,205,3,65,29,16,0,0,11,32,0,65,12,32,1,65,19,106,65,112,113,65,4,107,32,1,65,12,77,27,34,1,16,8,34,2,69,4,64,32,1,65,128,2,79,4,127,32,1,16,7,5,32,1,11,33,2,63,0,34,3,32,2,65,4,32,0,40,2,160,12,32,3,65,16,116,65,4,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,2,32,2,32,3,72,27,64,0,65,0,72,4,64,32,2,64,0,65,0,72,4,64,0,11,11,32,0,32,3,65,16,116,63,0,172,66,16,134,16,6,32,0,32,1,16,8,33,2,11,32,2,40,2,0,26,32,0,32,2,16,4,32,2,40,2,0,34,3,65,124,113,32,1,107,34,4,65,16,79,4,64,32,2,32,1,32,3,65,2,113,114,16,1,32,2,65,4,106,32,1,106,34,1,32,4,65,4,107,65,1,114,16,1,32,0,32,1,16,5,5,32,2,32,3,65,126,113,16,1,32,2,65,4,106,32,2,40,2,0,65,124,113,106,34,0,32,0,40,2,0,65,125,113,16,1,11,32,2,11,133,2,1,2,127,32,0,65,236,255,255,255,3,75,4,64,65,176,14,65,240,14,65,253,0,65,30,16,0,0,11,35,20,69,4,64,63,0,34,3,65,0,76,4,127,65,1,32,3,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,208,21,65,0,16,1,65,240,33,65,0,54,2,0,3,64,32,2,65,23,73,4,64,32,2,65,2,116,65,208,21,106,65,0,54,2,4,65,0,33,3,3,64,32,3,65,16,73,4,64,32,2,65,4,116,32,3,106,65,2,116,65,208,21,106,65,0,54,2,96,32,3,65,1,106,33,3,12,1,11,11,32,2,65,1,106,33,2,12,1,11,11,65,208,21,65,244,33,63,0,172,66,16,134,16,6,65,208,21,36,20,11,35,20,32,0,65,16,106,16,9,34,2,32,1,54,2,12,32,2,32,0,54,2,16,35,21,34,0,40,2,8,33,1,32,2,32,0,16,2,32,2,32,1,16,3,32,1,32,2,32,1,40,2,4,65,3,113,114,16,2,32,0,32,2,16,3,35,22,32,2,40,2,0,65,124,113,65,4,106,106,36,22,32,2,65,20,106,11,46,1,1,127,32,0,65,252,255,255,255,3,75,4,64,65,192,13,65,240,13,65,52,65,43,16,0,0,11,32,0,65,1,16,10,34,1,65,0,32,0,252,11,0,32,1,11,41,0,32,1,32,0,40,2,12,79,4,64,65,144,16,65,208,16,65,242,0,65,42,16,0,0,11,32,0,40,2,4,32,1,65,2,116,106,40,2,0,11,181,1,1,4,127,32,0,69,4,64,65,192,18,15,11,65,0,32,0,107,32,0,32,0,65,31,118,65,1,116,34,1,27,34,0,65,10,79,65,1,106,32,0,65,144,206,0,79,65,3,106,32,0,65,232,7,79,106,32,0,65,228,0,73,27,32,0,65,192,132,61,79,65,6,106,32,0,65,128,148,235,220,3,79,65,8,106,32,0,65,128,194,215,47,79,106,32,0,65,128,173,226,4,73,27,32,0,65,160,141,6,73,27,34,2,65,1,116,32,1,106,65,2,16,10,34,3,32,1,106,33,4,3,64,32,4,32,2,65,1,107,34,2,65,1,116,106,32,0,65,10,112,65,48,106,59,1,0,32,0,65,10,110,34,0,13,0,11,32,1,4,64,32,3,65,45,59,1,0,11,32,3,11,13,0,32,0,65,20,107,40,2,16,65,1,118,11,64,1,3,127,32,0,16,14,65,1,116,34,2,32,1,16,14,65,1,116,34,3,106,34,4,69,4,64,65,160,20,15,11,32,4,65,2,16,10,34,4,32,0,32,2,252,10,0,0,32,2,32,4,106,32,1,32,3,252,10,0,0,32,4,11,145,16,2,2,127,1,123,65,224,15,65,224,15,16,2,65,224,15,65,224,15,16,3,65,224,15,36,21,65,128,8,16,11,36,23,35,23,36,24,2,64,3,64,32,0,65,192,0,72,4,64,35,24,33,1,65,192,10,32,0,16,12,253,17,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,32,0,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,67,11,32,1,32,2,253,11,4,0,12,63,11,32,1,32,2,253,11,4,16,12,62,11,32,1,32,2,253,11,4,32,12,61,11,32,1,32,2,253,11,4,48,12,60,11,32,1,32,2,253,11,4,64,12,59,11,32,1,32,2,253,11,4,80,12,58,11,32,1,32,2,253,11,4,96,12,57,11,32,1,32,2,253,11,4,112,12,56,11,32,1,32,2,253,11,4,128,1,12,55,11,32,1,32,2,253,11,4,144,1,12,54,11,32,1,32,2,253,11,4,160,1,12,53,11,32,1,32,2,253,11,4,176,1,12,52,11,32,1,32,2,253,11,4,192,1,12,51,11,32,1,32,2,253,11,4,208,1,12,50,11,32,1,32,2,253,11,4,224,1,12,49,11,32,1,32,2,253,11,4,240,1,12,48,11,32,1,32,2,253,11,4,128,2,12,47,11,32,1,32,2,253,11,4,144,2,12,46,11,32,1,32,2,253,11,4,160,2,12,45,11,32,1,32,2,253,11,4,176,2,12,44,11,32,1,32,2,253,11,4,192,2,12,43,11,32,1,32,2,253,11,4,208,2,12,42,11,32,1,32,2,253,11,4,224,2,12,41,11,32,1,32,2,253,11,4,240,2,12,40,11,32,1,32,2,253,11,4,128,3,12,39,11,32,1,32,2,253,11,4,144,3,12,38,11,32,1,32,2,253,11,4,160,3,12,37,11,32,1,32,2,253,11,4,176,3,12,36,11,32,1,32,2,253,11,4,192,3,12,35,11,32,1,32,2,253,11,4,208,3,12,34,11,32,1,32,2,253,11,4,224,3,12,33,11,32,1,32,2,253,11,4,240,3,12,32,11,32,1,32,2,253,11,4,128,4,12,31,11,32,1,32,2,253,11,4,144,4,12,30,11,32,1,32,2,253,11,4,160,4,12,29,11,32,1,32,2,253,11,4,176,4,12,28,11,32,1,32,2,253,11,4,192,4,12,27,11,32,1,32,2,253,11,4,208,4,12,26,11,32,1,32,2,253,11,4,224,4,12,25,11,32,1,32,2,253,11,4,240,4,12,24,11,32,1,32,2,253,11,4,128,5,12,23,11,32,1,32,2,253,11,4,144,5,12,22,11,32,1,32,2,253,11,4,160,5,12,21,11,32,1,32,2,253,11,4,176,5,12,20,11,32,1,32,2,253,11,4,192,5,12,19,11,32,1,32,2,253,11,4,208,5,12,18,11,32,1,32,2,253,11,4,224,5,12,17,11,32,1,32,2,253,11,4,240,5,12,16,11,32,1,32,2,253,11,4,128,6,12,15,11,32,1,32,2,253,11,4,144,6,12,14,11,32,1,32,2,253,11,4,160,6,12,13,11,32,1,32,2,253,11,4,176,6,12,12,11,32,1,32,2,253,11,4,192,6,12,11,11,32,1,32,2,253,11,4,208,6,12,10,11,32,1,32,2,253,11,4,224,6,12,9,11,32,1,32,2,253,11,4,240,6,12,8,11,32,1,32,2,253,11,4,128,7,12,7,11,32,1,32,2,253,11,4,144,7,12,6,11,32,1,32,2,253,11,4,160,7,12,5,11,32,1,32,2,253,11,4,176,7,12,4,11,32,1,32,2,253,11,4,192,7,12,3,11,32,1,32,2,253,11,4,208,7,12,2,11,32,1,32,2,253,11,4,224,7,12,1,11,32,1,32,2,253,11,4,240,7,11,32,0,65,1,106,33,0,12,1,11,11,65,128,8,16,11,36,25,35,25,36,26,65,0,33,0,3,64,32,0,65,192,0,72,4,64,35,26,33,1,65,144,13,32,0,16,12,253,17,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,32,0,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,67,11,32,1,32,2,253,11,4,0,12,63,11,32,1,32,2,253,11,4,16,12,62,11,32,1,32,2,253,11,4,32,12,61,11,32,1,32,2,253,11,4,48,12,60,11,32,1,32,2,253,11,4,64,12,59,11,32,1,32,2,253,11,4,80,12,58,11,32,1,32,2,253,11,4,96,12,57,11,32,1,32,2,253,11,4,112,12,56,11,32,1,32,2,253,11,4,128,1,12,55,11,32,1,32,2,253,11,4,144,1,12,54,11,32,1,32,2,253,11,4,160,1,12,53,11,32,1,32,2,253,11,4,176,1,12,52,11,32,1,32,2,253,11,4,192,1,12,51,11,32,1,32,2,253,11,4,208,1,12,50,11,32,1,32,2,253,11,4,224,1,12,49,11,32,1,32,2,253,11,4,240,1,12,48,11,32,1,32,2,253,11,4,128,2,12,47,11,32,1,32,2,253,11,4,144,2,12,46,11,32,1,32,2,253,11,4,160,2,12,45,11,32,1,32,2,253,11,4,176,2,12,44,11,32,1,32,2,253,11,4,192,2,12,43,11,32,1,32,2,253,11,4,208,2,12,42,11,32,1,32,2,253,11,4,224,2,12,41,11,32,1,32,2,253,11,4,240,2,12,40,11,32,1,32,2,253,11,4,128,3,12,39,11,32,1,32,2,253,11,4,144,3,12,38,11,32,1,32,2,253,11,4,160,3,12,37,11,32,1,32,2,253,11,4,176,3,12,36,11,32,1,32,2,253,11,4,192,3,12,35,11,32,1,32,2,253,11,4,208,3,12,34,11,32,1,32,2,253,11,4,224,3,12,33,11,32,1,32,2,253,11,4,240,3,12,32,11,32,1,32,2,253,11,4,128,4,12,31,11,32,1,32,2,253,11,4,144,4,12,30,11,32,1,32,2,253,11,4,160,4,12,29,11,32,1,32,2,253,11,4,176,4,12,28,11,32,1,32,2,253,11,4,192,4,12,27,11,32,1,32,2,253,11,4,208,4,12,26,11,32,1,32,2,253,11,4,224,4,12,25,11,32,1,32,2,253,11,4,240,4,12,24,11,32,1,32,2,253,11,4,128,5,12,23,11,32,1,32,2,253,11,4,144,5,12,22,11,32,1,32,2,253,11,4,160,5,12,21,11,32,1,32,2,253,11,4,176,5,12,20,11,32,1,32,2,253,11,4,192,5,12,19,11,32,1,32,2,253,11,4,208,5,12,18,11,32,1,32,2,253,11,4,224,5,12,17,11,32,1,32,2,253,11,4,240,5,12,16,11,32,1,32,2,253,11,4,128,6,12,15,11,32,1,32,2,253,11,4,144,6,12,14,11,32,1,32,2,253,11,4,160,6,12,13,11,32,1,32,2,253,11,4,176,6,12,12,11,32,1,32,2,253,11,4,192,6,12,11,11,32,1,32,2,253,11,4,208,6,12,10,11,32,1,32,2,253,11,4,224,6,12,9,11,32,1,32,2,253,11,4,240,6,12,8,11,32,1,32,2,253,11,4,128,7,12,7,11,32,1,32,2,253,11,4,144,7,12,6,11,32,1,32,2,253,11,4,160,7,12,5,11,32,1,32,2,253,11,4,176,7,12,4,11,32,1,32,2,253,11,4,192,7,12,3,11,32,1,32,2,253,11,4,208,7,12,2,11,32,1,32,2,253,11,4,224,7,12,1,11,32,1,32,2,253,11,4,240,7,11,32,0,65,1,106,33,0,12,1,11,11,15,11,65,192,19,32,0,16,13,16,15,65,192,20,65,201,1,65,7,16,0,0,11,192,10,2,2,123,2,127,35,0,36,8,35,1,36,9,35,2,36,10,35,3,36,11,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,65,0,36,18,3,64,35,18,65,192,0,72,4,64,35,15,35,12,34,0,65,6,253,173,1,32,0,65,26,253,171,1,253,80,32,0,65,11,253,173,1,32,0,65,21,253,171,1,253,80,253,81,32,0,65,25,253,173,1,32,0,65,7,253,171,1,253,80,253,81,253,174,1,35,12,34,0,35,13,253,78,32,0,253,77,35,14,253,78,253,81,253,174,1,33,1,35,26,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,3,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,2,253,0,4,0,33,0,12,64,11,32,2,253,0,4,16,33,0,12,63,11,32,2,253,0,4,32,33,0,12,62,11,32,2,253,0,4,48,33,0,12,61,11,32,2,253,0,4,64,33,0,12,60,11,32,2,253,0,4,80,33,0,12,59,11,32,2,253,0,4,96,33,0,12,58,11,32,2,253,0,4,112,33,0,12,57,11,32,2,253,0,4,128,1,33,0,12,56,11,32,2,253,0,4,144,1,33,0,12,55,11,32,2,253,0,4,160,1,33,0,12,54,11,32,2,253,0,4,176,1,33,0,12,53,11,32,2,253,0,4,192,1,33,0,12,52,11,32,2,253,0,4,208,1,33,0,12,51,11,32,2,253,0,4,224,1,33,0,12,50,11,32,2,253,0,4,240,1,33,0,12,49,11,32,2,253,0,4,128,2,33,0,12,48,11,32,2,253,0,4,144,2,33,0,12,47,11,32,2,253,0,4,160,2,33,0,12,46,11,32,2,253,0,4,176,2,33,0,12,45,11,32,2,253,0,4,192,2,33,0,12,44,11,32,2,253,0,4,208,2,33,0,12,43,11,32,2,253,0,4,224,2,33,0,12,42,11,32,2,253,0,4,240,2,33,0,12,41,11,32,2,253,0,4,128,3,33,0,12,40,11,32,2,253,0,4,144,3,33,0,12,39,11,32,2,253,0,4,160,3,33,0,12,38,11,32,2,253,0,4,176,3,33,0,12,37,11,32,2,253,0,4,192,3,33,0,12,36,11,32,2,253,0,4,208,3,33,0,12,35,11,32,2,253,0,4,224,3,33,0,12,34,11,32,2,253,0,4,240,3,33,0,12,33,11,32,2,253,0,4,128,4,33,0,12,32,11,32,2,253,0,4,144,4,33,0,12,31,11,32,2,253,0,4,160,4,33,0,12,30,11,32,2,253,0,4,176,4,33,0,12,29,11,32,2,253,0,4,192,4,33,0,12,28,11,32,2,253,0,4,208,4,33,0,12,27,11,32,2,253,0,4,224,4,33,0,12,26,11,32,2,253,0,4,240,4,33,0,12,25,11,32,2,253,0,4,128,5,33,0,12,24,11,32,2,253,0,4,144,5,33,0,12,23,11,32,2,253,0,4,160,5,33,0,12,22,11,32,2,253,0,4,176,5,33,0,12,21,11,32,2,253,0,4,192,5,33,0,12,20,11,32,2,253,0,4,208,5,33,0,12,19,11,32,2,253,0,4,224,5,33,0,12,18,11,32,2,253,0,4,240,5,33,0,12,17,11,32,2,253,0,4,128,6,33,0,12,16,11,32,2,253,0,4,144,6,33,0,12,15,11,32,2,253,0,4,160,6,33,0,12,14,11,32,2,253,0,4,176,6,33,0,12,13,11,32,2,253,0,4,192,6,33,0,12,12,11,32,2,253,0,4,208,6,33,0,12,11,11,32,2,253,0,4,224,6,33,0,12,10,11,32,2,253,0,4,240,6,33,0,12,9,11,32,2,253,0,4,128,7,33,0,12,8,11,32,2,253,0,4,144,7,33,0,12,7,11,32,2,253,0,4,160,7,33,0,12,6,11,32,2,253,0,4,176,7,33,0,12,5,11,32,2,253,0,4,192,7,33,0,12,4,11,32,2,253,0,4,208,7,33,0,12,3,11,32,2,253,0,4,224,7,33,0,12,2,11,32,2,253,0,4,240,7,33,0,12,1,11,65,128,21,32,3,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,32,1,32,0,253,174,1,36,16,35,8,34,0,65,2,253,173,1,32,0,65,30,253,171,1,253,80,32,0,65,13,253,173,1,32,0,65,19,253,171,1,253,80,253,81,32,0,65,22,253,173,1,32,0,65,10,253,171,1,253,80,253,81,35,8,34,0,35,9,34,1,253,78,32,0,35,10,34,0,253,78,253,81,32,1,32,0,253,78,253,81,253,174,1,36,17,35,14,36,15,35,13,36,14,35,12,36,13,35,11,35,16,253,174,1,36,12,35,10,36,11,35,9,36,10,35,8,36,9,35,16,35,17,253,174,1,36,8,35,18,65,1,106,36,18,12,1,11,11,35,0,35,8,253,174,1,36,0,35,1,35,9,253,174,1,36,1,35,2,35,10,253,174,1,36,2,35,3,35,11,253,174,1,36,3,35,4,35,12,253,174,1,36,4,35,5,35,13,253,174,1,36,5,35,6,35,14,253,174,1,36,6,35,7,35,15,253,174,1,36,7,11,25,0,32,0,65,128,254,131,120,113,65,8,119,32,0,65,255,129,252,7,113,65,8,120,114,11,157,57,2,2,123,2,127,253,12,103,230,9,106,103,230,9,106,103,230,9,106,103,230,9,106,36,0,253,12,133,174,103,187,133,174,103,187,133,174,103,187,133,174,103,187,36,1,253,12,114,243,110,60,114,243,110,60,114,243,110,60,114,243,110,60,36,2,253,12,58,245,79,165,58,245,79,165,58,245,79,165,58,245,79,165,36,3,253,12,127,82,14,81,127,82,14,81,127,82,14,81,127,82,14,81,36,4,253,12,140,104,5,155,140,104,5,155,140,104,5,155,140,104,5,155,36,5,253,12,171,217,131,31,171,217,131,31,171,217,131,31,171,217,131,31,36,6,253,12,25,205,224,91,25,205,224,91,25,205,224,91,25,205,224,91,36,7,253,12,103,230,9,106,103,230,9,106,103,230,9,106,103,230,9,106,36,8,253,12,133,174,103,187,133,174,103,187,133,174,103,187,133,174,103,187,36,9,253,12,114,243,110,60,114,243,110,60,114,243,110,60,114,243,110,60,36,10,253,12,58,245,79,165,58,245,79,165,58,245,79,165,58,245,79,165,36,11,253,12,127,82,14,81,127,82,14,81,127,82,14,81,127,82,14,81,36,12,253,12,140,104,5,155,140,104,5,155,140,104,5,155,140,104,5,155,36,13,253,12,171,217,131,31,171,217,131,31,171,217,131,31,171,217,131,31,36,14,253,12,25,205,224,91,25,205,224,91,25,205,224,91,25,205,224,91,36,15,65,0,36,18,2,64,3,64,35,18,65,192,0,72,4,64,35,18,65,16,72,4,123,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,5,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,2,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,34,2,65,17,253,173,1,32,2,65,15,253,171,1,253,80,32,2,65,19,253,173,1,32,2,65,13,253,171,1,253,80,253,81,32,2,65,10,253,173,1,253,81,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,7,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,253,174,1,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,15,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,34,2,65,7,253,173,1,32,2,65,25,253,171,1,253,80,32,2,65,18,253,173,1,32,2,65,14,253,171,1,253,80,253,81,32,2,65,3,253,173,1,253,81,253,174,1,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,16,107,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,253,174,1,11,36,19,35,18,65,16,78,4,64,35,19,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,4,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,0,32,2,253,11,4,0,12,64,11,32,0,32,2,253,11,4,16,12,63,11,32,0,32,2,253,11,4,32,12,62,11,32,0,32,2,253,11,4,48,12,61,11,32,0,32,2,253,11,4,64,12,60,11,32,0,32,2,253,11,4,80,12,59,11,32,0,32,2,253,11,4,96,12,58,11,32,0,32,2,253,11,4,112,12,57,11,32,0,32,2,253,11,4,128,1,12,56,11,32,0,32,2,253,11,4,144,1,12,55,11,32,0,32,2,253,11,4,160,1,12,54,11,32,0,32,2,253,11,4,176,1,12,53,11,32,0,32,2,253,11,4,192,1,12,52,11,32,0,32,2,253,11,4,208,1,12,51,11,32,0,32,2,253,11,4,224,1,12,50,11,32,0,32,2,253,11,4,240,1,12,49,11,32,0,32,2,253,11,4,128,2,12,48,11,32,0,32,2,253,11,4,144,2,12,47,11,32,0,32,2,253,11,4,160,2,12,46,11,32,0,32,2,253,11,4,176,2,12,45,11,32,0,32,2,253,11,4,192,2,12,44,11,32,0,32,2,253,11,4,208,2,12,43,11,32,0,32,2,253,11,4,224,2,12,42,11,32,0,32,2,253,11,4,240,2,12,41,11,32,0,32,2,253,11,4,128,3,12,40,11,32,0,32,2,253,11,4,144,3,12,39,11,32,0,32,2,253,11,4,160,3,12,38,11,32,0,32,2,253,11,4,176,3,12,37,11,32,0,32,2,253,11,4,192,3,12,36,11,32,0,32,2,253,11,4,208,3,12,35,11,32,0,32,2,253,11,4,224,3,12,34,11,32,0,32,2,253,11,4,240,3,12,33,11,32,0,32,2,253,11,4,128,4,12,32,11,32,0,32,2,253,11,4,144,4,12,31,11,32,0,32,2,253,11,4,160,4,12,30,11,32,0,32,2,253,11,4,176,4,12,29,11,32,0,32,2,253,11,4,192,4,12,28,11,32,0,32,2,253,11,4,208,4,12,27,11,32,0,32,2,253,11,4,224,4,12,26,11,32,0,32,2,253,11,4,240,4,12,25,11,32,0,32,2,253,11,4,128,5,12,24,11,32,0,32,2,253,11,4,144,5,12,23,11,32,0,32,2,253,11,4,160,5,12,22,11,32,0,32,2,253,11,4,176,5,12,21,11,32,0,32,2,253,11,4,192,5,12,20,11,32,0,32,2,253,11,4,208,5,12,19,11,32,0,32,2,253,11,4,224,5,12,18,11,32,0,32,2,253,11,4,240,5,12,17,11,32,0,32,2,253,11,4,128,6,12,16,11,32,0,32,2,253,11,4,144,6,12,15,11,32,0,32,2,253,11,4,160,6,12,14,11,32,0,32,2,253,11,4,176,6,12,13,11,32,0,32,2,253,11,4,192,6,12,12,11,32,0,32,2,253,11,4,208,6,12,11,11,32,0,32,2,253,11,4,224,6,12,10,11,32,0,32,2,253,11,4,240,6,12,9,11,32,0,32,2,253,11,4,128,7,12,8,11,32,0,32,2,253,11,4,144,7,12,7,11,32,0,32,2,253,11,4,160,7,12,6,11,32,0,32,2,253,11,4,176,7,12,5,11,32,0,32,2,253,11,4,192,7,12,4,11,32,0,32,2,253,11,4,208,7,12,3,11,32,0,32,2,253,11,4,224,7,12,2,11,32,0,32,2,253,11,4,240,7,12,1,11,65,192,19,32,4,16,13,16,15,65,192,20,65,201,1,65,7,16,0,0,11,11,35,15,35,12,34,2,65,6,253,173,1,32,2,65,26,253,171,1,253,80,32,2,65,11,253,173,1,32,2,65,21,253,171,1,253,80,253,81,32,2,65,25,253,173,1,32,2,65,7,253,171,1,253,80,253,81,253,174,1,35,12,34,2,35,13,253,78,32,2,253,77,35,14,253,78,253,81,253,174,1,33,3,35,24,33,4,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,5,14,64,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,4,253,0,4,0,33,2,12,64,11,32,4,253,0,4,16,33,2,12,63,11,32,4,253,0,4,32,33,2,12,62,11,32,4,253,0,4,48,33,2,12,61,11,32,4,253,0,4,64,33,2,12,60,11,32,4,253,0,4,80,33,2,12,59,11,32,4,253,0,4,96,33,2,12,58,11,32,4,253,0,4,112,33,2,12,57,11,32,4,253,0,4,128,1,33,2,12,56,11,32,4,253,0,4,144,1,33,2,12,55,11,32,4,253,0,4,160,1,33,2,12,54,11,32,4,253,0,4,176,1,33,2,12,53,11,32,4,253,0,4,192,1,33,2,12,52,11,32,4,253,0,4,208,1,33,2,12,51,11,32,4,253,0,4,224,1,33,2,12,50,11,32,4,253,0,4,240,1,33,2,12,49,11,32,4,253,0,4,128,2,33,2,12,48,11,32,4,253,0,4,144,2,33,2,12,47,11,32,4,253,0,4,160,2,33,2,12,46,11,32,4,253,0,4,176,2,33,2,12,45,11,32,4,253,0,4,192,2,33,2,12,44,11,32,4,253,0,4,208,2,33,2,12,43,11,32,4,253,0,4,224,2,33,2,12,42,11,32,4,253,0,4,240,2,33,2,12,41,11,32,4,253,0,4,128,3,33,2,12,40,11,32,4,253,0,4,144,3,33,2,12,39,11,32,4,253,0,4,160,3,33,2,12,38,11,32,4,253,0,4,176,3,33,2,12,37,11,32,4,253,0,4,192,3,33,2,12,36,11,32,4,253,0,4,208,3,33,2,12,35,11,32,4,253,0,4,224,3,33,2,12,34,11,32,4,253,0,4,240,3,33,2,12,33,11,32,4,253,0,4,128,4,33,2,12,32,11,32,4,253,0,4,144,4,33,2,12,31,11,32,4,253,0,4,160,4,33,2,12,30,11,32,4,253,0,4,176,4,33,2,12,29,11,32,4,253,0,4,192,4,33,2,12,28,11,32,4,253,0,4,208,4,33,2,12,27,11,32,4,253,0,4,224,4,33,2,12,26,11,32,4,253,0,4,240,4,33,2,12,25,11,32,4,253,0,4,128,5,33,2,12,24,11,32,4,253,0,4,144,5,33,2,12,23,11,32,4,253,0,4,160,5,33,2,12,22,11,32,4,253,0,4,176,5,33,2,12,21,11,32,4,253,0,4,192,5,33,2,12,20,11,32,4,253,0,4,208,5,33,2,12,19,11,32,4,253,0,4,224,5,33,2,12,18,11,32,4,253,0,4,240,5,33,2,12,17,11,32,4,253,0,4,128,6,33,2,12,16,11,32,4,253,0,4,144,6,33,2,12,15,11,32,4,253,0,4,160,6,33,2,12,14,11,32,4,253,0,4,176,6,33,2,12,13,11,32,4,253,0,4,192,6,33,2,12,12,11,32,4,253,0,4,208,6,33,2,12,11,11,32,4,253,0,4,224,6,33,2,12,10,11,32,4,253,0,4,240,6,33,2,12,9,11,32,4,253,0,4,128,7,33,2,12,8,11,32,4,253,0,4,144,7,33,2,12,7,11,32,4,253,0,4,160,7,33,2,12,6,11,32,4,253,0,4,176,7,33,2,12,5,11,32,4,253,0,4,192,7,33,2,12,4,11,32,4,253,0,4,208,7,33,2,12,3,11,32,4,253,0,4,224,7,33,2,12,2,11,32,4,253,0,4,240,7,33,2,12,1,11,65,128,21,32,5,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,32,3,32,2,253,174,1,35,19,253,174,1,36,16,35,8,34,2,65,2,253,173,1,32,2,65,30,253,171,1,253,80,32,2,65,13,253,173,1,32,2,65,19,253,171,1,253,80,253,81,32,2,65,22,253,173,1,32,2,65,10,253,171,1,253,80,253,81,35,8,34,2,35,9,34,3,253,78,32,2,35,10,34,2,253,78,253,81,32,3,32,2,253,78,253,81,253,174,1,36,17,35,14,36,15,35,13,36,14,35,12,36,13,35,11,35,16,253,174,1,36,12,35,10,36,11,35,9,36,10,35,8,36,9,35,16,35,17,253,174,1,36,8,35,18,65,1,106,36,18,12,1,11,11,35,0,35,8,253,174,1,36,0,35,1,35,9,253,174,1,36,1,35,2,35,10,253,174,1,36,2,35,3,35,11,253,174,1,36,3,35,4,35,12,253,174,1,36,4,35,5,35,13,253,174,1,36,5,35,6,35,14,253,174,1,36,6,35,7,35,15,253,174,1,36,7,16,17,32,1,35,0,253,27,0,16,18,54,2,0,32,1,35,1,253,27,0,16,18,54,2,4,32,1,35,2,253,27,0,16,18,54,2,8,32,1,35,3,253,27,0,16,18,54,2,12,32,1,35,4,253,27,0,16,18,54,2,16,32,1,35,5,253,27,0,16,18,54,2,20,32,1,35,6,253,27,0,16,18,54,2,24,32,1,35,7,253,27,0,16,18,54,2,28,32,1,35,0,253,27,1,16,18,54,2,32,32,1,35,1,253,27,1,16,18,54,2,36,32,1,35,2,253,27,1,16,18,54,2,40,32,1,35,3,253,27,1,16,18,54,2,44,32,1,35,4,253,27,1,16,18,54,2,48,32,1,35,5,253,27,1,16,18,54,2,52,32,1,35,6,253,27,1,16,18,54,2,56,32,1,35,7,253,27,1,16,18,54,2,60,32,1,65,64,107,35,0,253,27,2,16,18,54,2,0,32,1,35,1,253,27,2,16,18,54,2,68,32,1,35,2,253,27,2,16,18,54,2,72,32,1,35,3,253,27,2,16,18,54,2,76,32,1,35,4,253,27,2,16,18,54,2,80,32,1,35,5,253,27,2,16,18,54,2,84,32,1,35,6,253,27,2,16,18,54,2,88,32,1,35,7,253,27,2,16,18,54,2,92,32,1,35,0,253,27,3,16,18,54,2,96,32,1,35,1,253,27,3,16,18,54,2,100,32,1,35,2,253,27,3,16,18,54,2,104,32,1,35,3,253,27,3,16,18,54,2,108,32,1,35,4,253,27,3,16,18,54,2,112,32,1,35,5,253,27,3,16,18,54,2,116,32,1,35,6,253,27,3,16,18,54,2,120,32,1,35,7,253,27,3,16,18,54,2,124,15,11,65,128,21,32,4,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,203,2,1,5,127,3,64,32,1,65,16,72,4,64,32,1,65,2,116,34,2,65,1,106,33,3,35,53,32,2,65,2,116,106,32,2,65,3,106,34,4,35,55,34,5,106,45,0,0,32,2,32,5,106,45,0,0,65,24,116,32,3,32,5,106,45,0,0,65,16,116,114,32,2,65,2,106,34,2,32,5,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,3,65,2,116,106,35,55,34,3,32,1,65,16,106,65,2,116,34,5,65,3,106,106,45,0,0,32,3,32,5,106,45,0,0,65,24,116,32,5,65,1,106,32,3,106,45,0,0,65,16,116,114,32,5,65,2,106,32,3,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,2,65,2,116,106,35,55,34,2,32,1,65,32,106,65,2,116,34,3,65,3,106,106,45,0,0,32,2,32,3,106,45,0,0,65,24,116,32,3,65,1,106,32,2,106,45,0,0,65,16,116,114,32,3,65,2,106,32,2,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,4,65,2,116,106,35,55,34,2,32,1,65,48,106,65,2,116,34,3,65,3,106,106,45,0,0,32,2,32,3,106,45,0,0,65,24,116,32,3,65,1,106,32,2,106,45,0,0,65,16,116,114,32,3,65,2,106,32,2,106,45,0,0,65,8,116,114,114,54,2,0,32,1,65,1,106,33,1,12,1,11,11,35,53,32,0,16,19,11,99,1,3,127,3,64,32,2,65,192,0,72,4,64,32,2,65,2,116,34,1,35,53,106,35,55,34,3,32,1,65,3,106,106,45,0,0,32,1,32,3,106,45,0,0,65,24,116,32,1,65,1,106,32,3,106,45,0,0,65,16,116,114,32,1,65,2,106,32,3,106,45,0,0,65,8,116,114,114,54,2,0,32,2,65,1,106,33,2,12,1,11,11,35,53,32,0,16,19,11,74,0,65,231,204,167,208,6,36,31,65,133,221,158,219,123,36,32,65,242,230,187,227,3,36,33,65,186,234,191,170,122,36,34,65,255,164,185,136,5,36,35,65,140,209,149,216,121,36,36,65,171,179,143,252,1,36,37,65,153,154,131,223,5,36,38,65,0,36,58,65,0,36,59,11,227,3,1,2,127,35,31,36,39,35,32,36,40,35,33,36,41,35,34,36,42,35,35,36,43,35,36,36,44,35,37,36,45,35,38,36,46,65,0,36,47,3,64,35,47,65,16,73,4,64,35,47,65,2,116,34,2,32,0,106,32,1,32,2,65,3,106,106,45,0,0,32,1,32,2,106,45,0,0,65,24,116,32,1,32,2,65,1,106,106,45,0,0,65,16,116,114,32,1,32,2,65,2,106,106,45,0,0,65,8,116,114,114,54,2,0,35,47,65,1,106,36,47,12,1,11,11,65,16,36,47,3,64,35,47,65,192,0,73,4,64,32,0,35,47,65,2,116,106,32,0,35,47,65,16,107,65,2,116,106,40,2,0,32,0,35,47,65,7,107,65,2,116,106,40,2,0,32,0,35,47,65,2,107,65,2,116,106,40,2,0,34,1,65,17,120,32,1,65,19,120,115,32,1,65,10,118,115,106,32,0,35,47,65,15,107,65,2,116,106,40,2,0,34,1,65,7,120,32,1,65,18,120,115,32,1,65,3,118,115,106,106,54,2,0,35,47,65,1,106,36,47,12,1,11,11,65,0,36,47,3,64,35,47,65,192,0,73,4,64,35,47,65,2,116,34,1,32,0,106,40,2,0,32,1,35,29,106,40,2,0,35,46,35,43,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,43,34,1,35,44,113,35,45,32,1,65,127,115,113,115,106,106,106,36,48,35,39,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,40,34,2,35,41,34,3,113,35,39,34,1,32,2,113,32,1,32,3,113,115,115,106,36,49,35,45,36,46,35,44,36,45,35,43,36,44,35,42,35,48,106,36,43,35,41,36,42,35,40,36,41,35,39,36,40,35,48,35,49,106,36,39,35,47,65,1,106,36,47,12,1,11,11,35,31,35,39,106,36,31,35,32,35,40,106,36,32,35,33,35,41,106,36,33,35,34,35,42,106,36,34,35,35,35,43,106,36,35,35,36,35,44,106,36,36,35,37,35,45,106,36,37,35,38,35,46,106,36,38,11,174,1,1,2,127,35,59,32,1,106,36,59,35,58,4,64,65,192,0,35,58,107,34,2,32,1,76,4,64,35,51,35,58,106,32,0,32,2,252,10,0,0,35,58,32,2,106,36,58,65,192,0,35,58,107,33,2,32,1,65,192,0,35,58,107,107,33,1,35,53,35,51,16,23,65,0,36,58,5,35,51,35,58,106,32,0,32,1,252,10,0,0,35,58,32,1,106,36,58,15,11,11,3,64,32,3,32,1,65,192,0,109,72,4,64,35,53,32,0,32,2,106,16,23,32,3,65,1,106,33,3,32,2,65,64,107,33,2,12,1,11,11,32,1,65,63,113,34,1,4,64,35,51,35,58,106,32,0,32,2,106,32,1,252,10,0,0,35,58,32,1,106,36,58,11,11,231,1,1,2,127,35,51,35,58,106,65,128,1,58,0,0,35,58,65,1,106,36,58,35,58,65,56,74,4,64,35,51,35,58,106,34,1,65,192,0,35,58,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,53,35,51,16,23,65,0,36,58,11,35,51,35,58,106,34,1,65,56,35,58,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,51,35,59,65,128,128,128,128,2,109,16,18,54,2,56,35,51,35,59,65,3,116,16,18,54,2,60,35,53,35,51,16,23,32,0,35,31,16,18,54,2,0,32,0,35,32,16,18,54,2,4,32,0,35,33,16,18,54,2,8,32,0,35,34,16,18,54,2,12,32,0,35,35,16,18,54,2,16,32,0,35,36,16,18,54,2,20,32,0,35,37,16,18,54,2,24,32,0,35,38,16,18,54,2,28,11,14,0,16,22,35,55,32,0,16,24,35,57,16,25,11,253,1,1,2,127,35,31,36,39,35,32,36,40,35,33,36,41,35,34,36,42,35,35,36,43,35,36,36,44,35,37,36,45,35,38,36,46,65,0,36,47,3,64,35,47,65,192,0,73,4,64,32,0,35,47,65,2,116,106,40,2,0,35,46,35,43,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,43,34,1,35,44,113,35,45,32,1,65,127,115,113,115,106,106,36,48,35,39,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,40,34,2,35,41,34,1,113,32,2,35,39,34,2,113,32,1,32,2,113,115,115,106,36,49,35,45,36,46,35,44,36,45,35,43,36,44,35,42,35,48,106,36,43,35,41,36,42,35,40,36,41,35,39,36,40,35,48,35,49,106,36,39,35,47,65,1,106,36,47,12,1,11,11,35,31,35,39,106,36,31,35,32,35,40,106,36,32,35,33,35,41,106,36,33,35,34,35,42,106,36,34,35,35,35,43,106,36,35,35,36,35,44,106,36,36,35,37,35,45,106,36,37,35,38,35,46,106,36,38,11,86,0,16,22,35,53,32,0,16,23,35,30,16,27,32,1,35,31,16,18,54,2,0,32,1,35,32,16,18,54,2,4,32,1,35,33,16,18,54,2,8,32,1,35,34,16,18,54,2,12,32,1,35,35,16,18,54,2,16,32,1,35,36,16,18,54,2,20,32,1,35,37,16,18,54,2,24,32,1,35,38,16,18,54,2,28,11,63,0,16,16,65,196,10,40,2,0,36,29,65,148,13,40,2,0,36,30,65,192,0,16,11,36,50,35,50,36,51,65,128,8,16,11,36,52,35,52,36,53,65,128,4,16,11,36,54,35,54,36,55,65,32,16,11,36,56,35,56,36,57,11,11,141,12,38,0,65,140,8,11,2,28,1,0,65,152,8,11,136,2,1,0,0,0,0,1,0,0,152,47,138,66,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,241,155,193,193,105,155,228,134,71,190,239,198,157,193,15,204,161,12,36,111,44,233,45,170,132,116,74,220,169,176,92,218,136,249,118,82,81,62,152,109,198,49,168,200,39,3,176,199,127,89,191,243,11,224,198,71,145,167,213,81,99,202,6,103,41,41,20,133,10,183,39,56,33,27,46,252,109,44,77,19,13,56,83,84,115,10,101,187,10,106,118,46,201,194,129,133,44,114,146,161,232,191,162,75,102,26,168,112,139,75,194,163,81,108,199,25,232,146,209,36,6,153,214,133,53,14,244,112,160,106,16,22,193,164,25,8,108,55,30,76,119,72,39,181,188,176,52,179,12,28,57,74,170,216,78,79,202,156,91,243,111,46,104,238,130,143,116,111,99,165,120,20,120,200,132,8,2,199,140,250,255,190,144,235,108,80,164,247,163,249,190,242,120,113,198,0,65,172,10,11,1,44,0,65,184,10,11,21,4,0,0,0,16,0,0,0,32,4,0,0,32,4,0,0,0,1,0,0,64,0,65,220,10,11,2,28,1,0,65,232,10,11,136,2,1,0,0,0,0,1,0,0,152,47,138,194,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,243,155,193,193,105,155,100,134,71,254,240,198,237,225,15,84,242,12,36,111,52,233,79,190,132,201,108,30,65,185,97,250,136,249,22,82,81,198,242,109,90,142,168,101,252,25,176,199,158,217,185,195,49,18,154,160,234,14,231,43,35,177,253,176,62,53,199,213,186,105,48,95,109,151,203,143,17,15,90,253,238,30,220,137,182,53,10,4,122,11,222,157,202,244,88,22,91,93,225,134,62,127,0,128,137,8,55,50,234,7,165,55,149,171,111,16,97,64,23,241,214,140,13,109,59,170,205,55,190,187,192,218,59,97,131,99,163,72,219,49,233,2,11,167,92,209,111,202,250,26,82,49,132,51,49,149,26,212,110,144,120,67,109,242,145,156,195,189,171,204,158,230,160,201,181,60,182,47,83,198,65,199,210,163,126,35,7,104,75,149,164,118,29,25,76,0,65,252,12,11,1,44,0,65,136,13,11,21,4,0,0,0,16,0,0,0,112,5,0,0,112,5,0,0,0,1,0,0,64,0,65,172,13,11,1,44,0,65,184,13,11,35,2,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,220,13,11,1,60,0,65,232,13,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,156,14,11,1,60,0,65,168,14,11,47,2,0,0,0,40,0,0,0,65,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,220,14,11,1,60,0,65,232,14,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,99,0,109,0,115,0,46,0,116,0,115,0,65,156,15,11,1,60,0,65,168,15,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115,0,65,252,15,11,1,60,0,65,136,16,11,43,2,0,0,0,36,0,0,0,73,0,110,0,100,0,101,0,120,0,32,0,111,0,117,0,116,0,32,0,111,0,102,0,32,0,114,0,97,0,110,0,103,0,101,0,65,188,16,11,1,44,0,65,200,16,11,33,2,0,0,0,26,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,46,0,116,0,115,0,65,236,16,11,1,124,0,65,248,16,11,107,2,0,0,0,100,0,0,0,116,0,111,0,83,0,116,0,114,0,105,0,110,0,103,0,40,0,41,0,32,0,114,0,97,0,100,0,105,0,120,0,32,0,97,0,114,0,103,0,117,0,109,0,101,0,110,0,116,0,32,0,109,0,117,0,115,0,116,0,32,0,98,0,101,0,32,0,98,0,101,0,116,0,119,0,101,0,101,0,110,0,32,0,50,0,32,0,97,0,110,0,100,0,32,0,51,0,54,0,65,236,17,11,1,60,0,65,248,17,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,117,0,116,0,105,0,108,0,47,0,110,0,117,0,109,0,98,0,101,0,114,0,46,0,116,0,115,0,65,172,18,11,1,28,0,65,184,18,11,9,2,0,0,0,2,0,0,0,48,0,65,204,18,11,1,92,0,65,216,18,11,79,2,0,0,0,72,0,0,0,48,0,49,0,50,0,51,0,52,0,53,0,54,0,55,0,56,0,57,0,97,0,98,0,99,0,100,0,101,0,102,0,103,0,104,0,105,0,106,0,107,0,108,0,109,0,110,0,111,0,112,0,113,0,114,0,115,0,116,0,117,0,118,0,119,0,120,0,121,0,122,0,65,172,19,11,1,92,0,65,184,19,11,79,2,0,0,0,72,0,0,0,115,0,101,0,116,0,86,0,49,0,50,0,56,0,58,0,32,0,101,0,120,0,112,0,101,0,99,0,116,0,32,0,105,0,32,0,102,0,114,0,111,0,109,0,32,0,48,0,32,0,116,0,111,0,32,0,54,0,51,0,44,0,32,0,103,0,111,0,116,0,32,0,65,140,20,11,1,28,0,65,152,20,11,1,2,0,65,172,20,11,1,60,0,65,184,20,11,51,2,0,0,0,44,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,117,0,116,0,105,0,108,0,115,0,47,0,118,0,49,0,50,0,56,0,46,0,116,0,115,0,65,236,20,11,1,92,0,65,248,20,11,79,2,0,0,0,72,0,0,0,103,0,101,0,116,0,86,0,49,0,50,0,56,0,58,0,32,0,101,0,120,0,112,0,101,0,99,0,116,0,32,0,105,0,32,0,102,0,114,0,111,0,109,0,32,0,48,0,32,0,116,0,111,0,32,0,54,0,51,0,44,0,32,0,103,0,111,0,116,0,32]);var S8={env:{abort:(r,e,t,n)=>{throw Error(`abort: ${r}:${e}:${t}:${n}`)}}};function Hb(r){return(r!==void 0?r:WebAssembly.validate($b))?new WebAssembly.Instance(new WebAssembly.Module($b),S8).exports:new WebAssembly.Instance(new WebAssembly.Module(E8),S8).exports}var Qe,zz,pa,iu,au,$z,I8,Hz;function qz(r){Qe=Hb(r),zz=!!Qe.HAS_SIMD.valueOf(),pa=Qe.input.value,iu=Qe.output.value,au=new Uint8Array(Qe.memory.buffer,pa,Qe.INPUT_LENGTH),$z=new Uint8Array(Qe.memory.buffer,iu,Qe.PARALLEL_FACTOR*32),I8=new Uint8Array(Qe.memory.buffer,iu,32),Hz=new Uint32Array(Qe.memory.buffer,pa,Qe.INPUT_LENGTH)}qz();function A8(r){return r.length===64?Vz(r):r.length<=Qe.INPUT_LENGTH?(au.set(r),Qe.digest(r.length),qb()):(Qe.init(),Gz(r),Wz())}function Vz(r){if(r.length===64)return au.set(r),Qe.digest64(pa,iu),qb();throw new Error("InvalidLengthForDigest64")}function Gz(r){let e=Qe.INPUT_LENGTH;if(r.length>e)for(let t=0;t<r.length;t+=e){let n=r.subarray(t,t+e);au.set(n),Qe.update(pa,n.length)}else au.set(r),Qe.update(pa,r.length)}function Wz(){return Qe.final(iu),qb()}function qb(){let r=v8(32);return r.set(I8),r}var _8=ne(T8(),1),Yz=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,P8=(0,_8.default)();var D8=P8&&!Yz;var t4e=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!P8,r4e=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,n4e=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+"_"+"ENV"]==="test",s4e=typeof navigator<"u"&&navigator.product==="ReactNative";function Xz(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Hp(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function qp(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function ct(r,e,t=""){let n=Xz(r),s=r?.length,o=e!==void 0;if(!n||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Vb(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function k8(r,e){ct(r,void 0,"output");let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function kn(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Ln(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Qz(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var Jz=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function L8(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function M8(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var Gb=(r,e)=>{function t(n,...s){if(ct(n,void 0,"key"),!Jz)throw new Error("Non little-endian hardware is not yet supported");if(r.nonceLength!==void 0){let u=s[0];ct(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let o=r.tagLength;o&&s[1]!==void 0&&ct(s[1],void 0,"AAD");let i=e(n,...s),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");ct(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ct(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(ct(u),o&&u.length<o)throw new Error('"ciphertext" expected length bigger than tagLength='+o);return a(i.decrypt.length,d),i.decrypt(u,d)}}}return Object.assign(t,r),t};function Wb(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!Zz(e))throw new Error("invalid output, must be aligned");return e}function O8(r,e,t){Hp(t);let n=new Uint8Array(16),s=Qz(n);return s.setBigUint64(0,BigInt(e),t),s.setBigUint64(8,BigInt(r),t),n}function Zz(r){return r.byteOffset%4===0}function ma(r){return Uint8Array.from(r)}var N8=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),e$=N8("expand 16-byte k"),t$=N8("expand 32-byte k"),r$=kn(e$),n$=kn(t$);function F(r,e){return r<<e|r>>>32-e}function jb(r){return r.byteOffset%4===0}var Vp=64,s$=16,B8=2**32-1,R8=Uint32Array.of();function o$(r,e,t,n,s,o,i,a){let c=s.length,l=new Uint8Array(Vp),u=kn(l),d=jb(s)&&jb(o),p=d?kn(s):R8,f=d?kn(o):R8;for(let h=0;h<c;i++){if(r(e,t,n,u,i,a),i>=B8)throw new Error("arx: counter overflow");let m=Math.min(Vp,c-h);if(d&&m===Vp){let g=h/4;if(h%4!==0)throw new Error("arx: invalid block position");for(let y=0,b;y<s$;y++)b=g+y,f[b]=p[b]^u[y];h+=Vp;continue}for(let g=0,y;g<m;g++)y=h+g,o[y]=s[y]^l[g];h+=m}}function Yb(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:s,counterRight:o,rounds:i}=L8({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return qp(s),qp(i),Hp(o),Hp(t),(a,c,l,u,d=0)=>{ct(a,void 0,"key"),ct(c,void 0,"nonce"),ct(l,void 0,"data");let p=l.length;if(u===void 0&&(u=new Uint8Array(p)),ct(u,void 0,"output"),qp(d),d<0||d>=B8)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);let f=[],h=a.length,m,g;if(h===32)f.push(m=ma(a)),g=n$;else if(h===16&&t)m=new Uint8Array(32),m.set(a),m.set(a,16),g=r$,f.push(m);else throw ct(a,32,"arx key"),new Error("invalid key size");jb(c)||f.push(c=ma(c));let y=kn(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(g,y,kn(c.subarray(0,16)),y),c=c.subarray(16)}let b=16-s;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let x=new Uint8Array(12);x.set(c,o?0:12-c.length),c=x,f.push(c)}let E=kn(c);return o$(r,g,y,E,l,u,d,i),Ln(...f),u}}function pt(r,e){return r[e++]&255|(r[e++]&255)<<8}var Xb=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){e=ma(ct(e,32,"key"));let t=pt(e,0),n=pt(e,2),s=pt(e,4),o=pt(e,6),i=pt(e,8),a=pt(e,10),c=pt(e,12),l=pt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|s<<6)&7939,this.r[3]=(s>>>7|o<<9)&8191,this.r[4]=(o>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=pt(e,16+2*u)}process(e,t,n=!1){let s=n?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],d=i[4],p=i[5],f=i[6],h=i[7],m=i[8],g=i[9],y=pt(e,t+0),b=pt(e,t+2),E=pt(e,t+4),x=pt(e,t+6),v=pt(e,t+8),S=pt(e,t+10),w=pt(e,t+12),I=pt(e,t+14),A=o[0]+(y&8191),G=o[1]+((y>>>13|b<<3)&8191),J=o[2]+((b>>>10|E<<6)&8191),$=o[3]+((E>>>7|x<<9)&8191),k=o[4]+((x>>>4|v<<12)&8191),_=o[5]+(v>>>1&8191),T=o[6]+((v>>>14|S<<2)&8191),L=o[7]+((S>>>11|w<<5)&8191),M=o[8]+((w>>>8|I<<8)&8191),O=o[9]+(I>>>5|s),D=0,R=D+A*a+G*(5*g)+J*(5*m)+$*(5*h)+k*(5*f);D=R>>>13,R&=8191,R+=_*(5*p)+T*(5*d)+L*(5*u)+M*(5*l)+O*(5*c),D+=R>>>13,R&=8191;let U=D+A*c+G*a+J*(5*g)+$*(5*m)+k*(5*h);D=U>>>13,U&=8191,U+=_*(5*f)+T*(5*p)+L*(5*d)+M*(5*u)+O*(5*l),D+=U>>>13,U&=8191;let K=D+A*l+G*c+J*a+$*(5*g)+k*(5*m);D=K>>>13,K&=8191,K+=_*(5*h)+T*(5*f)+L*(5*p)+M*(5*d)+O*(5*u),D+=K>>>13,K&=8191;let ye=D+A*u+G*l+J*c+$*a+k*(5*g);D=ye>>>13,ye&=8191,ye+=_*(5*m)+T*(5*h)+L*(5*f)+M*(5*p)+O*(5*d),D+=ye>>>13,ye&=8191;let ae=D+A*d+G*u+J*l+$*c+k*a;D=ae>>>13,ae&=8191,ae+=_*(5*g)+T*(5*m)+L*(5*h)+M*(5*f)+O*(5*p),D+=ae>>>13,ae&=8191;let te=D+A*p+G*d+J*u+$*l+k*c;D=te>>>13,te&=8191,te+=_*a+T*(5*g)+L*(5*m)+M*(5*h)+O*(5*f),D+=te>>>13,te&=8191;let ue=D+A*f+G*p+J*d+$*u+k*l;D=ue>>>13,ue&=8191,ue+=_*c+T*a+L*(5*g)+M*(5*m)+O*(5*h),D+=ue>>>13,ue&=8191;let Se=D+A*h+G*f+J*p+$*d+k*u;D=Se>>>13,Se&=8191,Se+=_*l+T*c+L*a+M*(5*g)+O*(5*m),D+=Se>>>13,Se&=8191;let He=D+A*m+G*h+J*f+$*p+k*d;D=He>>>13,He&=8191,He+=_*u+T*l+L*c+M*a+O*(5*g),D+=He>>>13,He&=8191;let pe=D+A*g+G*m+J*h+$*f+k*p;D=pe>>>13,pe&=8191,pe+=_*d+T*u+L*l+M*c+O*a,D+=pe>>>13,pe&=8191,D=(D<<2)+D|0,D=D+R|0,R=D&8191,D=D>>>13,U+=D,o[0]=R,o[1]=U,o[2]=K,o[3]=ye,o[4]=ae,o[5]=te,o[6]=ue,o[7]=Se,o[8]=He,o[9]=pe}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,n[0]=e[0]+5,s=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+s,s=n[a]>>>13,n[a]&=8191;n[9]-=8192;let o=(s^1)-1;for(let a=0;a<10;a++)n[a]&=o;o=~o;for(let a=0;a<10;a++)e[a]=e[a]&o|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;Ln(n)}update(e){Vb(this),ct(e),e=ma(e);let{buffer:t,blockLen:n}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);if(i===n){for(;n<=s-o;o+=n)this.process(e,o);continue}t.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Ln(this.h,this.r,this.buffer,this.pad)}digestInto(e){Vb(this),k8(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:s}=this;if(s){for(t[s++]=1;s<16;s++)t[s]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)e[o++]=n[i]>>>0,e[o++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function i$(r){let e=(n,s)=>r(s).update(n).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var U8=i$(r=>new Xb(r));function z8(r,e,t,n,s,o=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],d=e[1],p=e[2],f=e[3],h=e[4],m=e[5],g=e[6],y=e[7],b=s,E=t[0],x=t[1],v=t[2],S=i,w=a,I=c,A=l,G=u,J=d,$=p,k=f,_=h,T=m,L=g,M=y,O=b,D=E,R=x,U=v;for(let ye=0;ye<o;ye+=2)S=S+G|0,O=F(O^S,16),_=_+O|0,G=F(G^_,12),S=S+G|0,O=F(O^S,8),_=_+O|0,G=F(G^_,7),w=w+J|0,D=F(D^w,16),T=T+D|0,J=F(J^T,12),w=w+J|0,D=F(D^w,8),T=T+D|0,J=F(J^T,7),I=I+$|0,R=F(R^I,16),L=L+R|0,$=F($^L,12),I=I+$|0,R=F(R^I,8),L=L+R|0,$=F($^L,7),A=A+k|0,U=F(U^A,16),M=M+U|0,k=F(k^M,12),A=A+k|0,U=F(U^A,8),M=M+U|0,k=F(k^M,7),S=S+J|0,U=F(U^S,16),L=L+U|0,J=F(J^L,12),S=S+J|0,U=F(U^S,8),L=L+U|0,J=F(J^L,7),w=w+$|0,O=F(O^w,16),M=M+O|0,$=F($^M,12),w=w+$|0,O=F(O^w,8),M=M+O|0,$=F($^M,7),I=I+k|0,D=F(D^I,16),_=_+D|0,k=F(k^_,12),I=I+k|0,D=F(D^I,8),_=_+D|0,k=F(k^_,7),A=A+G|0,R=F(R^A,16),T=T+R|0,G=F(G^T,12),A=A+G|0,R=F(R^A,8),T=T+R|0,G=F(G^T,7);let K=0;n[K++]=i+S|0,n[K++]=a+w|0,n[K++]=c+I|0,n[K++]=l+A|0,n[K++]=u+G|0,n[K++]=d+J|0,n[K++]=p+$|0,n[K++]=f+k|0,n[K++]=h+_|0,n[K++]=m+T|0,n[K++]=g+L|0,n[K++]=y+M|0,n[K++]=b+O|0,n[K++]=E+D|0,n[K++]=x+R|0,n[K++]=v+U|0}function a$(r,e,t,n){let s=r[0],o=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],d=e[3],p=e[4],f=e[5],h=e[6],m=e[7],g=t[0],y=t[1],b=t[2],E=t[3];for(let v=0;v<20;v+=2)s=s+c|0,g=F(g^s,16),p=p+g|0,c=F(c^p,12),s=s+c|0,g=F(g^s,8),p=p+g|0,c=F(c^p,7),o=o+l|0,y=F(y^o,16),f=f+y|0,l=F(l^f,12),o=o+l|0,y=F(y^o,8),f=f+y|0,l=F(l^f,7),i=i+u|0,b=F(b^i,16),h=h+b|0,u=F(u^h,12),i=i+u|0,b=F(b^i,8),h=h+b|0,u=F(u^h,7),a=a+d|0,E=F(E^a,16),m=m+E|0,d=F(d^m,12),a=a+d|0,E=F(E^a,8),m=m+E|0,d=F(d^m,7),s=s+l|0,E=F(E^s,16),h=h+E|0,l=F(l^h,12),s=s+l|0,E=F(E^s,8),h=h+E|0,l=F(l^h,7),o=o+u|0,g=F(g^o,16),m=m+g|0,u=F(u^m,12),o=o+u|0,g=F(g^o,8),m=m+g|0,u=F(u^m,7),i=i+d|0,y=F(y^i,16),p=p+y|0,d=F(d^p,12),i=i+d|0,y=F(y^i,8),p=p+y|0,d=F(d^p,7),a=a+c|0,b=F(b^a,16),f=f+b|0,c=F(c^f,12),a=a+c|0,b=F(b^a,8),f=f+b|0,c=F(c^f,7);let x=0;n[x++]=s,n[x++]=o,n[x++]=i,n[x++]=a,n[x++]=g,n[x++]=y,n[x++]=b,n[x++]=E}var c$=Yb(z8,{counterRight:!1,counterLength:4,allowShortKeys:!1}),l$=Yb(z8,{counterRight:!1,counterLength:8,extendNonceFn:a$,allowShortKeys:!1});var u$=new Uint8Array(16),K8=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(u$.subarray(t))},h$=new Uint8Array(32);function F8(r,e,t,n,s){s!==void 0&&ct(s,void 0,"AAD");let o=r(e,t,h$),i=O8(n.length,s?s.length:0,!0),a=U8.create(o);s&&K8(a,s),K8(a,n),a.update(i);let c=a.digest();return Ln(o,i),c}var $8=r=>(e,t,n)=>({encrypt(o,i){let a=o.length;i=Wb(a+16,i,!1),i.set(o);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=F8(r,e,t,c,n);return i.set(l,a),Ln(l),i},decrypt(o,i){i=Wb(o.length-16,i,!1);let a=o.subarray(0,-16),c=o.subarray(-16),l=F8(r,e,t,a,n);if(!M8(c,l))throw new Error("invalid tag");return i.set(o.subarray(0,-16)),r(e,t,i,i,1),Ln(l),i}}),Qb=Gb({blockSize:64,nonceLength:12,tagLength:16},$8(c$)),x4e=Gb({blockSize:64,nonceLength:24,tagLength:16},$8(l$));var cu=BigInt(0),ga=BigInt(1),Gp=BigInt(2);function d$(r){return Rs(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function H8(r){let e=d$(r),{P:t,type:n,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||Nr,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),p=BigInt(a?121665:39081),f=a?Gp**BigInt(254):Gp**BigInt(447),h=a?BigInt(8)*Gp**BigInt(251)-ga:BigInt(4)*Gp**BigInt(445)-ga,m=f+h+ga,g=_=>Tt(_,t),y=b(d);function b(_){return wc(g(_),u)}function E(_){let T=Ih(de(_,u,"uCoordinate"));return a&&(T[31]&=127),g(Qo(T))}function x(_){return Qo(s(Ih(de(_,u,"scalar"))))}function v(_,T){let L=G(E(T),x(_));if(L===cu)throw new Error("invalid private or public key received");return b(L)}function S(_){return v(_,y)}let w=S,I=v;function A(_,T,L){let M=g(_*(T-L));return T=g(T-M),L=g(L+M),{x_2:T,x_3:L}}function G(_,T){xc("u",_,cu,t),xc("scalar",T,f,m);let L=T,M=_,O=ga,D=cu,R=_,U=ga,K=cu;for(let ae=BigInt(l-1);ae>=cu;ae--){let te=L>>ae&ga;K^=te,{x_2:O,x_3:R}=A(K,O,R),{x_2:D,x_3:U}=A(K,D,U),K=te;let ue=O+D,Se=g(ue*ue),He=O-D,pe=g(He*He),Ge=Se-pe,Do=R+U,Mu=R-U,za=g(Mu*ue),P6=g(Do*He),D6=za+P6,k6=za-P6;R=g(D6*D6),U=g(M*g(k6*k6)),O=g(Se*pe),D=g(Ge*(Se+g(p*Ge)))}({x_2:O,x_3:R}=A(K,O,R)),{x_2:D,x_3:U}=A(K,D,U);let ye=o(D);return g(O*ye)}let J={secretKey:u,publicKey:u,seed:u},$=(_=c(u))=>(de(_,J.seed,"seed"),_),k={randomSecretKey:$};return Object.freeze({keygen:Ch($,w),getSharedSecret:I,getPublicKey:w,scalarMult:v,scalarMultBase:S,utils:k,GuBytes:y.slice(),lengths:J})}var f$=BigInt(1),q8=BigInt(2),p$=BigInt(3),m$=BigInt(5),D4e=BigInt(8),V8=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function g$(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=V8,a=r*r%o*r%o,c=_e(a,q8,o)*a%o,l=_e(c,f$,o)*r%o,u=_e(l,m$,o)*l%o,d=_e(u,e,o)*u%o,p=_e(d,t,o)*d%o,f=_e(p,n,o)*p%o,h=_e(f,s,o)*f%o,m=_e(h,s,o)*f%o,g=_e(m,e,o)*u%o;return{pow_p_5_8:_e(g,q8,o)*r%o,b2:a}}function y$(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var lu=(()=>{let r=V8;return H8({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=g$(e);return Tt(_e(t,p$,r)*n,r)},adjustScalarBytes:y$})})();function W8(r,e,t){return Ls(r),t===void 0&&(t=new Uint8Array(r.outputLen)),ei(r,t,e)}var Jb=Uint8Array.of(0),G8=Uint8Array.of();function j8(r,e,t,n=32){Ls(r),ar(n,"length");let s=r.outputLen;if(n>255*s)throw new Error("Length must be <= 255*HashLen");let o=Math.ceil(n/s);t===void 0?t=G8:de(t,void 0,"info");let i=new Uint8Array(o*s),a=ei.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)Jb[0]=u+1,c.update(u===0?G8:l).update(t).update(Jb).digestInto(l),i.set(l,s*u),a._cloneInto(c);return a.destroy(),c.destroy(),pn(l,Jb),i.slice(0,n)}var Zb={hashSHA256(r){return Ut(r.subarray())},getHKDF(r,e){let t=W8(Ut,e,r),s=j8(Ut,t,void 0,96),o=s.subarray(0,32),i=s.subarray(32,64),a=s.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){let r=lu.utils.randomSecretKey();return{publicKey:lu.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:lu.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return lu.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return Qb(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,s){return Qb(n,e,t).decrypt(r.subarray(),s)}};var b$=(0,Yp.newInstance)(),Y8=new Yp.ChaCha20Poly1305(b$),X8="chacha20-poly1305",ya=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),uu=Buffer.from([48,42,48,5,6,3,43,101,110,3,33,0]);var ew={hashSHA256(r){let e=en.default.createHash("sha256");if(r instanceof Uint8Array)return e.update(r).digest();for(let t of r)e.update(t);return e.digest()},chaCha20Poly1305Encrypt(r,e,t,n){let s=en.default.createCipheriv(X8,n,e,{authTagLength:16});if(s.setAAD(t,{plaintextLength:r.byteLength}),r instanceof Uint8Array){let a=s.update(r),c=s.final(),l=s.getAuthTag();return Buffer.concat([a,c,l],a.byteLength+c.byteLength+l.byteLength)}let o=new B;for(let a of r)o.append(s.update(a));let i=s.final();return i.byteLength>0&&o.append(i),o.append(s.getAuthTag()),o},chaCha20Poly1305Decrypt(r,e,t,n,s){let o=r.subarray(r.length-16),i=en.default.createDecipheriv(X8,n,e,{authTagLength:16}),a;if(r instanceof Uint8Array?a=r.subarray(0,r.length-16):a=r.sublist(0,r.length-16),i.setAAD(t,{plaintextLength:a.byteLength}),i.setAuthTag(o),a instanceof Uint8Array){let u=i.update(a),d=i.final();return d.byteLength>0?Buffer.concat([u,d],u.byteLength+d.byteLength):u}let c=new B;for(let u of a)c.append(i.update(u));let l=i.final();return l.byteLength>0&&c.append(l),c}},Wp={hashSHA256(r){return A8(r.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return Y8.seal(n,e,r.subarray(),t)},chaCha20Poly1305Decrypt(r,e,t,n,s){let o=Y8.open(n,e,r.subarray(),t,s);if(!o)throw new Error("Invalid chacha20poly1305 decryption");return o}},jp={...Zb,hashSHA256(r){return ew.hashSHA256(r)},chaCha20Poly1305Encrypt(r,e,t,n){return r.byteLength<1200?Wp.chaCha20Poly1305Encrypt(r,e,t,n):ew.chaCha20Poly1305Encrypt(r,e,t,n)},chaCha20Poly1305Decrypt(r,e,t,n,s){return r.byteLength<1200?Wp.chaCha20Poly1305Decrypt(r,e,t,n,s):ew.chaCha20Poly1305Decrypt(r,e,t,n,s)},generateX25519KeyPair(){let{publicKey:r,privateKey:e}=en.default.generateKeyPairSync("x25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return{publicKey:r.subarray(uu.length),privateKey:e.subarray(ya.length)}},generateX25519KeyPairFromSeed(r){let e=en.default.createPrivateKey({key:Buffer.concat([ya,r],ya.byteLength+r.byteLength),type:"pkcs8",format:"der"});return{publicKey:en.default.createPublicKey(e).export({type:"spki",format:"der"}).subarray(uu.length),privateKey:r}},generateX25519SharedKey(r,e){return e instanceof Uint8Array?e=Buffer.concat([uu,e],uu.byteLength+e.byteLength):e=new B(uu,e).subarray(),r instanceof Uint8Array?r=Buffer.concat([ya,r],ya.byteLength+r.byteLength):r=new B(ya,r).subarray(),en.default.diffieHellman({publicKey:en.default.createPublicKey({key:Buffer.from(e.buffer,e.byteOffset,e.byteLength),type:"spki",format:"der"}),privateKey:en.default.createPrivateKey({key:Buffer.from(r.buffer,r.byteOffset,r.byteLength),type:"pkcs8",format:"der"})})}};D8&&(jp.chaCha20Poly1305Encrypt=Wp.chaCha20Poly1305Encrypt,jp.chaCha20Poly1305Decrypt=Wp.chaCha20Poly1305Decrypt);function Q8(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var ba=r=>{let e=We(2);return e[0]=r>>8,e[1]=r,e};ba.bytes=2;var wa=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};wa.bytes=2;function J8(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function tw(r,e){!e.enabled||!da||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${C(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${C(r.privateKey,"hex")}`)):e("Missing local static keys."))}function rw(r,e){!e.enabled||!da||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${C(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${C(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Z8(r,e){!e.enabled||!da||e(r?`REMOTE_STATIC_PUBLIC_KEY ${C(r.subarray(),"hex")}`:"Missing remote static public key.")}function nw(r,e){!e.enabled||!da||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${C(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function sw(r,e,t){!t.enabled||!da||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&C(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&C(e.k,"hex")}`))}var xa=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var w$=0,x$=4294967295,v$="Cipherstate has reached maximum n, a new handshake must be performed",Xp=class{n;bytes;view;constructor(e=w$){this.n=e,this.bytes=se(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>x$)throw new Error(v$)}};var Ao=se(0),va=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new Xp(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let s=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),s}},ow=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=P(t,"utf-8");this.h=E$(e,n),this.ck=this.h,this.cs=new va(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new va(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new B(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,Ao);return[new va(this.crypto,e),new va(this.crypto,t)]}},iw=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:s,initiator:o,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new ow(t,n),this.ss.mixHash(s),this.initiator=o,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let s=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(s),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},hu=class extends iw{writeMessageA(e){return new B(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new B(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new B(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new xa(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new xa(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new xa(`handshake stage 2 validation fail: ${t.message}`)}}};function E$(r,e){if(e.length<=32){let t=se(32);return t.set(e),t}else return r.hash(e)}var Qp;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let o of t.webtransportCerthashes)n.uint32(10),n.bytes(o);if(t.streamMuxers!=null)for(let o of t.streamMuxers)n.uint32(18),n.string(o);s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(s.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===s.limits.webtransportCerthashes)throw new Ie('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(t.bytes());break}case 2:{if(s.limits?.streamMuxers!=null&&o.streamMuxers.length===s.limits.streamMuxers)throw new Ie('Decode error - map field "streamMuxers" had too many elements');o.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(Qp||(Qp={}));var du;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),Qp.codec().encode(t.extensions,n)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={identityKey:se(0),identitySig:se(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.identityKey=t.bytes();break}case 2:{o.identitySig=t.bytes();break}case 4:{o.extensions=Qp.codec().decode(t,t.uint32(),{limits:s.limits?.extensions});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(du||(du={}));async function cw(r,e,t){let n=await r.sign(tC(e));return du.encode({identityKey:nt(r.publicKey),identitySig:n,extensions:t})}async function lw(r,e,t){try{let n=du.decode(r),s=Pt(n.identityKey);if(t?.equals(s)===!1)throw new Error(`Payload identity key ${s} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let o=tC(e);if(!await s.verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new qu(n.message)}}function tC(r){let e=P("noise-libp2p-static-key:");return r instanceof Uint8Array?be([e,r],e.length+r.length):(r.prepend(e),r)}var aw=class extends hs{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new ef({lengthDecoder:wa,maxBufferSize:16*1024*1024,encodingLength:()=>2});let s=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",s);let o=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",o);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new B;for(let n=0;n<e.byteLength;n+=65519){let s=n+65519;s>e.byteLength&&(s=e.byteLength);let o;e instanceof Uint8Array?o=this.handshake.encrypt(e.subarray(n,s)):o=this.handshake.encrypt(e.sublist(n,s)),this.metrics?.encryptedPackets.increment(),t.append(ba(o.byteLength)),t.append(o)}return t}decrypt(e){let t=new B;for(let n=0;n<e.byteLength;n+=65535){let s=n+65535;if(s>e.byteLength&&(s=e.byteLength),s-Nb<n)throw new Error("Invalid chunk");let o;e instanceof Uint8Array?o=e.subarray(n,s):o=e.sublist(n,s);let i=e.subarray(n,s-Nb);try{let a=this.handshake.decrypt(o,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function uw(r,e,t){return new aw(r,e,t)}async function rC(r,e){let{log:t,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await cw(o,a.publicKey,l),d=new hu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});tw(d.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA(Ao),e),t.trace("Stage 0 - Initiator finished sending first message."),rw(d.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let p=d.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),nw(d.re,t),Z8(d.rs,t),t.trace("Initiator going to check remote's signature...");let f=await lw(p,d.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[h,m]=d.ss.split();return sw(h,m,t),{payload:f,encrypt:g=>h.encryptWithAd(Ao,g),decrypt:(g,y)=>m.decryptWithAd(Ao,g,y)}}async function nC(r,e){let{log:t,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await cw(o,a.publicKey,l),d=new hu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});tw(d.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),nw(d.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),rw(d.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let p=d.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let f=await lw(p,d.rs,c),[h,m]=d.ss.split();return sw(h,m,t),{payload:f,encrypt:g=>m.encryptWithAd(Ao,g),decrypt:(g,y)=>h.decryptWithAd(Ao,g,y)}}var Jp=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:s,crypto:o,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=o??jp;this.crypto=Q8(c),this.extensions={webtransportCerthashes:[],...s},this.metrics=a?J8(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??se(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[je]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,s=ds(e,{lengthEncoder:ba,lengthDecoder:wa,maxDataLength:65535}),o=await this.performHandshakeInitiator(s,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Pt(o.payload.identityKey);return{connection:uw(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:Zn(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let s=t.get(n);if(s!=null)return s}if(e.length)throw new Vu("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,s=ds(e,{lengthEncoder:ba,lengthDecoder:wa,maxDataLength:65535}),o=await this.performHandshakeResponder(s,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=Pt(o.payload.identityKey);return{connection:uw(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:Zn(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await rC({connection:e,privateKey:t,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,s,o){let i,a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await nC({connection:e,privateKey:t,remoteIdentityKey:s,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function sC(r={}){return e=>new Jp(e,r)}function S$(r){return r.reason}async function hw(r,e,t){if(e==null)return r;let n=t?.translateError??S$;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var Le;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Le||(Le={}));var ge;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(ge||(ge={}));var tEe=Object.values(ge).filter(r=>typeof r!="string"),oC=0,Je;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(Je||(Je={}));var tn=12;var Mn=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function iC(r){return r?.reason!==null}var rr=class extends Mn{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Je.ProtocolError),this.name="InvalidFrameError"}},Ea=class extends Mn{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Je.ProtocolError),this.name="UnRequestedPingError"}},Sa=class extends Mn{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Je.ProtocolError),this.name="NotMatchingPingError"}};var Zp=class extends Mn{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,Je.ProtocolError),this.name="StreamAlreadyExistsError"}},e1=class extends Mn{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,Je.ProtocolError),this.name="DecodeInvalidVersionError"}},t1=class extends Mn{static name="BothClientsError";constructor(e="Both clients"){super(e,Je.ProtocolError),this.name="BothClientsError"}},Ia=class extends Mn{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Je.ProtocolError),this.name="ReceiveWindowExceededError"}};var iEe=new Set([rr.name,Ea.name,Sa.name,Zp.name,e1.name,t1.name,Ia.name]),pu=256*1024,r1=16*1024*1024;var mu={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:pu,maxStreamWindowSize:r1,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function aC(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new N("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new N("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new N("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new N("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<pu)throw new N("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new N("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new N("MaxStreamWindowSize must be less than equal MAX_UINT32")}function lC(r){return r.header.type===Le.Data&&r.data!==null}var cC=2**24;function I$(r){if(r[0]!==oC)throw new rr("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*cC+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*cC+(r[9]<<16)+(r[10]<<8)+r[11]}}var n1=class{buffer;constructor(){this.buffer=new B}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=tn;if(this.buffer.byteLength<tn)return;let t=I$(this.buffer.subarray(0,tn));if(t.type===Le.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(tn,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function dw(r){let e=new Uint8Array(tn);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var Lt;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(Lt||(Lt={}));var s1=class extends Qd{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??pu;super({...e,maxMessageSize:t-tn}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??r1,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=Lt.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,s=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){s=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let o=Math.min(this.sendWindowCapacity,e.byteLength),i=this.getSendFlags(),a=e.sublist(0,o);e.consume(o);let c=this.sendFrame({type:Le.Data,flag:i,streamID:this.streamId,length:o},a);if(this.sendWindowCapacity-=o,n+=o,!c){s=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:s}}sendReset(){this.sendFrame({type:Le.WindowUpdate,flag:ge.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|ge.FIN;this.sendFrame({type:Le.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=Lt.Paused}sendResume(){this.state=Lt.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-tn,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!lC(e))throw new rr("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new Ia("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&ge.ACK)===ge.ACK&&this.state===Lt.SYNSent&&(this.state=Lt.Established),(e&ge.FIN)===ge.FIN&&this.onRemoteCloseWrite(),(e&ge.RST)===ge.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case Lt.Init:return this.state=Lt.SYNSent,ge.SYN;case Lt.SYNReceived:return this.state=Lt.Established,ge.ACK;default:return 0}}sendWindowUpdate(){if(this.state===Lt.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let s=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Le.WindowUpdate,flag:e,streamID:this.streamId,length:s})}};function uC(r){return{type:Le[r.type],flags:[(r.flag&ge.SYN)===ge.SYN?"SYN":void 0,(r.flag&ge.ACK)===ge.ACK?"ACK":void 0,(r.flag&ge.FIN)===ge.FIN?"FIN":void 0,(r.flag&ge.RST)===ge.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var hC="/yamux/1.0.0",o1=class{protocol=hC;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[je]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new fw(e,{...this._init})}},fw=class extends Xd{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:hC,name:"yamux"}),this.client=e.direction==="outbound",aC(t),this.enableKeepAlive=t.enableKeepAlive??mu.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??mu.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??mu.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??mu.maxOutboundStreams,this.decoder=new n1,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=qS(async n=>{try{await this.ping(n)}catch(s){this.log.error("ping error: %s",s)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new hn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new hn("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Ro("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,Lt.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new hn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new hn("Muxer closed locally");if(this.activePing!=null)return hw(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await hw(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??Je.NormalTermination;this.log.trace("muxer close reason=%s",Je[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=Je.InternalError;iC(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(o=>o.streamId===e)!=null)throw new N("Stream already exists with that id");let s=new s1({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return s.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),s}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:s}=e.header;if(this.log.trace("received frame %o",uC(e.header)),t===0)switch(n){case Le.Ping:{this.handlePing(e.header);return}case Le.GoAway:{this.handleGoAway(s);return}default:throw new rr("Invalid frame type")}else switch(e.header.type){case Le.Data:case Le.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new rr("Invalid frame type")}}handlePing(e){if(e.flag===ge.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,ge.ACK);else if(e.flag===ge.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new rr("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new Ea("ping not requested");if(this.activePing.id!==e)throw new Sa("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Je[e]??"unknown"),this.remoteGoAway=e,e===Je.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:s}=e.header;(n&ge.SYN)===ge.SYN&&this.incomingStream(t);let o=this.streams.find(i=>i.streamId===t);if(o===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(s){case Le.WindowUpdate:{o.handleWindowUpdate(e);return}case Le.Data:{o.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new N("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Le.WindowUpdate,flag:ge.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Le.WindowUpdate,flag:ge.RST,streamID:e,length:0});return}let t=this._newStream(e,Lt.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Le.Data){if(t==null)throw new rr("Invalid frame");n=new B(dw(e),t)}else n=dw(e);return this.log.trace("sending frame %o",uC(e)),this.send(n)}sendPing(e,t=ge.SYN){t===ge.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:Le.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Je.NormalTermination){this.log("sending GoAway reason=%s",Je[e]),this.localGoAway=e,this.sendFrame({type:Le.GoAway,flag:0,streamID:0,length:e})}};function dC(r={}){return()=>new o1(r)}var fC="0.1.0";var pC="1.0.0";var gu;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)n.uint32(18),n.bytes(o);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)n.uint32(26),n.string(o);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={listenAddrs:[],protocols:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 5:{o.protocolVersion=t.string();break}case 6:{o.agentVersion=t.string();break}case 1:{o.publicKey=t.bytes();break}case 2:{if(s.limits?.listenAddrs!=null&&o.listenAddrs.length===s.limits.listenAddrs)throw new Ie('Decode error - map field "listenAddrs" had too many elements');o.listenAddrs.push(t.bytes());break}case 4:{o.observedAddr=t.bytes();break}case 3:{if(s.limits?.protocols!=null&&o.protocols.length===s.limits.protocols)throw new Ie('Decode error - map field "protocols" had too many elements');o.protocols.push(t.string());break}case 8:{o.signedPeerRecord=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(gu||(gu={}));var rn={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function mC(r){if(r!=null&&r.length>0)try{return H(r)}catch{}}async function gC(r,e,t,n,s){if(t("received identify from %p",n.remotePeer),s==null)throw new At("message was null or undefined");let o={};if(s.listenAddrs.length>0&&(o.addresses=s.listenAddrs.map(c=>({isCertified:!1,multiaddr:H(c)}))),s.protocols.length>0&&(o.protocols=s.protocols),s.publicKey!=null){let c=Pt(s.publicKey);if(!Zn(c).equals(n.remotePeer))throw new At("public key did not match remote PeerId");o.publicKey=c}let i;if(s.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",n.remotePeer);let c=s.signedPeerRecord,l=await Jt.openAndCertify(c,Zt.DOMAIN),u=Zt.createFromProtobuf(l.payload),d=yn(l.publicKey.toCID());if(!u.peerId.equals(d))throw new At("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(u.peerId))throw new At("signing key does not match remote PeerId");let p;try{p=await r.get(u.peerId)}catch(f){if(f.name!=="NotFoundError")throw f}if(p!=null&&(o.metadata=p.metadata,p.peerRecordEnvelope!=null)){let f=Jt.createFromProtobuf(p.peerRecordEnvelope),h=Zt.createFromProtobuf(f.payload);h.seqNumber>=u.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",h.seqNumber,u.seqNumber),u=h,c=p.peerRecordEnvelope)}o.peerRecordEnvelope=c,o.addresses=u.multiaddrs.map(f=>({isCertified:!0,multiaddr:f})),i={seq:u.seqNumber,addresses:u.multiaddrs}}else t("%p did not send a signed peer record",n.remotePeer);if(t.trace("patching %p with",n.remotePeer,o),await r.patch(n.remotePeer,o),s.agentVersion!=null||s.protocolVersion!=null){let c={};s.agentVersion!=null&&(c.AgentVersion=P(s.agentVersion)),s.protocolVersion!=null&&(c.ProtocolVersion=P(s.protocolVersion)),t.trace("merging %p metadata",n.remotePeer,c),await r.merge(n.remotePeer,{metadata:c})}let a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map(c=>H(c)),observedAddr:s.observedAddr==null?void 0:H(s.observedAddr),protocols:s.protocols,signedPeerRecord:i,connection:n};return e.safeDispatchEvent("peer:identify",{detail:a}),a}var i1=class{host;components;protocol;started;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.components=e,this.log=t.log,this.timeout=t.timeout??rn.timeout,this.maxInboundStreams=t.maxInboundStreams??rn.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??rn.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??rn.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??rn.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??rn.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??rn.protocolPrefix}/${fC}`,agentVersion:e.nodeInfo.userAgent},this.handleProtocol=this.handleProtocol.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.merge(this.components.peerId,{metadata:{AgentVersion:P(this.host.agentVersion),ProtocolVersion:P(this.host.protocolVersion)}}),await this.components.registrar.handle(this.protocol,this.handleProtocol,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}};var a1=class extends i1{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??rn.protocolPrefix}/${"id"}/${pC}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??rn.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let s=n.detail;this.identify(s).catch(()=>{})})}[je]=["@libp2p/identify"];async _identify(e,t={}){let n,s;if(t.signal==null){let o=AbortSignal.timeout(this.timeout);W(1/0,o),t={...t,signal:o}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),s=n.log.newScope("identify");let o=Cr(n,{maxDataLength:this.maxMessageSize}).pb(gu),i=await o.read(t);return await o.unwrap().unwrap().close(t),i}catch(o){throw s?.error("identify failed - %e",o),n?.abort(o),o}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:s,protocols:o,observedAddr:i}=n;if(s==null)throw new At("Public key was missing from identify message");let a=Pt(s),c=yn(a.toCID());if(!e.remotePeer.equals(c))throw new At("Identified peer does not match the expected peer");if(this.components.peerId.equals(c))throw new At("Identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("completed for peer %p and protocols %o",c,o),gC(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){let t=mC(e);if(t==null||(this.log.trace("our observed address was %a",t),In(t)))return;let n=t.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!LS(t)){this.log.trace("our observed address was IPv6 but not a global unicast address");return}Sn.exactMatch(t)||(this.log.trace("storing the observed address"),this.components.addressManager.addObservedAddr(t))}async handleProtocol(e,t){let n=e.log.newScope("identify");n("responding to identify");let s=AbortSignal.timeout(this.timeout);W(1/0,s);let o=await this.components.peerStore.get(this.components.peerId,{signal:s}),i=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),a=o.peerRecordEnvelope;if(i.length>0&&a==null){let u=new Zt({peerId:this.components.peerId,multiaddrs:i});a=(await Jt.seal(u,this.components.privateKey,{signal:s})).marshal().subarray()}let c=t.remoteAddr.bytes;SS.matches(t.remoteAddr)||(c=void 0);let l=Cr(e).pb(gu);n("send response"),await l.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:nt(this.components.privateKey.publicKey),listenAddrs:i.map(u=>u.bytes),signedPeerRecord:a,observedAddr:c,protocols:o.protocols},{signal:s}),n("close write"),await l.unwrap().unwrap().close({signal:s})}};function yC(r={}){return e=>new a1(e,r)}function _$(r){return r.reason}async function bC(r,e,t){if(e==null)return r;let n=t?.translateError??_$;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var wC="1.0.0",xC="ping",vC="ipfs";var c1=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??vC}/${xC}/${wC}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[je]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handlePing,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async handlePing(e,t){let n=e.log.newScope("ping");n.trace("ping from %p",t.remotePeer);let s=AbortSignal.timeout(this.timeout);W(1/0,s),s.addEventListener("abort",()=>{e.abort(new kr("Ping timed out"))});let o=Date.now();for await(let i of e){if(e.status!=="open"){n("stream status changed to %s",e.status);break}e.send(i)||(n("waiting for stream to drain"),await De(e,"drain",{rejectionEvents:["close"],signal:s}),n("stream drained"))}n("ping from %p complete in %dms",t.remotePeer,Date.now()-o),await e.close({signal:s})}async ping(e,t={}){let n=Xn(32),s=await this.components.connectionManager.openStream(e,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...t}),o=s.log.newScope("ping");try{let i=Date.now(),a=Promise.withResolvers(),c=new B,l=u=>{if(c.append(u.data),c.byteLength===32){s.removeEventListener("message",l);let d=Date.now()-i;Promise.all([s.closeRead(t)]).then(()=>{if(V(n,c.subarray()))a.resolve(d);else throw new Xu(`Received wrong ping ack after ${d}ms`)}).catch(p=>{s.abort(p),a.reject(p)})}};return s.addEventListener("message",l),s.send(n),await s.close(t),await bC(a.promise,t.signal)}catch(i){throw o.error("error while pinging %o - %e",e,i),s?.abort(i),i}finally{s?.close()}}};function SC(r={}){return e=>new c1(e,r)}var pw=Symbol.for("@libp2p/peer-id");var Co="StrictSign",Aa="StrictNoSign",Mt;(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(Mt||(Mt={}));var SSe=Symbol.for("@libp2p/pubsub");var l1=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var u1=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},h1=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var IC=Symbol.for("@libp2p/service-capabilities"),AC=Symbol.for("@libp2p/service-dependencies");var Ze=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ca=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var yu=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ww={};z(ww,{base58btc:()=>$e,base58flickr:()=>U$});var jSe=new Uint8Array(0);function CC(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function mr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function TC(r){return new TextEncoder().encode(r)}function _C(r){return new TextDecoder().decode(r)}function L$(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,g=0,y=0,b=h.length;y!==b&&h[y]===0;)y++,m++;for(var E=(b-y)*u+1>>>0,x=new Uint8Array(E);y!==b;){for(var v=h[y],S=0,w=E-1;(v!==0||S<g)&&w!==-1;w--,S++)v+=256*x[w]>>>0,x[w]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,y++}for(var I=E-g;I!==E&&x[I]===0;)I++;for(var A=c.repeat(m);I<E;++I)A+=r.charAt(x[I]);return A}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var g=0,y=0;h[m]===c;)g++,m++;for(var b=(h.length-m)*l+1>>>0,E=new Uint8Array(b);h[m];){var x=t[h.charCodeAt(m)];if(x===255)return;for(var v=0,S=b-1;(x!==0||v<y)&&S!==-1;S--,v++)x+=a*E[S]>>>0,E[S]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=v,m++}if(h[m]!==" "){for(var w=b-y;w!==b&&E[w]===0;)w++;for(var I=new Uint8Array(g+(b-w)),A=g;w!==b;)I[A++]=E[w++];return I}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var M$=L$,O$=M$,DC=O$;var mw=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},gw=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 kC(this,e)}},yw=class{decoders;constructor(e){this.decoders=e}or(e){return kC(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function kC(r,e){return new yw({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var bw=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new mw(e,t,n),this.decoder=new gw(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ta({name:r,prefix:e,encode:t,decode:n}){return new bw(r,e,t,n)}function ys({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=DC(t,r);return Ta({prefix:e,name:r,encode:n,decode:o=>mr(s(o))})}function R$(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function N$(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function B$(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ze({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=B$(n);return Ta({prefix:e,name:r,encode(o){return N$(o,n,t)},decode(o){return R$(o,s,t,r)}})}var $e=ys({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),U$=ys({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xw={};z(xw,{base32:()=>bs,base32hex:()=>$$,base32hexpad:()=>q$,base32hexpadupper:()=>V$,base32hexupper:()=>H$,base32pad:()=>F$,base32padupper:()=>z$,base32upper:()=>K$,base32z:()=>G$});var bs=ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),K$=ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),F$=ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),z$=ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$$=ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),H$=ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),q$=ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),V$=ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),G$=ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var vw={};z(vw,{base36:()=>bu,base36upper:()=>W$});var bu=ys({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),W$=ys({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var j$=OC,LC=128,Y$=127,X$=~Y$,Q$=Math.pow(2,31);function OC(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Q$;)e[t++]=r&255|LC,r/=128;for(;r&X$;)e[t++]=r&255|LC,r>>>=7;return e[t]=r|0,OC.bytes=t-n+1,e}var J$=Ew,Z$=128,MC=127;function Ew(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ew.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&MC)<<s:(i&MC)*Math.pow(2,s),s+=7}while(i>=Z$);return Ew.bytes=o-n,t}var eH=Math.pow(2,7),tH=Math.pow(2,14),rH=Math.pow(2,21),nH=Math.pow(2,28),sH=Math.pow(2,35),oH=Math.pow(2,42),iH=Math.pow(2,49),aH=Math.pow(2,56),cH=Math.pow(2,63),lH=function(r){return r<eH?1:r<tH?2:r<rH?3:r<nH?4:r<sH?5:r<oH?6:r<iH?7:r<aH?8:r<cH?9:10},uH={encode:j$,decode:J$,encodingLength:lH},hH=uH,wu=hH;function xu(r,e=0){return[wu.decode(r,e),wu.decode.bytes]}function _a(r,e,t=0){return wu.encode(r,e,t),e}function Pa(r){return wu.encodingLength(r)}function nn(r,e){let t=e.byteLength,n=Pa(r),s=n+Pa(t),o=new Uint8Array(s+t);return _a(r,o,0),_a(t,o,n),o.set(e,s),new Da(r,t,e,o)}function On(r){let e=mr(r),[t,n]=xu(e),[s,o]=xu(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Da(t,s,i,e)}function RC(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&CC(r.bytes,t.bytes)}}var Da=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function NC(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return fH(t,Sw(r),e??$e.encoder);default:return pH(t,Sw(r),e??bs.encoder)}}var BC=new WeakMap;function Sw(r){let e=BC.get(r);if(e==null){let t=new Map;return BC.set(r,t),t}return e}var et=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==vu)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==mH)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=nn(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&RC(e.multihash,n.multihash)}toString(e){return NC(this,e)}toJSON(){return{"/":NC(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??UC(n,s,o.bytes))}else if(t[gH]===!0){let{version:n,multihash:s,code:o}=t,i=On(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==vu)throw new Error(`Version 0 CID must use dag-pb (code: ${vu}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=UC(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,vu,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=mr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Da(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,p]=xu(e.subarray(t));return t+=p,d},s=n(),o=vu;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=dH(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Sw(o).set(n,e),o}};function dH(r,e){switch(r[0]){case"Q":{let t=e??$e;return[$e.prefix,t.decode(`${$e.prefix}${r}`)]}case $e.prefix:{let t=e??$e;return[$e.prefix,t.decode(r)]}case bs.prefix:{let t=e??bs;return[bs.prefix,t.decode(r)]}case bu.prefix:{let t=e??bu;return[bu.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function fH(r,e,t){let{prefix:n}=t;if(n!==$e.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function pH(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var vu=112,mH=18;function UC(r,e,t){let n=Pa(r),s=n+Pa(e),o=new Uint8Array(s+t.byteLength);return _a(r,o,0),_a(e,o,n),o.set(t,s),o}var gH=Symbol.for("@ipld/js-cid/CID");var Iw={};z(Iw,{identity:()=>Tr});var KC=0,yH="identity",FC=mr;function bH(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return nn(KC,FC(r))}var Tr={code:KC,name:yH,encode:FC,digest:bH};var wH=parseInt("11111",2),Aw=parseInt("10000000",2),xH=parseInt("01111111",2),zC={0:Eu,1:Eu,2:vH,3:IH,4:AH,5:SH,6:EH,16:Eu,22:Eu,48:Eu};function Rn(r,e={offset:0}){let t=r[e.offset]&wH;if(e.offset++,zC[t]!=null)return zC[t](r,e);throw new Error("No decoder for tag "+t)}function Su(r,e){let t=0;if((r[e.offset]&Aw)===Aw){let n=r[e.offset]&xH,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Eu(r,e){Su(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Rn(r,e);if(n===null)break;t.push(n)}return t}function vH(r,e){let t=Su(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function EH(r,e){let t=Su(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function SH(r,e){return e.offset++,null}function IH(r,e){let t=Su(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function AH(r,e){let t=Su(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function CH(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new B;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Cw(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=CH(r.byteLength);return new B(Uint8Array.from([e.byteLength|Aw]),e)}function qt(r){let e=new B,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new B(Uint8Array.from([2]),Cw(e),e)}function f1(r){let e=Uint8Array.from([0]),t=new B(e,r);return new B(Uint8Array.from([3]),Cw(t),t)}function xs(r,e=48){let t=new B;for(let n of r)t.append(n);return new B(Uint8Array.from([e]),Cw(t),t)}async function $C(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,t.subarray());return n?.signal?.throwIfAborted(),o}var TH=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),_H=Uint8Array.from([6,5,43,129,4,0,34]),PH=Uint8Array.from([6,5,43,129,4,0,35]),DH={ext:!0,kty:"EC",crv:"P-256"},kH={ext:!0,kty:"EC",crv:"P-384"},LH={ext:!0,kty:"EC",crv:"P-521"},Tw=32,_w=48,Pw=66;function Dw(r){let e=Rn(r);return HC(e)}function HC(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===Tw*2+1)return n=C(e.subarray(t,t+Tw),"base64url"),s=C(e.subarray(t+Tw),"base64url"),new ka({...DH,key_ops:["verify"],x:n,y:s});if(e.byteLength===_w*2+1)return n=C(e.subarray(t,t+_w),"base64url"),s=C(e.subarray(t+_w),"base64url"),new ka({...kH,key_ops:["verify"],x:n,y:s});if(e.byteLength===Pw*2+1)return n=C(e.subarray(t,t+Pw),"base64url"),s=C(e.subarray(t+Pw),"base64url"),new ka({...LH,key_ops:["verify"],x:n,y:s});throw new Ze(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function qC(r){return xs([qt(Uint8Array.from([1])),xs([MH(r.crv)],160),xs([f1(new B(Uint8Array.from([4]),P(r.x??"","base64url"),P(r.y??"","base64url")))],161)]).subarray()}function MH(r){if(r==="P-256")return TH;if(r==="P-384")return _H;if(r==="P-521")return PH;throw new Ze(`Invalid curve ${r}`)}var ka=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=qC(this.jwk)),this._raw}toMultihash(){return Tr.digest(vs(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return $e.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}async verify(e,t,n){return $C(this.jwk,t,e,n)}};var p1=ne(Z("crypto"),1);var BIe=p1.default.generateKeyPairSync,Iu=32;var OH=64;function VC(r,e,t){if(r.byteLength!==Iu)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==OH)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=p1.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:C(r,"base64url"),kty:"OKP"}});return p1.default.verify(null,t instanceof Uint8Array?t:t.subarray(),n,e)}function WC(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var m1=class{type="Ed25519";raw;constructor(e){this.raw=kw(e,Iu)}toMultihash(){return Tr.digest(vs(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return $e.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=VC(this.raw,t,e);return WC(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}};function Lw(r){return r=kw(r,Iu),new m1(r)}function kw(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Ze(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Ve;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ve||(Ve={}));var Mw;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Mw||(Mw={}));(function(r){r.codec=()=>Wt(Mw)})(Ve||(Ve={}));var sn;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ve.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Ve.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(sn||(sn={}));var Ow;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ve.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=Ve.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(Ow||(Ow={}));var y1=ne(Z("node:crypto"),1),rT=Z("node:util");function g1(r){if(isNaN(r)||r<=0)throw new Ze("random bytes length must be a Number bigger than 0");return Nr(r)}var Cu={};z(Cu,{MAX_RSA_KEY_SIZE:()=>Rw,generateRSAKeyPair:()=>JC,jwkToJWKKeyPair:()=>ZC,jwkToPkcs1:()=>KH,jwkToPkix:()=>Kw,jwkToRSAPrivateKey:()=>Hw,pkcs1MessageToJwk:()=>Bw,pkcs1MessageToRSAPrivateKey:()=>Fw,pkcs1ToJwk:()=>UH,pkcs1ToRSAPrivateKey:()=>QC,pkixMessageToJwk:()=>Uw,pkixMessageToRSAPublicKey:()=>$w,pkixToJwk:()=>FH,pkixToRSAPublicKey:()=>zw});var La=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Cu.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return et.createV1(114,this._multihash)}toString(){return $e.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}verify(e,t,n){return XC(this.jwk,t,e,n)}},Au=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Cu.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}sign(e,t){return YC(this.jwk,e,t)}};var Rw=8192,Nw=18,NH=1062,BH=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function UH(r){let e=Rn(r);return Bw(e)}function Bw(r){return{n:C(r[1],"base64url"),e:C(r[2],"base64url"),d:C(r[3],"base64url"),p:C(r[4],"base64url"),q:C(r[5],"base64url"),dp:C(r[6],"base64url"),dq:C(r[7],"base64url"),qi:C(r[8],"base64url"),kty:"RSA"}}function KH(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new Ze("JWK was missing components");return xs([qt(Uint8Array.from([0])),qt(P(r.n,"base64url")),qt(P(r.e,"base64url")),qt(P(r.d,"base64url")),qt(P(r.p,"base64url")),qt(P(r.q,"base64url")),qt(P(r.dp,"base64url")),qt(P(r.dq,"base64url")),qt(P(r.qi,"base64url"))]).subarray()}function FH(r){let e=Rn(r,{offset:0});return Uw(e)}function Uw(r){let e=Rn(r[1],{offset:0});return{kty:"RSA",n:C(e[0],"base64url"),e:C(e[1],"base64url")}}function Kw(r){if(r.n==null||r.e==null)throw new Ze("JWK was missing components");return xs([BH,f1(xs([qt(P(r.n,"base64url")),qt(P(r.e,"base64url"))]))]).subarray()}function QC(r){let e=Rn(r);return Fw(e)}function Fw(r){let e=Bw(r);return Hw(e)}function zw(r,e){if(r.byteLength>=NH)throw new Ca("Key size is too large");let t=Rn(r,{offset:0});return $w(t,r,e)}function $w(r,e,t){let n=Uw(r);if(t==null){let s=Ut(sn.encode({Type:Ve.RSA,Data:e}));t=nn(Nw,s)}return new La(n,t)}function Hw(r){if(tT(r)>Rw)throw new Ze("Key size is too large");let e=ZC(r),t=Ut(sn.encode({Type:Ve.RSA,Data:Kw(e.publicKey)})),n=nn(Nw,t);return new Au(e.privateKey,new La(e.publicKey,n))}async function JC(r){if(r>Rw)throw new Ze("Key size is too large");let e=await eT(r),t=Ut(sn.encode({Type:Ve.RSA,Data:Kw(e.publicKey)})),n=nn(Nw,t);return new Au(e.privateKey,new La(e.publicKey,n))}function ZC(r){if(r==null)throw new Ze("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var zH=(0,rT.promisify)(y1.default.generateKeyPair);async function eT(r,e){let t=await zH("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function YC(r,e,t){t?.signal?.throwIfAborted();let n=y1.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)n.update(e);else for(let s of e)n.update(s);return n.sign({format:"jwk",key:r})}function XC(r,e,t,n){n?.signal?.throwIfAborted();let s=y1.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)s.update(t);else for(let o of t)s.update(o);return s.verify({format:"jwk",key:r},e)}function tT(r){if(r.kty!=="RSA")throw new Ze("Invalid key type");if(r.n==null)throw new Ze("Invalid key modulus");return P(r.n,"base64url").length*8}var nT=ne(Z("node:crypto"),1);var b1=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function sT(r,e,t,n){n?.signal?.throwIfAborted();let s=nT.default.createHash("sha256");if(t instanceof Uint8Array)s.update(t);else for(let i of t)s.update(i);let o=s.digest();try{return Ye.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new b1(String(i))}}var w1=class{type="secp256k1";raw;_key;constructor(e){this._key=iT(e),this.raw=oT(this._key)}toMultihash(){return Tr.digest(vs(this))}toCID(){return et.createV1(114,this.toMultihash())}toString(){return $e.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:V(this.raw,e.raw)}verify(e,t,n){return sT(this._key,t,e,n)}};function qw(r){return new w1(r)}function oT(r){return Ye.Point.fromBytes(r).toBytes()}function iT(r){try{return Ye.Point.fromBytes(r),r}catch(e){throw new Ca(String(e))}}function Vw(r,e){let{Type:t,Data:n}=sn.decode(r),s=n??new Uint8Array;switch(t){case Ve.RSA:return zw(s,e);case Ve.Ed25519:return Lw(s);case Ve.secp256k1:return qw(s);case Ve.ECDSA:return Dw(s);default:throw new yu}}function aT(r){let{Type:e,Data:t}=sn.decode(r.digest),n=t??new Uint8Array;switch(e){case Ve.Ed25519:return Lw(n);case Ve.secp256k1:return qw(n);case Ve.ECDSA:return Dw(n);default:throw new yu}}function vs(r){return sn.encode({Type:Ve[r.type],Data:r.raw})}var Yw={};z(Yw,{sha256:()=>Tu,sha512:()=>HH});var jw=ne(Z("crypto"),1);var $H=20;function Ww({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Gw(r,e,t,n,s)}var Gw=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??$H,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?cT(n,this.code,t?.truncate):n.then(s=>cT(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function cT(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return nn(e,r)}var Tu=Ww({name:"sha2-256",code:18,encode:r=>mr(jw.default.createHash("sha256").update(r).digest())}),HH=Ww({name:"sha2-512",code:19,encode:r=>mr(jw.default.createHash("sha512").update(r).digest())});var uT=Symbol.for("nodejs.util.inspect.custom"),qH=114,_u=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[pw]=!0;toString(){return this.string==null&&(this.string=$e.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return et.createV1(qH,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return V(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return V(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[uT](){return`PeerId(${this.toString()})`}},x1=class extends _u{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},v1=class extends _u{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},E1=class extends _u{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},VH=2336,Pu=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Tr.digest(P(this.url))}[uT](){return`PeerId(${this.url})`}[pw]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return et.createV1(VH,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=C(e)),e.toString()===this.toString())}};var GH=114,hT=2336;function To(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=On($e.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return WH(et.parse(r));if(e==null)throw new l1('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=On(e.decode(r))}return Ma(t)}function Ma(r){if(YH(r))return new x1({multihash:r});if(jH(r))try{let e=aT(r);if(e.type==="Ed25519")return new v1({multihash:r,publicKey:e});if(e.type==="secp256k1")return new E1({multihash:r,publicKey:e})}catch{let t=C(r.digest);return new Pu(new URL(t))}throw new h1("Supplied PeerID Multihash is invalid")}function WH(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==GH&&r.code!==hT)throw new u1("Supplied PeerID CID is invalid");if(r.code===hT){let e=C(r.multihash.digest);return new Pu(new URL(e))}return Ma(r.multihash)}function jH(r){return r.code===Tr.code}function YH(r){return r.code===Tu.code}function S1(r){return r[Symbol.asyncIterator]!=null}var I1=r=>{let e=ve(r),t=We(e);return Dr(r,t),I1.bytes=e,t};I1.bytes=0;function Oa(r,e){e=e??{};let t=e.lengthEncoder??I1;function*n(s){let o=t(s.byteLength);o instanceof Uint8Array?yield o:yield*o,s instanceof Uint8Array?yield s:yield*s}return S1(r)?(async function*(){for await(let s of r)yield*n(s)})():(function*(){for(let s of r)yield*n(s)})()}Oa.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??I1;return new B(t(r.byteLength),r)};var A1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},C1=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},T1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Du=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var XH=8,QH=1024*1024*4,_o;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(_o||(_o={}));var Xw=r=>{let e=Bt(r);return Xw.bytes=ve(e),e};Xw.bytes=0;function ku(r,e){let t=new B,n=_o.LENGTH,s=-1,o=e?.lengthDecoder??Xw,i=e?.maxLengthLength??XH,a=e?.maxDataLength??QH;function*c(){for(;t.byteLength>0;){if(n===_o.LENGTH)try{if(s=o(t),s<0)throw new A1("Invalid message length");if(s>a)throw new C1("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=_o.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new T1("Message length length too long");break}throw l}if(n===_o.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=_o.LENGTH}}}return S1(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Du("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Du("Unexpected end of input")})()}ku.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return ku(n,{...e??{},onLength:o=>{t=o}})};var Qw="/floodsub/1.0.0",Jw="/meshsub/1.0.0",dT="/meshsub/1.1.0",_1="/meshsub/1.2.0";var fT="ERR_TOPIC_VALIDATOR_REJECT",pT="ERR_TOPIC_VALIDATOR_IGNORE";var mT={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};var Nn;(function(r){let e;(function(d){let p;d.codec=()=>(p==null&&(p=Q((f,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),f.subscribe!=null&&(h.uint32(8),h.bool(f.subscribe)),f.topic!=null&&(h.uint32(18),h.string(f.topic)),m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.subscribe=f.bool();break}case 2:{g.topic=f.string();break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>X(f,d.codec()),d.decode=(f,h)=>Y(f,d.codec(),h)})(e=r.SubOpts||(r.SubOpts={}));let t;(function(d){let p;d.codec=()=>(p==null&&(p=Q((f,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),f.from!=null&&(h.uint32(10),h.bytes(f.from)),f.data!=null&&(h.uint32(18),h.bytes(f.data)),f.seqno!=null&&(h.uint32(26),h.bytes(f.seqno)),f.topic!=null&&f.topic!==""&&(h.uint32(34),h.string(f.topic)),f.signature!=null&&(h.uint32(42),h.bytes(f.signature)),f.key!=null&&(h.uint32(50),h.bytes(f.key)),m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={topic:""},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.from=f.bytes();break}case 2:{g.data=f.bytes();break}case 3:{g.seqno=f.bytes();break}case 4:{g.topic=f.string();break}case 5:{g.signature=f.bytes();break}case 6:{g.key=f.bytes();break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>X(f,d.codec()),d.decode=(f,h)=>Y(f,d.codec(),h)})(t=r.Message||(r.Message={}));let n;(function(d){let p;d.codec=()=>(p==null&&(p=Q((f,h,m={})=>{if(m.lengthDelimited!==!1&&h.fork(),f.ihave!=null)for(let g of f.ihave)h.uint32(10),r.ControlIHave.codec().encode(g,h);if(f.iwant!=null)for(let g of f.iwant)h.uint32(18),r.ControlIWant.codec().encode(g,h);if(f.graft!=null)for(let g of f.graft)h.uint32(26),r.ControlGraft.codec().encode(g,h);if(f.prune!=null)for(let g of f.prune)h.uint32(34),r.ControlPrune.codec().encode(g,h);if(f.idontwant!=null)for(let g of f.idontwant)h.uint32(42),r.ControlIDontWant.codec().encode(g,h);m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.ihave!=null&&g.ihave.length===m.limits.ihave)throw new Ie('Decode error - map field "ihave" had too many elements');g.ihave.push(r.ControlIHave.codec().decode(f,f.uint32(),{limits:m.limits?.ihave$}));break}case 2:{if(m.limits?.iwant!=null&&g.iwant.length===m.limits.iwant)throw new Ie('Decode error - map field "iwant" had too many elements');g.iwant.push(r.ControlIWant.codec().decode(f,f.uint32(),{limits:m.limits?.iwant$}));break}case 3:{if(m.limits?.graft!=null&&g.graft.length===m.limits.graft)throw new Ie('Decode error - map field "graft" had too many elements');g.graft.push(r.ControlGraft.codec().decode(f,f.uint32(),{limits:m.limits?.graft$}));break}case 4:{if(m.limits?.prune!=null&&g.prune.length===m.limits.prune)throw new Ie('Decode error - map field "prune" had too many elements');g.prune.push(r.ControlPrune.codec().decode(f,f.uint32(),{limits:m.limits?.prune$}));break}case 5:{if(m.limits?.idontwant!=null&&g.idontwant.length===m.limits.idontwant)throw new Ie('Decode error - map field "idontwant" had too many elements');g.idontwant.push(r.ControlIDontWant.codec().decode(f,f.uint32(),{limits:m.limits?.idontwant$}));break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>X(f,d.codec()),d.decode=(f,h)=>Y(f,d.codec(),h)})(n=r.ControlMessage||(r.ControlMessage={}));let s;(function(d){let p;d.codec=()=>(p==null&&(p=Q((f,h,m={})=>{if(m.lengthDelimited!==!1&&h.fork(),f.topicID!=null&&(h.uint32(10),h.string(f.topicID)),f.messageIDs!=null)for(let g of f.messageIDs)h.uint32(18),h.bytes(g);m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={messageIDs:[]},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}case 2:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new Ie('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>X(f,d.codec()),d.decode=(f,h)=>Y(f,d.codec(),h)})(s=r.ControlIHave||(r.ControlIHave={}));let o;(function(d){let p;d.codec=()=>(p==null&&(p=Q((f,h,m={})=>{if(m.lengthDelimited!==!1&&h.fork(),f.messageIDs!=null)for(let g of f.messageIDs)h.uint32(10),h.bytes(g);m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={messageIDs:[]},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new Ie('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>X(f,d.codec()),d.decode=(f,h)=>Y(f,d.codec(),h)})(o=r.ControlIWant||(r.ControlIWant={}));let i;(function(d){let p;d.codec=()=>(p==null&&(p=Q((f,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),f.topicID!=null&&(h.uint32(10),h.string(f.topicID)),m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>X(f,d.codec()),d.decode=(f,h)=>Y(f,d.codec(),h)})(i=r.ControlGraft||(r.ControlGraft={}));let a;(function(d){let p;d.codec=()=>(p==null&&(p=Q((f,h,m={})=>{if(m.lengthDelimited!==!1&&h.fork(),f.topicID!=null&&(h.uint32(10),h.string(f.topicID)),f.peers!=null)for(let g of f.peers)h.uint32(18),r.PeerInfo.codec().encode(g,h);f.backoff!=null&&(h.uint32(24),h.uint64Number(f.backoff)),m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={peers:[]},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.topicID=f.string();break}case 2:{if(m.limits?.peers!=null&&g.peers.length===m.limits.peers)throw new Ie('Decode error - map field "peers" had too many elements');g.peers.push(r.PeerInfo.codec().decode(f,f.uint32(),{limits:m.limits?.peers$}));break}case 3:{g.backoff=f.uint64Number();break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>X(f,d.codec()),d.decode=(f,h)=>Y(f,d.codec(),h)})(a=r.ControlPrune||(r.ControlPrune={}));let c;(function(d){let p;d.codec=()=>(p==null&&(p=Q((f,h,m={})=>{m.lengthDelimited!==!1&&h.fork(),f.peerID!=null&&(h.uint32(10),h.bytes(f.peerID)),f.signedPeerRecord!=null&&(h.uint32(18),h.bytes(f.signedPeerRecord)),m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{g.peerID=f.bytes();break}case 2:{g.signedPeerRecord=f.bytes();break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>X(f,d.codec()),d.decode=(f,h)=>Y(f,d.codec(),h)})(c=r.PeerInfo||(r.PeerInfo={}));let l;(function(d){let p;d.codec=()=>(p==null&&(p=Q((f,h,m={})=>{if(m.lengthDelimited!==!1&&h.fork(),f.messageIDs!=null)for(let g of f.messageIDs)h.uint32(10),h.bytes(g);m.lengthDelimited!==!1&&h.ldelim()},(f,h,m={})=>{let g={messageIDs:[]},y=h==null?f.len:f.pos+h;for(;f.pos<y;){let b=f.uint32();switch(b>>>3){case 1:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new Ie('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),p),d.encode=f=>X(f,d.codec()),d.decode=(f,h)=>Y(f,d.codec(),h)})(l=r.ControlIDontWant||(r.ControlIDontWant={}));let u;r.codec=()=>(u==null&&(u=Q((d,p,f={})=>{if(f.lengthDelimited!==!1&&p.fork(),d.subscriptions!=null)for(let h of d.subscriptions)p.uint32(10),r.SubOpts.codec().encode(h,p);if(d.messages!=null)for(let h of d.messages)p.uint32(18),r.Message.codec().encode(h,p);d.control!=null&&(p.uint32(26),r.ControlMessage.codec().encode(d.control,p)),f.lengthDelimited!==!1&&p.ldelim()},(d,p,f={})=>{let h={subscriptions:[],messages:[]},m=p==null?d.len:d.pos+p;for(;d.pos<m;){let g=d.uint32();switch(g>>>3){case 1:{if(f.limits?.subscriptions!=null&&h.subscriptions.length===f.limits.subscriptions)throw new Ie('Decode error - map field "subscriptions" had too many elements');h.subscriptions.push(r.SubOpts.codec().decode(d,d.uint32(),{limits:f.limits?.subscriptions$}));break}case 2:{if(f.limits?.messages!=null&&h.messages.length===f.limits.messages)throw new Ie('Decode error - map field "messages" had too many elements');h.messages.push(r.Message.codec().decode(d,d.uint32(),{limits:f.limits?.messages$}));break}case 3:{h.control=r.ControlMessage.codec().decode(d,d.uint32(),{limits:f.limits?.control});break}default:{d.skipType(g&7);break}}}return h})),u),r.encode=d=>X(d,r.codec()),r.decode=(d,p)=>Y(d,r.codec(),p)})(Nn||(Nn={}));var P1=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,n){this.gossip=e,this.msgIdToStrFn=n;for(let s=0;s<t;s++)this.history[s]=[]}get size(){return this.msgs.size}put(e,t,n=!1){let{msgIdStr:s}=e;return this.msgs.has(s)?!1:(this.msgs.set(s,{message:t,validated:n,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),n||this.notValidatedCount++,!0)}observeDuplicate(e,t){let n=this.msgs.get(e);n!=null&&!n.validated&&n.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let n=this.msgs.get(e);if(n==null)return null;let s=(n.iwantCounts.get(t)??0)+1;return n.iwantCounts.set(t,s),{msg:n.message,count:s}}getGossipIDs(e){let t=new Map;for(let n=0;n<this.gossip;n++)this.history[n].forEach(s=>{if((this.msgs.get(s.msgIdStr)?.validated??!1)&&e.has(s.topic)){let i=t.get(s.topic);i==null&&(i=[],t.set(s.topic,i)),i.push(s.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:n,originatingPeers:s}=t;return t.validated=!0,t.originatingPeers=new Set,{message:n,originatingPeers:s}}shift(){this.history[this.history.length-1].forEach(t=>{let n=this.msgs.get(t.msgIdStr);n!=null&&(this.msgs.delete(t.msgIdStr),n.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t==null?null:(this.msgs.delete(e),t)}};var gT;(function(r){r.StrictSign="StrictSign",r.StrictNoSign="StrictNoSign"})(gT||(gT={}));var Es;(function(r){r[r.Signing=0]="Signing",r[r.Anonymous=1]="Anonymous"})(Es||(Es={}));var Ot;(function(r){r.Error="error",r.Ignore="ignore",r.Reject="reject",r.Blacklisted="blacklisted"})(Ot||(Ot={}));var Et;(function(r){r.InvalidSignature="invalid_signature",r.InvalidSeqno="invalid_seqno",r.InvalidPeerId="invalid_peerid",r.SignaturePresent="signature_present",r.SeqnoPresent="seqno_present",r.FromPresent="from_present",r.TransformFailed="transform_failed"})(Et||(Et={}));var St;(function(r){r.duplicate="duplicate",r.invalid="invalid",r.valid="valid"})(St||(St={}));function Zw(r){switch(r){case Mt.Ignore:return Ot.Ignore;case Mt.Reject:return Ot.Reject;default:throw new Error("Unreachable")}}var yT;(function(r){r.forward="forward",r.publish="publish"})(yT||(yT={}));var Rt;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(Rt||(Rt={}));var _r;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Excess="excess"})(_r||(_r={}));var Na;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(Na||(Na={}));var Ba;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(Ba||(Ba={}));var Ra;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(Ra||(Ra={}));function bT(r,e,t){return{protocolsEnabled:r.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:r.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:r.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:r.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:r.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:r.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:r.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:r.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:r.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:r.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:r.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:r.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:r.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:r.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:r.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:r.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:r.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:r.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:r.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:r.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:r.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:r.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:r.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:r.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:r.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:r.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:r.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:r.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:r.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:r.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:r.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:r.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:r.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:r.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:r.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:r.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:r.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:r.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:r.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:r.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:r.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),rpcSentIDontWant:r.gauge({name:"gossipsub_rpc_sent_idontwant_total",help:"RPC sent"}),msgPublishCount:r.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:r.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:r.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:r.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:r.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:r.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:r.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:r.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:r.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:r.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:r.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:r.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:r.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:r.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:r.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:r.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:r.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:r.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:r.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,Number(t.maxMeshMessageDeliveriesWindowSec),2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:r.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:r.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:r.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:r.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:r.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:r.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:r.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:r.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:r.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:r.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:r.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,Number(t.behaviourPenaltyThreshold),2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:r.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:r.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:r.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:r.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),idontwantRcvMsgids:r.gauge({name:"gossipsub_idontwant_rcv_msgids_total",help:"Total received IDONTWANT messages"}),idontwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_idontwant_rcv_dont_have_msgids_total",help:"Total received IDONTWANT messageIDs that we do not have in mcache"}),iwantPromiseStarted:r.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:r.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:r.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:r.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:r.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:r.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:r.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,Number(t.gossipPromiseExpireSec),2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:r.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:r.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:r.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:r.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:r.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:r.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:r.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(n){return this.topicStrToLabel.get(n)??n},onJoin(n){this.topicSubscriptionStatus.set({topicStr:n},1),this.meshPeerCounts.set({topicStr:n},0)},onLeave(n){this.topicSubscriptionStatus.set({topicStr:n},0),this.meshPeerCounts.set({topicStr:n},0)},onAddToMesh(n,s,o){let i=this.toTopic(n);switch(s){case Rt.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case Rt.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case Rt.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case Rt.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case Rt.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case Rt.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:i},o);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:i},o);break}},onRemoveFromMesh(n,s,o){let i=this.toTopic(n);switch(s){case _r.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:i},o);break;case _r.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:i},o);break;case _r.Prune:this.meshPeerChurnEventsPrune.inc({topic:i},o);break;case _r.Excess:this.meshPeerChurnEventsExcess.inc({topic:i},o);break;default:this.meshPeerChurnEventsUnknown.inc({topic:i},o);break}},onReportValidation(n,s,o){if(this.asyncValidationMcacheHit.inc({hit:n!=null?"hit":"miss"}),n!=null){let i=this.toTopic(n.message.topic);switch(s){case Mt.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case Mt.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case Mt.Reject:this.rejectedMessagesTotal.inc({topic:i});break;default:this.unknownValidationResultsTotal.inc({topic:i});break}}o!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-o)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(n){this.scoringPenalties.inc({penalty:n},1)},onIhaveRcv(n,s,o){let i=this.toTopic(n);this.ihaveRcvMsgids.inc({topic:i},s),this.ihaveRcvNotSeenMsgids.inc({topic:i},o)},onIwantRcv(n,s){for(let[o,i]of n){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},i)}this.iwantRcvDonthaveMsgids.inc(s)},onIdontwantRcv(n,s){this.idontwantRcvMsgids.inc(n),this.idontwantRcvDonthaveMsgids.inc(s)},onForwardMsg(n,s){let o=this.toTopic(n);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},s)},onPublishMsg(n,s,o,i,a){let c=this.toTopic(n);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},o*i),this.msgPublishPeersByTopic.inc({topic:c},o),this.directPeersPublishedTotal.inc({topic:c},s.direct),this.floodsubPeersPublishedTotal.inc({topic:c},s.floodsub),this.meshPeersPublishedTotal.inc({topic:c},s.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},s.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(n){let s=this.toTopic(n);this.msgReceivedPreValidation.inc({topic:s},1)},onMsgRecvError(n){let s=this.toTopic(n);this.msgReceivedError.inc({topic:s},1)},onPrevalidationResult(n,s){let o=this.toTopic(n);switch(s){case St.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case St.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case St.valid:this.prevalidationValidTotal.inc({topic:o});break;default:this.prevalidationUnknownTotal.inc({topic:o});break}},onMsgRecvInvalid(n,s){let o=this.toTopic(n),i=s.reason===Ot.Error?s.error:s.reason;this.msgReceivedInvalid.inc({error:i},1),this.msgReceivedInvalidByTopic.inc({topic:o},1)},onDuplicateMsgDelivery(n,s,o){let i=this.toTopic(n);this.duplicateMsgDeliveryDelay.observe({topic:i},s/1e3),o&&this.duplicateMsgLateDelivery.inc({topic:i},1)},onPublishDuplicateMsg(n){let s=this.toTopic(n);this.duplicateMsgIgnored.inc({topic:s},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(n,s){this.rpcRecvBytes.inc(s),this.rpcRecvCount.inc(1),n.subscriptions!=null&&this.rpcRecvSubscription.inc(n.subscriptions.length),n.messages!=null&&this.rpcRecvMessage.inc(n.messages.length),n.control!=null&&(this.rpcRecvControl.inc(1),n.control.ihave!=null&&this.rpcRecvIHave.inc(n.control.ihave.length),n.control.iwant!=null&&this.rpcRecvIWant.inc(n.control.iwant.length),n.control.graft!=null&&this.rpcRecvGraft.inc(n.control.graft.length),n.control.prune!=null&&this.rpcRecvPrune.inc(n.control.prune.length))},onRpcSent(n,s){if(this.rpcSentBytes.inc(s),this.rpcSentCount.inc(1),n.subscriptions!=null&&this.rpcSentSubscription.inc(n.subscriptions.length),n.messages!=null&&this.rpcSentMessage.inc(n.messages.length),n.control!=null){let o=n.control.ihave?.length??0,i=n.control.iwant?.length??0,a=n.control.graft?.length??0,c=n.control.prune?.length??0,l=n.control.idontwant?.length??0;o>0&&this.rpcSentIHave.inc(o),i>0&&this.rpcSentIWant.inc(i),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),l>0&&this.rpcSentIDontWant.inc(l),(o>0||i>0||a>0||c>0||l>0)&&this.rpcSentControl.inc(1)}},registerScores(n,s){let o=0,i=0,a=0,c=0;for(let l of n)l>=s.graylistThreshold&&o++,l>=s.publishThreshold&&i++,l>=s.gossipThreshold&&a++,l>=0&&c++;this.peersByScoreThreshold.set({threshold:Ra.graylist},o),this.peersByScoreThreshold.set({threshold:Ra.publish},i),this.peersByScoreThreshold.set({threshold:Ra.gossip},a),this.peersByScoreThreshold.set({threshold:Ra.mesh},c),this.score.set(n)},registerScoreWeights(n){for(let[s,o]of n.byTopic)this.scoreWeights.set({topic:s,p:"p1"},o.p1w),this.scoreWeights.set({topic:s,p:"p2"},o.p2w),this.scoreWeights.set({topic:s,p:"p3"},o.p3w),this.scoreWeights.set({topic:s,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:s,p:"p4"},o.p4w);this.scoreWeights.set({p:"p5"},n.p5w),this.scoreWeights.set({p:"p6"},n.p6w),this.scoreWeights.set({p:"p7"},n.p7w)},registerScorePerMesh(n,s){let o=new Map;n.forEach((i,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",l=o.get(c);l==null&&(l=new Set,o.set(c,l)),i.forEach(u=>l?.add(u))});for(let[i,a]of o){let c=[];a.forEach(l=>{c.push(s.get(l)??0)}),this.scorePerMesh.set({topic:i},c)}}}}var xe=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var ZH={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},eq={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function wT(r={}){return{...ZH,...r,topics:r.topics!=null?Object.entries(r.topics).reduce((e,[t,n])=>(e[t]=tq(n),e),{}):{}}}function tq(r={}){return{...eq,...r}}function xT(r){for(let[e,t]of Object.entries(r.topics))try{rq(t)}catch(n){throw new xe(`invalid score parameters for topic ${e}: ${n.message}`)}if(r.topicScoreCap<0)throw new xe("invalid topic score cap; must be positive (or 0 for no cap)");if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new xe("missing application specific score function");if(r.IPColocationFactorWeight>0)throw new xe("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new xe("invalid IPColocationFactorThreshold; must be at least 1");if(r.behaviourPenaltyWeight>0)throw new xe("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new xe("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(r.decayInterval<1e3)throw new xe("invalid DecayInterval; must be at least 1s");if(r.decayToZero<=0||r.decayToZero>=1)throw new xe("invalid DecayToZero; must be between 0 and 1")}function rq(r){if(r.topicWeight<0)throw new xe("invalid topic weight; must be >= 0");if(r.timeInMeshQuantum===0)throw new xe("invalid TimeInMeshQuantum; must be non zero");if(r.timeInMeshWeight<0)throw new xe("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new xe("invalid TimeInMeshQuantum; must be positive");if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new xe("invalid TimeInMeshCap; must be positive");if(r.firstMessageDeliveriesWeight<0)throw new xe("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new xe("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new xe("invalid FirstMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight>0)throw new xe("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new xe("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new xe("invalid MeshMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new xe("invalid MeshMessageDeliveriesThreshold; must be positive");if(r.meshMessageDeliveriesWindow<0)throw new xe("invalid MeshMessageDeliveriesWindow; must be non-negative");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new xe("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(r.meshFailurePenaltyWeight>0)throw new xe("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new xe("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(r.invalidMessageDeliveriesWeight>0)throw new xe("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new xe("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var nq={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function vT(r={}){return{...nq,...r}}function k1(r,e,t=()=>!0){let n=new Set;if(e<=0)return n;for(let s of r){if(n.size>=e)break;t(s)&&(n.add(s),r.delete(s))}return n}function ET(r,e){return k1(r,e,()=>!0)}var D1=class extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};function ST(r,e,t,n){let s=0;Object.entries(e.topics).forEach(([i,a])=>{let c=t.topics[i];if(c===void 0)return;let l=0;if(a.inMesh){let f=a.meshTime/c.timeInMeshQuantum;f>c.timeInMeshCap&&(f=c.timeInMeshCap),l+=f*c.timeInMeshWeight}let u=a.firstMessageDeliveries;if(u>c.firstMessageDeliveriesCap&&(u=c.firstMessageDeliveriesCap),l+=u*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let f=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,h=f*f;l+=h*c.meshMessageDeliveriesWeight}let d=a.meshFailurePenalty;l+=d*c.meshFailurePenaltyWeight;let p=a.invalidMessageDeliveries*a.invalidMessageDeliveries;l+=p*c.invalidMessageDeliveriesWeight,s+=l*c.topicWeight}),t.topicScoreCap>0&&s>t.topicScoreCap&&(s=t.topicScoreCap);let o=t.appSpecificScore(r);if(s+=o*t.appSpecificWeight,e.knownIPs.forEach(i=>{if(t.IPColocationFactorWhitelist.has(i))return;let a=n.get(i),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let l=c-t.IPColocationFactorThreshold,u=l*l;s+=u*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let i=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=i*i;s+=a*t.behaviourPenaltyWeight}return s}var CT=ne(AT(),1);var Nt;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(Nt||(Nt={}));var L1=class{records;queue;constructor(){this.records=new Map,this.queue=new CT.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Nt.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let n={msgId:e,expire:Date.now()+12e4};return this.queue.push(n),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t!=null&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};var M1=class{params;metrics;peerStats=new Map;peerIPs=new D1(()=>new Set);scoreCache=new Map;deliveryRecords=new L1;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,n,s){this.params=e,this.metrics=t,xT(e),this.scoreCacheValidityMs=s.scoreCacheValidityMs,this.computeScore=s.computeScore??ST,this.log=n.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(this._backgroundInterval!=null){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(this._backgroundInterval==null){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return t!=null?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((n,s)=>{if(!n.connected){e>n.expire&&(this.removeIPsForPeer(s,n.knownIPs),this.peerStats.delete(s),this.scoreCache.delete(s));return}Object.entries(n.topics).forEach(([o,i])=>{let a=this.params.topics[o];a!==void 0&&(i.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,i.firstMessageDeliveries<t&&(i.firstMessageDeliveries=0),i.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,i.meshMessageDeliveries<t&&(i.meshMessageDeliveries=0),i.meshFailurePenalty*=a.meshFailurePenaltyDecay,i.meshFailurePenalty<t&&(i.meshFailurePenalty=0),i.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,i.invalidMessageDeliveries<t&&(i.invalidMessageDeliveries=0),i.inMesh&&(i.meshTime=e-i.graftTime,i.meshTime>a.meshMessageDeliveriesActivation&&(i.meshMessageDeliveriesActive=!0)))}),n.behaviourPenalty*=this.params.behaviourPenaltyDecay,n.behaviourPenalty<t&&(n.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let n=Date.now(),s=this.scoreCache.get(e);if(s!=null&&s.cacheUntil>n)return s.score;this.metrics?.scoreFnRuns.inc();let o=this.computeScore(e,t,this.params,this.peerIPs),i=n+this.scoreCacheValidityMs;return s!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(o-s.score)),s.score=o,s.cacheUntil=i):this.scoreCache.set(e,{score:o,cacheUntil:i}),o}addPenalty(e,t,n){let s=this.peerStats.get(e);s!=null&&(s.behaviourPenalty+=t,this.metrics?.onScorePenalty(n))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let n=this.peerStats.get(e);n?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let n=this.peerStats.get(e);n?.knownIPs.delete(t);let s=this.peerIPs.get(t);s!=null&&(s.delete(e),s.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t!=null){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([n,s])=>{s.firstMessageDeliveries=0;let o=this.params.topics[n].meshMessageDeliveriesThreshold;if(s.inMesh&&s.meshMessageDeliveriesActive&&s.meshMessageDeliveries<o){let i=o-s.meshMessageDeliveries;s.meshFailurePenalty+=i*i}s.inMesh=!1,s.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);s!=null&&(s.inMesh=!0,s.graftTime=Date.now(),s.meshTime=0,s.meshMessageDeliveriesActive=!1)}}prune(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);if(s!=null){let o=this.params.topics[t].meshMessageDeliveriesThreshold;if(s.meshMessageDeliveriesActive&&s.meshMessageDeliveries<o){let i=o-s.meshMessageDeliveries;s.meshFailurePenalty+=i*i}s.meshMessageDeliveriesActive=!1,s.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,n){this.markFirstMessageDelivery(e,n);let s=this.deliveryRecords.ensureRecord(t),o=Date.now();if(s.status!==Nt.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-s.firstSeenTsMs,Nt[s.status]);return}s.status=Nt.valid,s.validated=o,s.peers.forEach(i=>{i!==e.toString()&&this.markDuplicateMessageDelivery(i,n)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,n,s){switch(s){case Ot.Error:this.markInvalidMessageDelivery(e,n);return;case Ot.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==Nt.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,Nt[o.status]);return}if(s===Ot.Ignore){o.status=Nt.ignored,o.peers.clear();return}o.status=Nt.invalid,this.markInvalidMessageDelivery(e,n),o.peers.forEach(i=>{this.markInvalidMessageDelivery(i,n)}),o.peers.clear()}duplicateMessage(e,t,n){let s=this.deliveryRecords.ensureRecord(t);if(!s.peers.has(e))switch(s.status){case Nt.unknown:s.peers.add(e);break;case Nt.valid:s.peers.add(e),this.markDuplicateMessageDelivery(e,n,s.validated);break;case Nt.invalid:this.markInvalidMessageDelivery(e,n);break;case Nt.ignored:break}}markInvalidMessageDelivery(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);s!=null&&(s.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let n=this.peerStats.get(e);if(n!=null){let s=this.getPtopicStats(n,t);if(s!=null){let o=this.params.topics[t].firstMessageDeliveriesCap;s.firstMessageDeliveries=Math.min(o,s.firstMessageDeliveries+1),s.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,s.meshMessageDeliveries=Math.min(o,s.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,n){let s=this.peerStats.get(e);if(s!=null){let o=n!==void 0?Date.now():0,i=this.getPtopicStats(s,t);if(i!=null&&i.inMesh){let a=this.params.topics[t];if(n!==void 0){let l=o-n,u=l>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,l,u),u)return}let c=a.meshMessageDeliveriesCap;i.meshMessageDeliveries=Math.min(c,i.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let n of t){let s=this.peerIPs.get(n);s!=null&&(s.delete(e),s.size===0&&this.peerIPs.delete(n))}}getPtopicStats(e,t){let n=e.topics[t];return n!==void 0?n:this.params.topics[t]!==void 0?(n={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=n,n):null}};function sq(r,e,t,n,s){let o=0,i=new Map;if(Object.entries(e.topics).forEach(([p,f])=>{let h=s.get(p)??"unknown",m=t.topics[p];if(m===void 0)return;let g=i.get(h);g==null&&(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(h,g));let y=0,b=0,E=0,x=0,v=0;if(f.inMesh){let A=Math.max(f.meshTime/m.timeInMeshQuantum,m.timeInMeshCap);y+=A*m.timeInMeshWeight}let S=f.firstMessageDeliveries;if(S>m.firstMessageDeliveriesCap&&(S=m.firstMessageDeliveriesCap),b+=S*m.firstMessageDeliveriesWeight,f.meshMessageDeliveriesActive&&f.meshMessageDeliveries<m.meshMessageDeliveriesThreshold){let A=m.meshMessageDeliveriesThreshold-f.meshMessageDeliveries,G=A*A;E+=G*m.meshMessageDeliveriesWeight}let w=f.meshFailurePenalty;x+=w*m.meshFailurePenaltyWeight;let I=f.invalidMessageDeliveries*f.invalidMessageDeliveries;v+=I*m.invalidMessageDeliveriesWeight,o+=(y+b+E+x+v)*m.topicWeight,g.p1w+=y,g.p2w+=b,g.p3w+=E,g.p3bw+=x,g.p4w+=v}),t.topicScoreCap>0&&o>t.topicScoreCap){o=t.topicScoreCap;let p=t.topicScoreCap/o;for(let f of i.values())f.p1w*=p,f.p2w*=p,f.p3w*=p,f.p3bw*=p,f.p4w*=p}let a=0,c=0,l=0,u=t.appSpecificScore(r);a+=u*t.appSpecificWeight,e.knownIPs.forEach(p=>{if(t.IPColocationFactorWhitelist.has(p))return;let f=n.get(p),h=f!=null?f.size:0;if(h>t.IPColocationFactorThreshold){let m=h-t.IPColocationFactorThreshold,g=m*m;c+=g*t.IPColocationFactorWeight}});let d=e.behaviourPenalty*e.behaviourPenalty;return l+=d*t.behaviourPenaltyWeight,o+=a+c+l,{byTopic:i,p5w:a,p6w:c,p7w:l,score:o}}function TT(r,e,t,n,s){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let i of r){let a=e.get(i);if(a!=null){let c=sq(i,a,t,n,s);for(let[l,u]of c.byTopic){let d=o.byTopic.get(l);d==null&&(d={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(l,d)),d.p1w.push(u.p1w),d.p2w.push(u.p2w),d.p3w.push(u.p3w),d.p3bw.push(u.p3bw),d.p4w.push(u.p4w)}o.p5w.push(c.p5w),o.p6w.push(c.p6w),o.p7w.push(c.p7w),o.score.push(c.score)}else o.p5w.push(0),o.p6w.push(0),o.p7w.push(0),o.score.push(0)}return o}var O1=class{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,n){this.rawStream=e,this.pushable=It(),this.closeController=new AbortController,this.maxBufferSize=n.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(s=>{e.abort(s)})}),rt(this.pushable,this.rawStream).catch(t)}get protocol(){return this.rawStream.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(Oa.single(e))}pushPrefixed(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}async close(){this.closeController.abort(),await this.pushable.return()}},R1=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(n=>{e.abort(n)})}),this.source=rt(this.rawStream,n=>ku(n,t))}async close(){this.closeController.abort()}};var N1=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,n){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=n,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let n=Math.floor(Math.random()*t.length),s=t[n],o=this.msgIdToStrFn(s),i=this.promises.get(o);i==null&&(i=new Map,this.promises.set(o,i));let a=Date.now();i.has(e)||(i.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(o)||this.requestMsByMsg.set(o,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,n=0;return this.promises.forEach((s,o)=>{s.forEach((i,a)=>{i<e&&(t.set(a,(t.get(a)??0)+1),s.delete(a),n++)}),s.size===0&&this.promises.delete(o)}),this.metrics?.iwantPromiseBroken.inc(n),t}deliverMessage(e,t=!1){this.trackMessage(e);let n=this.promises.get(e);n!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(n.size)))}rejectMessage(e,t){switch(this.trackMessage(e),t){case Ot.Error:return;default:break}this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[n,s]of this.requestMsByMsg.entries())if(s<e)this.requestMsByMsg.delete(n),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var t6={};z(t6,{base64:()=>oq,base64pad:()=>iq,base64url:()=>e6,base64urlpad:()=>aq});var oq=ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),iq=ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),e6=ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),aq=ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var _T=P("libp2p-pubsub:");async function PT(r,e,t,n){switch(r.type){case Es.Signing:{let s={from:r.author.toMultihash().bytes,data:n,seqno:g1(8),topic:e,signature:void 0,key:void 0},o=be([_T,Nn.Message.encode(s)]);s.signature=await r.privateKey.sign(o),s.key=r.key;let i={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${C(s.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:s.signature,key:Vw(s.key)};return{raw:s,msg:i}}case Es.Anonymous:return{raw:{from:void 0,data:n,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}};default:throw new Error("Unreachable")}}async function DT(r,e){switch(r){case Aa:return e.signature!=null?{valid:!1,error:Et.SignaturePresent}:e.seqno!=null?{valid:!1,error:Et.SeqnoPresent}:e.from!=null?{valid:!1,error:Et.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case Co:{if(e.seqno==null)return{valid:!1,error:Et.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:Et.InvalidSeqno};if(e.signature==null)return{valid:!1,error:Et.InvalidSignature};if(e.from==null)return{valid:!1,error:Et.InvalidPeerId};let t;try{t=Ma(On(e.from))}catch{return{valid:!1,error:Et.InvalidPeerId}}let n;if(e.key!=null){if(n=Vw(e.key),t.publicKey!==void 0&&!n.equals(t.publicKey))return{valid:!1,error:Et.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:Et.InvalidPeerId};n=t.publicKey}let s={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=be([_T,Nn.Message.encode(s)]);return await n.verify(o,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${C(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:n}}:{valid:!1,error:Et.InvalidSignature}}default:throw new Error("Unreachable")}}function Pr(r=[],e){return{subscriptions:[],messages:r,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function r6(r){return r.control===void 0&&(r.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),r}function on(r){if(r.length<=1)return r;let e=()=>Math.floor(Math.random()*Math.floor(r.length));for(let t=0;t<r.length;t++){let n=e(),s=r[t];r[t]=r[n],r[n]=s}return r}function kT(r){return C(r,"base64")}function LT(r,e,t){switch(r){case Co:return{type:Es.Signing,author:e,key:vs(t.publicKey),privateKey:t};case Aa:return{type:Es.Anonymous};default:throw new Error(`Unknown signature policy "${r}"`)}}var RCe=new Uint8Array(0);function B1(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}var cq=RT,MT=128,lq=127,uq=~lq,hq=Math.pow(2,31);function RT(r,e,t){e=e||[],t=t||0;for(var n=t;r>=hq;)e[t++]=r&255|MT,r/=128;for(;r&uq;)e[t++]=r&255|MT,r>>>=7;return e[t]=r|0,RT.bytes=t-n+1,e}var dq=n6,fq=128,OT=127;function n6(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw n6.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&OT)<<s:(i&OT)*Math.pow(2,s),s+=7}while(i>=fq);return n6.bytes=o-n,t}var pq=Math.pow(2,7),mq=Math.pow(2,14),gq=Math.pow(2,21),yq=Math.pow(2,28),bq=Math.pow(2,35),wq=Math.pow(2,42),xq=Math.pow(2,49),vq=Math.pow(2,56),Eq=Math.pow(2,63),Sq=function(r){return r<pq?1:r<mq?2:r<gq?3:r<yq?4:r<bq?5:r<wq?6:r<xq?7:r<vq?8:r<Eq?9:10},Iq={encode:cq,decode:dq,encodingLength:Sq},Aq=Iq,s6=Aq;function o6(r,e,t=0){return s6.encode(r,e,t),e}function i6(r){return s6.encodingLength(r)}function NT(r,e){let t=e.byteLength,n=i6(r),s=n+i6(t),o=new Uint8Array(s+t);return o6(r,o,0),o6(t,o,n),o.set(e,s),new a6(r,t,e,o)}var a6=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var an;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(an||(an={}));var c6;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(c6||(c6={}));(function(r){r.codec=()=>Wt(c6)})(an||(an={}));var U1;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),an.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=an.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(U1||(U1={}));var l6;(function(r){let e;r.codec=()=>(e==null&&(e=Q((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),an.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=an.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>X(t,r.codec()),r.decode=(t,n)=>Y(t,r.codec(),n)})(l6||(l6={}));function UT(r){return U1.encode({Type:an[r.type],Data:r.raw})}var d6=ne(Z("crypto"),1);var _q=20;function h6({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new u6(r,e,t,n,s)}var u6=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??_q,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?KT(n,this.code,t?.truncate):n.then(s=>KT(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function KT(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return NT(e,r)}var Pq=h6({name:"sha2-256",code:18,encode:r=>B1(d6.default.createHash("sha256").update(r).digest())}),WCe=h6({name:"sha2-512",code:19,encode:r=>B1(d6.default.createHash("sha512").update(r).digest())});var FT=(r,e)=>{let t=P(e.toString(16).padStart(16,"0"),"base16"),n=UT(r),s=new Uint8Array(n.byteLength+t.length);return s.set(n,0),s.set(t,n.byteLength),s};function zT(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return FT(r.from.publicKey??r.key,r.sequenceNumber)}async function $T(r){return Tu.encode(r.data)}var Bn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Un=class extends Error{static name="ValidationError";name="ValidationError"};var K1=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var f6={};z(f6,{base10:()=>Dq});var Dq=ys({prefix:"9",name:"base10",alphabet:"0123456789"});var p6={};z(p6,{base16:()=>kq,base16upper:()=>Lq});var kq=ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Lq=ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var m6={};z(m6,{base2:()=>Mq});var Mq=ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var g6={};z(g6,{base256emoji:()=>Uq});var HT=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}"),Oq=HT.reduce((r,e,t)=>(r[t]=e,r),[]),Rq=HT.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Nq(r){return r.reduce((e,t)=>(e+=Oq[t],e),"")}function Bq(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Rq[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Uq=Ta({prefix:"\u{1F680}",name:"base256emoji",encode:Nq,decode:Bq});var y6={};z(y6,{base8:()=>Kq});var Kq=ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var b6={};z(b6,{identity:()=>Fq});var Fq=Ta({prefix:"\0",name:"identity",encode:r=>_C(r),decode:r=>TC(r)});var ETe=new TextEncoder,STe=new TextDecoder;var qT={...b6,...m6,...y6,...f6,...p6,...xw,...vw,...ww,...t6,...g6},CTe={...Yw,...Iw};function x6(r){return e=>C(e,r)}function v6(r){return e=>P(e,r)}function Ua(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Po(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function VT(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=P(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Po(n);return be([t,s],t.length+s.length)}function GT(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=bs.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 s=Po(n);return be([t,s],t.length+s.length)}function E6(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=C(e,"base32"),s=Ua(t);return`${n}:${s}`}var S6=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new Bn("Invalid byte value in IP address");e[n]=s}),e},WT=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=(0,le.isIPv4)(t[n]),i;o&&(i=S6(t[n]),t[n]=C(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,C(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new Bn("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},jT=function(r){if(r.byteLength!==4)throw new Bn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},YT=function(r){if(r.byteLength!==16)throw new Bn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Bn(`Invalid IPv6 address "${t}"`)}};function XT(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Bn(`Invalid IPv6 address "${r}"`)}}var w6=Object.values(qT).map(r=>r.decoder),Hq=(function(){let r=w6[0].or(w6[1]);return w6.slice(2).forEach(e=>r=r.or(e)),r})();function QT(r){return Hq.decode(r)}function JT(r){return e=>r.encoder.encode(e)}function qq(r){if(parseInt(r).toString()!==r)throw new Un("Value must be an integer")}function Vq(r){if(r<0)throw new Un("Value must be a positive integer, or zero")}function Gq(r){return e=>{if(e>r)throw new Un(`Value must be smaller than or equal to ${r}`)}}function Wq(...r){return e=>{for(let t of r)t(e)}}var Lu=Wq(qq,Vq,Gq(65535));var nr=-1,I6=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new K1(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},A6=new I6,OV=[{code:4,name:"ip4",size:32,valueToBytes:S6,bytesToValue:jT,validate:r=>{if(!(0,le.isIPv4)(r))throw new Un(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Po,bytesToValue:Ua,validate:Lu},{code:273,name:"udp",size:16,valueToBytes:Po,bytesToValue:Ua,validate:Lu},{code:33,name:"dccp",size:16,valueToBytes:Po,bytesToValue:Ua,validate:Lu},{code:41,name:"ip6",size:128,valueToBytes:WT,bytesToValue:YT,stringToValue:XT,validate:r=>{if(!(0,le.isIPv6)(r))throw new Un(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:nr},{code:43,name:"ipcidr",size:8,bytesToValue:x6("base10"),valueToBytes:v6("base10")},{code:53,name:"dns",size:nr,resolvable:!0},{code:54,name:"dns4",size:nr,resolvable:!0},{code:55,name:"dns6",size:nr,resolvable:!0},{code:56,name:"dnsaddr",size:nr,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Po,bytesToValue:Ua,validate:Lu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:nr,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:nr,bytesToValue:x6("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?v6("base58btc")(r):et.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:E6,valueToBytes:VT},{code:445,name:"onion3",size:296,bytesToValue:E6,valueToBytes:GT},{code:446,name:"garlic64",size:nr},{code:447,name:"garlic32",size:nr},{code:448,name:"tls"},{code:449,name:"sni",size:nr},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:nr,bytesToValue:JT(e6),valueToBytes:QT},{code:480,name:"http"},{code:481,name:"http-path",size:nr,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:nr}];OV.forEach(r=>{A6.addProtocol(r)});function ZT(r,e){return A6.getProtocol(r).bytesToValue?.(e)??C(e,"base16")}var F1;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(F1||(F1={}));function e_(r){for(let e of r.tuples())switch(e[0]){case F1.ip4:case F1.ip6:return ZT(e[0],e[1]);default:break}return null}var Ka=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,n]of this.entries.entries())if(n.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var sr;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(sr||(sr={}));var C6=class extends he{globalSignaturePolicy;multicodecs=[_1,dT,Jw];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=It({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=_1;opts;decodeRpcLimits;metrics;status={code:sr.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let n={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,tagMeshPeers:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,gossipFactor:.25,idontwantMinDataSize:512,idontwantMaxMessages:512,...t,scoreParams:wT(t.scoreParams),scoreThresholds:vT(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=n.decodeRpcLimits??mT,this.globalSignaturePolicy=n.globalSignaturePolicy??Co,n.fallbackToFloodsub&&this.multicodecs.push(Qw),this.log=e.logger.forComponent(n.debugName??"libp2p:gossipsub"),this.opts=n,this.direct=new Set(n.directPeers.map(s=>s.id.toString())),this.seenCache=new Ka({validityMs:n.seenTTL}),this.publishedMessageIds=new Ka({validityMs:n.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Co:this.msgIdFn=zT;break;case Aa:this.msgIdFn=$T;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new Ka({validityMs:n.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??kT,this.mcache=t.messageCache??new P1(n.mcacheGossip,n.mcacheLength,this.msgIdToStrFn),t.dataTransform!=null&&(this.dataTransform=t.dataTransform),t.metricsRegister!=null){if(t.metricsTopicStrToLabel==null)throw Error("Must set metricsTopicStrToLabel with metrics");let s=Math.max(...Object.values(n.scoreParams.topics).map(i=>i.meshMessageDeliveriesWindow),1e3),o=bT(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:n.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:s/1e3});o.mcacheSize.addCollect(()=>{this.onScrapeMetrics(o)});for(let i of this.multicodecs)o.protocolsEnabled.set({protocol:i},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new N1(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new M1(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:n.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=n.allowedTopics!=null?new Set(n.allowedTopics):null}[Symbol.toStringTag]="@chainsafe/libp2p-gossipsub";[IC]=["@libp2p/pubsub"];[AC]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===sr.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=LT(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=It({objectMode:!0}),rt(this.outboundInflightQueue,async o=>{for await(let{peerId:i,connection:a}of o)await this.createOutboundStream(i,a)}).catch(o=>{this.log.error("outbound inflight queue error",o)}),await Promise.all(this.opts.directPeers.map(async o=>{await this.components.peerStore.merge(o.id,{multiaddrs:o.addrs})}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(async o=>e.handle(o,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnLimitedConnection:this.runOnLimitedConnection},n=await Promise.all(this.multicodecs.map(async o=>e.register(o,t))),s=setTimeout(this.runHeartbeat,100);this.status={code:sr.started,registrarTopologyIds:n,heartbeatTimeout:s,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async o=>this.connect(o)))}).catch(o=>{this.log(o)})},1e3),this.opts.tagMeshPeers&&(this.addEventListener("gossipsub:graft",this.tagMeshPeer),this.addEventListener("gossipsub:prune",this.untagMeshPeer)),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==sr.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:sr.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.multicodecs.map(async s=>t.unhandle(s))),e.forEach(s=>{t.unregister(s)}),this.outboundInflightQueue.end();let n=[];for(let s of this.streamsOutbound.values())n.push(s.close());this.streamsOutbound.clear();for(let s of this.streamsInbound.values())n.push(s.close());this.streamsInbound.clear(),await Promise.all(n),this.peers.clear(),this.subscriptions.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;let n=t.remotePeer;this.addPeer(n,t.direction,t.remoteAddr),this.createInboundStream(n,e),this.outboundInflightQueue.push({peerId:n,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(this.peers.has(n)&&!this.streamsOutbound.has(n))try{let s=new O1(await t.newStream(this.multicodecs,{runOnLimitedConnection:this.runOnLimitedConnection}),i=>{this.log.error("outbound pipe error",i)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(n,s);let o=s.protocol;o===Qw&&this.floodsubPeers.add(n),this.metrics?.peersPerProtocol.inc({protocol:o},1),this.subscriptions.size>0&&(this.log("send subscriptions to",n),this.sendSubscriptions(n,Array.from(this.subscriptions),!0))}catch(s){this.log.error("createOutboundStream error",s)}}createInboundStream(e,t){if(!this.isStarted())return;let n=e.toString();if(!this.peers.has(n))return;let s=this.streamsInbound.get(n);s!==void 0&&(this.log("replacing existing inbound steam %s",n),s.close().catch(i=>{this.log.error(i)})),this.log("create inbound stream %s",n);let o=new R1(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(n,o),this.pipePeerReadStream(e,o.source).catch(i=>{this.log(i)})}addPeer(e,t,n){let s=e.toString();if(!this.peers.has(s)){this.log("new peer %p",e),this.peers.set(s,e),this.score.addPeer(s);let o=e_(n);o!==null?this.score.addIP(s,o):this.log("Added peer has no IP in current address %s %s",s,n.toString()),this.outbound.has(s)||this.outbound.set(s,t==="outbound")}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let n=this.streamsOutbound.get(t),s=this.streamsInbound.get(t);n!=null&&this.metrics?.peersPerProtocol.inc({protocol:n.protocol},-1),n?.close().catch(o=>{this.log.error(o)}),s?.close().catch(o=>{this.log.error(o)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let o of this.topics.values())o.delete(t);for(let[o,i]of this.mesh)i.delete(t)&&this.metrics?.onRemoveFromMesh(o,_r.Dc,1);for(let o of this.fanout.values())o.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.idontwantCounts.delete(t),this.idontwants.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===sr.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(n=>this.peers.get(n)??To(n))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await rt(t,async n=>{for await(let s of n)try{let o=s.subarray(),i=Nn.decode(o,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant:this.decodeRpcLimits.maxIwantMessageIDs,graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}});if(this.metrics?.onRpcRecv(i,o.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,i)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,i).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(o){this.metrics?.onRpcDataError(),this.log(o)}})}catch(n){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(n,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let n=t.subscriptions!=null?t.subscriptions.length:0,s=t.messages!=null?t.messages.length:0,o=0,i=0,a=0,c=0;if(t.control!=null&&(t.control.ihave!=null&&(o=t.control.ihave.length),t.control.iwant!=null&&(i=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${n} messages ${s} ihave ${o} iwant ${i} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let l=[];t.subscriptions.forEach(u=>{let d=u.topic,p=u.subscribe===!0;if(d!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(d))return;this.handleReceivedSubscription(e,d,p),l.push({topic:d,subscribe:p})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:l}})}for(let l of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(l.topic))continue;let u=this.handleReceivedMessage(e,l).catch(d=>{this.metrics?.onMsgRecvError(l.topic),this.log(d)});this.opts.awaitRpcMessageHandler&&await u}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,n){this.log("subscription update from %p topic %s",e,t);let s=this.topics.get(t);s==null&&(s=new Set,this.topics.set(t,s)),n?s.add(e.toString()):s.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let n=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,n.code);let s=n.code;switch(s){case St.duplicate:this.score.duplicateMessage(e.toString(),n.msgIdStr,t.topic),this.gossipTracer.deliverMessage(n.msgIdStr,!0),this.mcache.observeDuplicate(n.msgIdStr,e.toString());return;case St.invalid:if(n.msgIdStr!=null){let o=n.msgIdStr;this.score.rejectMessage(e.toString(),o,t.topic,n.reason),this.gossipTracer.rejectMessage(o,n.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,n);return;case St.valid:this.score.validateMessage(n.messageId.msgIdStr),this.gossipTracer.deliverMessage(n.messageId.msgIdStr),this.mcache.put(n.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:n.messageId.msgIdStr,msg:n.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:n.msg}))),this.opts.asyncValidation||this.forwardMessage(n.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${s}`)}}async validateReceivedMessage(e,t){let n=this.fastMsgIdFn?.(t),s=n!==void 0?this.fastMsgIdCache?.get(n):void 0;if(s!=null)return{code:St.duplicate,msgIdStr:s};let o=await DT(this.globalSignaturePolicy,t);if(!o.valid)return{code:St.invalid,reason:Ot.Error,error:o.error};let i=o.message;try{this.dataTransform!=null&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(d){return this.log("Invalid message, transform failed",d),{code:St.invalid,reason:Ot.Error,error:Et.TransformFailed}}let a=await this.msgIdFn(i),c=this.msgIdToStrFn(a),l={msgId:a,msgIdStr:c};if(n!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(n,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:St.duplicate,msgIdStr:c};this.seenCache.put(c),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let u=this.topicValidators.get(t.topic);if(u!=null){let d;try{d=await u(e,i)}catch(p){let f=p.code;f===pT&&(d=Mt.Ignore),f===fT?d=Mt.Reject:d=Mt.Ignore}if(d!==Mt.Accept)return{code:St.invalid,reason:Zw(d),msgIdStr:c}}return{code:St.valid,messageId:l,msg:i}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,n){this.sendRpc(e,{subscriptions:t.map(s=>({topic:s,subscribe:n})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let n=t.ihave?.length>0?this.handleIHave(e,t.ihave):[],s=t.iwant?.length>0?this.handleIWant(e,t.iwant):[],o=t.graft?.length>0?await this.handleGraft(e,t.graft):[];if(t.prune?.length>0&&await this.handlePrune(e,t.prune),t.idontwant?.length>0&&this.handleIdontwant(e,t.idontwant),n.length===0&&s.length===0&&o.length===0)return;let i=this.sendRpc(e,Pr(s,{iwant:n,prune:o})),a=n[0]?.messageIDs;a!=null&&(i?this.gossipTracer.addPromise(e,a):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),n=this.acceptFromWhitelist.get(e);if(n!=null&&n.messagesAccepted<128&&n.acceptUntil>=t)return n.messagesAccepted+=1,!0;let s=this.score.score(e);return s>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),s>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:Ba.LowScore}),[];let s=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,s),s>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:Ba.MaxIhave}),[];let o=this.iasked.get(e)??0;if(o>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,o),this.metrics?.ihaveRcvIgnored.inc({reason:Ba.MaxIasked}),[];let i=new Map;if(t.forEach(({topicID:l,messageIDs:u})=>{if(l==null||u==null||!this.mesh.has(l))return;let d=0;u.forEach(p=>{let f=this.msgIdToStrFn(p);this.seenCache.has(f)||(i.set(f,p),d++)}),this.metrics?.onIhaveRcv(l,u.length,d)}),i.size===0)return[];let a=i.size;a+o>5e3&&(a=5e3-o),this.log("IHAVE: Asking for %d out of %d messages from %s",a,i.size,e);let c=Array.from(i.values());return on(c),c=c.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:c}]}handleIWant(e,t){if(t.length===0)return[];let n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,n),[];let s=new Map,o=new Map,i=0;return t.forEach(({messageIDs:a})=>{a?.forEach(c=>{let l=this.msgIdToStrFn(c),u=this.mcache.getWithIWantCount(l,e);if(u==null){i++;return}if(o.set(u.msg.topic,1+(o.get(u.msg.topic)??0)),u.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c);return}s.set(l,u.msg)})}),this.metrics?.onIwantRcv(o,i),s.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",s.size,e),Array.from(s.values()))}async handleGraft(e,t){let n=[],s=this.score.score(e),o=Date.now(),i=this.opts.doPX;if(t.forEach(({topicID:c})=>{if(c==null)return;let l=this.mesh.get(c);if(l==null){i=!1;return}if(l.has(e))return;let u=this.backoff.get(c)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),n.push(c),i=!1;else if(typeof u=="number"&&o<u){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,Na.GraftBackoff),i=!1;let d=u+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<d&&this.score.addPenalty(e,1,Na.GraftBackoff),this.addBackoff(e,c),n.push(c)}else s<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,s,c),n.push(c),i=!1,this.addBackoff(e,c)):l.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(n.push(c),this.addBackoff(e,c)):(this.log("GRAFT: Add mesh link from %s in %s",e,c),this.score.graft(e,c),l.add(e),this.metrics?.onAddToMesh(c,Rt.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),n.length===0)return[];let a=!1;return Promise.all(n.map(async c=>this.makePrune(e,c,i,a)))}async handlePrune(e,t){let n=this.score.score(e);for(let{topicID:s,backoff:o,peers:i}of t){if(s==null)continue;let a=this.mesh.get(s);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,s),this.score.prune(e,s),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(s,_r.Prune,1)),typeof o=="number"&&o>0?this.doAddBackoff(e,s,o*1e3):this.addBackoff(e,s),i!=null&&i.length>0&&(n<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,n,s):await this.pxConnect(i)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:s,direction:"inbound"}})}}handleIdontwant(e,t){let n=this.idontwantCounts.get(e)??0;if(n>=this.opts.idontwantMaxMessages)return;let s=n,o=this.idontwants.get(e);o==null&&(o=new Map,this.idontwants.set(e,o));let i=0;e:for(let{messageIDs:c}of t)for(let l of c){if(n>=this.opts.idontwantMaxMessages)break e;n++;let u=this.msgIdToStrFn(l);o.set(u,this.heartbeatTicks),this.mcache.msgs.has(u)||i++}this.idontwantCounts.set(e,n);let a=n-s;this.metrics?.onIdontwantRcv(a,i)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,n){let s=this.backoff.get(t);s==null&&(s=new Map,this.backoff.set(t,s));let o=Date.now()+n;(s.get(e)??0)<o&&s.set(e,o)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,Na.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,n)=>{t.forEach((s,o)=>{s+1*this.opts.heartbeatInterval<e&&t.delete(o)}),t.size===0&&this.backoff.delete(n)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(on(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async n=>{if(n.peerID==null)return;let s=Ma(On(n.peerID)),o=s.toString();if(!this.peers.has(o)){if(n.signedPeerRecord==null){t.push(o);return}try{if(!await this.components.peerStore.consumePeerRecord(n.signedPeerRecord,s)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(o)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length!==0&&await Promise.all(t.map(async n=>this.connect(n)))}async connect(e){this.log("Initiating connection with %s",e);let t=To(e),n=await this.components.connectionManager.openConnection(t);for(let s of this.multicodecs)for(let o of this.components.registrar.getTopologies(s))o.onConnect?.(t,n)}subscribe(e){if(this.status.code!==sr.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==sr.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let n of this.peers.keys())this.sendSubscriptions(n,[e],!1);this.leave(e)}join(e){if(this.status.code!==sr.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,n=this.backoff.get(e),s=this.fanout.get(e);if(s!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),s.forEach(o=>{!this.direct.has(o)&&this.score.score(o)>=0&&n?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,Rt.Fanout,t.size)),t.size<this.opts.D){let o=t.size;this.getRandomGossipPeers(e,this.opts.D,a=>!t.has(a)&&!this.direct.has(a)&&this.score.score(a)>=0&&n?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,Rt.Random,t.size-o)}this.mesh.set(e,t),t.forEach(o=>{this.log("JOIN: Add mesh link to %s in %s",o,e),this.sendGraft(o,e)})}leave(e){if(this.status.code!==sr.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async n=>{this.log("LEAVE: Remove mesh link to %s in %s",n,e),await this.sendPrune(n,e)})).catch(n=>{this.log("Error sending prunes to mesh peers",n)}),this.mesh.delete(e))}selectPeersToForward(e,t,n){let s=new Set,o=this.topics.get(e);o!=null&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(n?.has(a)??!1)&&s.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(n?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&s.add(a)}));let i=this.mesh.get(e);return i!=null&&i.size>0&&i.forEach(a=>{t!==a&&!(n?.has(a)??!1)&&s.add(a)}),s}selectPeersToPublish(e){let t=new Set,n={direct:0,floodsub:0,mesh:0,fanout:0},s=this.topics.get(e);if(s!=null)if(this.opts.floodPublish)s.forEach(o=>{this.direct.has(o)?(t.add(o),n.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),n.floodsub++)});else{this.direct.forEach(i=>{s.has(i)&&(t.add(i),n.direct++)}),this.floodsubPeers.forEach(i=>{s.has(i)&&this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),n.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(i=>{t.add(i),n.mesh++}),o.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-o.size,a=>!o.has(a)&&!this.direct.has(a)&&!this.floodsubPeers.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold).forEach(a=>{t.add(a),n.mesh++});else{let i=this.fanout.get(e);if(i!=null&&i.size>0)i.forEach(a=>{t.add(a),n.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),n.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:n}}forwardMessage(e,t,n,s){n!=null&&this.score.deliverMessage(n,e,t.topic);let o=this.selectPeersToForward(t.topic,n,s);o.forEach(i=>{this.sendRpc(i,Pr([t]))}),this.metrics?.onForwardMsg(t.topic,o.size)}async publish(e,t,n){let s=Date.now(),o=this.dataTransform!=null?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:i,msg:a}=await PT(this.publishConfig,e,t,o),c=await this.msgIdFn(a),l=this.msgIdToStrFn(c),u=n?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(l)){if(u)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:d,tosendCount:p}=this.selectPeersToPublish(e),f=this.opts.emitSelf&&this.subscriptions.has(e),h=n?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(d.size===0&&!h&&!f)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(l),this.mcache.put({msgId:c,msgIdStr:l},i,!0),this.gossipTracer.deliverMessage(l),this.publishedMessageIds.put(l);let m=n?.batchPublish??this.opts.batchPublish,g=Pr([i]);if(m)this.sendRpcInBatch(d,g);else for(let b of d)this.sendRpc(b,g)||d.delete(b);let y=Date.now()-s;return this.metrics?.onPublishMsg(e,p,d.size,i.data!=null?i.data.length:0,y),f&&(d.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:l,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(d.values()).map(b=>this.peers.get(b)??To(b))}}sendRpcInBatch(e,t){let n=Nn.encode(t),s=Oa.single(n);for(let o of e){let i=this.streamsOutbound.get(o);if(i==null){this.log(`Cannot send RPC to ${o} as there is no open stream to it available`),e.delete(o);continue}try{i.pushPrefixed(s)}catch(a){e.delete(o),this.log.error(`Cannot send rpc to ${o}`,a)}this.metrics?.onRpcSent(t,n.length)}}reportMessageValidationResult(e,t,n){let s;if(n===Mt.Accept){if(s=this.mcache.validate(e),s!=null){let{message:i,originatingPeers:a}=s;this.score.deliverMessage(t,e,i.topic),this.forwardMessage(e,s.message,t,a)}}else if(s=this.mcache.remove(e),s!=null){let i=Zw(n),{message:a,originatingPeers:c}=s;this.score.rejectMessage(t,e,a.topic,i);for(let l of c)this.score.rejectMessage(l,e,a.topic,i)}let o=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(s,n,o)}sendGraft(e,t){let s=Pr([],{graft:[{topicID:t}]});this.sendRpc(e,s)}async sendPrune(e,t){let s=[await this.makePrune(e,t,this.opts.doPX,!0)],o=Pr([],{prune:s});this.sendRpc(e,o)}sendIDontWants(e,t,n){let s=this.mesh.get(t);if(s==null)return;let o=new Set(s);o.delete(n);for(let a of o)this.streamsOutbound.get(a)?.protocol!==_1&&o.delete(a);let i=Pr([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(o,i)}sendRpc(e,t){let n=this.streamsOutbound.get(e);if(n==null)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let s=this.control.get(e);s!=null&&(this.piggybackControl(e,t,s),this.control.delete(e));let o=this.gossip.get(e);o!=null&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let i=Nn.encode(t);try{n.push(i)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),s!=null&&this.control.set(e,s),o!=null&&this.gossip.set(e,o),!1}if(this.metrics?.onRpcSent(t,i.length),t.control?.graft!=null)for(let a of t.control?.graft)a.topicID!=null&&this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});if(t.control?.prune!=null)for(let a of t.control?.prune)a.topicID!=null&&this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});return!0}piggybackControl(e,t,n){let s=r6(t);for(let o of n.graft)o.topicID!=null&&(this.mesh.get(o.topicID)?.has(e)??!1)&&s.control.graft.push(o);for(let o of n.prune)o.topicID!=null&&!(this.mesh.get(o.topicID)?.has(e)??!1)&&s.control.prune.push(o)}piggybackGossip(e,t,n){let s=r6(t);s.control.ihave=n}async sendGraftPrune(e,t,n){let s=this.opts.doPX,o=!1;for(let[i,a]of e){let c=a.map(d=>({topicID:d})),l=[],u=t.get(i);u!=null&&(l=await Promise.all(u.map(async d=>this.makePrune(i,d,s&&!(n.get(i)??!1),o))),t.delete(i)),this.sendRpc(i,Pr([],{graft:c,prune:l}))}for(let[i,a]of t){let c=await Promise.all(a.map(async l=>this.makePrune(i,l,s&&!(n.get(i)??!1),o)));this.sendRpc(i,Pr([],{prune:c}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[n,s]of e)this.doEmitGossip(n,s,t.get(n)??[])}doEmitGossip(e,t,n){if(n.length===0||(on(n),n.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",n.length),t.size===0))return;let s=this.opts.Dlazy,i=this.opts.gossipFactor*t.size,a=t;i>s&&(s=i),s>a.size?s=a.size:a=on(Array.from(a)).slice(0,s),a.forEach(c=>{let l=n;n.length>5e3&&(l=on(l.slice()).slice(0,5e3)),this.pushGossip(c,{topicID:e,messageIDs:l})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,Pr([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let n=Pr([],{graft:t.graft,prune:t.prune});this.sendRpc(e,n)}}pushGossip(e,t){this.log("Add gossip to %s",e);let n=this.gossip.get(e)??[];this.gossip.set(e,n.concat(t))}async makePrune(e,t,n,s){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===Jw)return{topicID:t,peers:[]};let o=s?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=o/1e3;if(this.doAddBackoff(e,t,o),!n)return{topicID:t,peers:[],backoff:i};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,l=>l!==e&&this.score.score(l)>=0),c=await Promise.all(Array.from(a).map(async l=>{let u=this.peers.get(l)??To(l),d;try{d=await this.components.peerStore.get(u)}catch(p){if(p.name!=="NotFoundError")throw p}return{peerID:u.toMultihash().bytes,signedPeerRecord:d?.peerRecordEnvelope}}));return{topicID:t,peers:c,backoff:i}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===sr.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:n,Dscore:s,Dout:o,fanoutTTL:i}=this.opts;this.heartbeatTicks++;let a=new Map,c=h=>{let m=a.get(h);return m===void 0&&(m=this.score.score(h),a.set(h,m)),m},l=new Map,u=new Map,d=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let h of this.idontwants.values())for(let[m,g]of h)this.heartbeatTicks-g>=this.opts.mcacheLength&&h.delete(m);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let p=new Map;this.mesh.forEach((h,m)=>{let g=this.topics.get(m),y=new Set,b=new Set;if(p.set(m,b),g!=null){let v=on(Array.from(g)),S=this.backoff.get(m);for(let w of v){let I=this.streamsOutbound.get(w);if(I!=null&&this.multicodecs.includes(I.protocol)&&!h.has(w)&&!this.direct.has(w)){let A=c(w);S?.has(w)!==!0&&A>=0&&y.add(w),A>=this.opts.scoreThresholds.gossipThreshold&&b.add(w)}}}let E=(v,S)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",v,m),this.addBackoff(v,m),h.delete(v),c(v)>=this.opts.scoreThresholds.gossipThreshold&&b.add(v),this.metrics?.onRemoveFromMesh(m,S,1);let w=u.get(v);w==null?u.set(v,[m]):w.push(m)},x=(v,S)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",v,m),this.score.graft(v,m),h.add(v),b.delete(v),this.metrics?.onAddToMesh(m,S,1);let w=l.get(v);w==null?l.set(v,[m]):w.push(m)};if(h.forEach(v=>{let S=c(v);S<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",v,S,m),E(v,_r.BadScore),d.set(v,!0))}),h.size<t){let v=e-h.size;ET(y,v).forEach(w=>{x(w,Rt.NotEnough)})}if(h.size>n){let v=Array.from(h);v.sort((w,I)=>c(I)-c(w)),v=v.slice(0,s).concat(on(v.slice(s)));let S=0;if(v.slice(0,e).forEach(w=>{(this.outbound.get(w)??!1)&&S++}),S<o){let w=A=>{let G=v[A];for(let J=A;J>0;J--)v[J]=v[J-1];v[0]=G};if(S>0){let A=S;for(let G=1;G<e&&A>0;G++)(this.outbound.get(v[G])??!1)&&(w(G),A--)}let I=e-S;for(let A=e;A<v.length&&I>0;A++)(this.outbound.get(v[A])??!1)&&(w(A),I--)}v.slice(e).forEach(w=>{E(w,_r.Excess)})}if(h.size>=t){let v=0;if(h.forEach(S=>{(this.outbound.get(S)??!1)&&v++}),v<o){let S=o-v;k1(y,S,I=>this.outbound.get(I)===!0).forEach(I=>{x(I,Rt.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&h.size>1){let v=Array.from(h).sort((I,A)=>c(I)-c(A)),S=Math.floor(h.size/2),w=c(v[S]);if(w<this.opts.scoreThresholds.opportunisticGraftThreshold){let I=this.opts.opportunisticGraftPeers,A=k1(y,I,G=>c(G)>w);for(let G of A)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",G,m),x(G,Rt.Opportunistic)}}});let f=Date.now();this.fanoutLastpub.forEach((h,m)=>{h+i<f&&(this.fanout.delete(m),this.fanoutLastpub.delete(m))}),this.fanout.forEach((h,m)=>{let g=this.topics.get(m);h.forEach(x=>{(!(g?.has(x)??!1)||c(x)<this.opts.scoreThresholds.publishThreshold)&&h.delete(x)});let y=this.topics.get(m),b=[],E=new Set;if(p.set(m,E),y!=null){let x=on(Array.from(y));for(let v of x){let S=this.streamsOutbound.get(v);if(S!=null&&this.multicodecs.includes(S.protocol)&&!h.has(v)&&!this.direct.has(v)){let w=c(v);w>=this.opts.scoreThresholds.publishThreshold&&b.push(v),w>=this.opts.scoreThresholds.gossipThreshold&&E.add(v)}}}if(h.size<e){let x=e-h.size;b.slice(0,x).forEach(v=>{h.add(v),E?.delete(v)})}}),this.emitGossip(p),await this.sendGraftPrune(l,u,d),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,n=()=>!0){let s=this.topics.get(e);if(s==null)return new Set;let o=[];return s.forEach(i=>{let a=this.streamsOutbound.get(i);a!=null&&this.multicodecs.includes(a.protocol)&&n(i)&&o.push(i)}),o=on(o),t>0&&o.length>t&&(o=o.slice(0,t)),new Set(o)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,n=Date.now();e.connectedPeersBackoffSec.reset();for(let c of this.backoff.values()){t+=c.size;for(let[l,u]of c.entries())this.peers.has(l)&&e.connectedPeersBackoffSec.observe(Math.max(0,u-n)/1e3)}e.cacheSize.set({cache:"backoff"},t);let s=0;for(let c of this.idontwants.values())s+=c.size;e.cacheSize.set({cache:"idontwants"},s);for(let[c,l]of this.topics)e.topicPeersCount.set({topicStr:c},l.size);for(let[c,l]of this.mesh)e.meshPeerCounts.set({topicStr:c},l.size);let o=[],i=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let l=this.score.score(c);o.push(l),i.set(c,l),e.behaviourPenalty.observe(this.score.peerStats.get(c)?.behaviourPenalty??0)}e.registerScores(o,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let a=TT(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:n}=e.detail;this.components.peerStore.merge(this.peers.get(t)??To(t),{tags:{[n]:{value:100}}}).catch(s=>{this.log.error("Error tagging peer %s with topic %s",t,n,s)})};untagMeshPeer=e=>{let{peerId:t,topic:n}=e.detail;this.components.peerStore.merge(this.peers.get(t)??To(t),{tags:{[n]:void 0}}).catch(s=>{this.log.error("Error untagging peer %s with topic %s",t,n,s)})}};function r_(r={}){return e=>new C6(e,r)}var cG="bootstrap",lG=50,uG=1e3,T6=class extends he{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??uG,this.list=t.list.map(n=>H(n)).filter(n=>zd.matches(n)?n.getComponents().findLast(o=>o.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:oe(n.getComponents().findLast(s=>s.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[Wa]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[je]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??cG]:{value:this._init.tagValue??lG,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function n_(r){return e=>new T6(e,r)}var z1=class{components;running=!1;log;cfg;readyPromise=null;coordinatorCache=new Map;clusterCache=new Map;lastEstimate=null;blacklist=new Map;libp2pRef;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("db-p2p:network-manager"),this.cfg={clusterSize:t.clusterSize??1,seedKeys:t.seedKeys??[],estimation:t.estimation??{samples:8,kth:5,timeoutMs:1e3,ttlMs:6e4},readiness:t.readiness??{minPeers:1,maxWaitMs:2e3},cacheTTLs:t.cacheTTLs??{coordinatorMs:30*6e4,clusterMs:5*6e4},expectedRemotes:t.expectedRemotes??!1,allowClusterDownsize:t.allowClusterDownsize??!0,clusterSizeTolerance:t.clusterSizeTolerance??.5}}setLibp2p(e){this.libp2pRef=e}getLibp2p(){return this.libp2pRef??this.components.libp2p}getFret(){let e=this.getLibp2p();if(e)return e.services?.fret}get[Symbol.toStringTag](){return"@libp2p/network-manager"}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}async ready(){return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{let t=(await Promise.allSettled((this.cfg.seedKeys??[]).map(n=>this.seedKey(n)))).filter(n=>n.status==="rejected");t.length>0&&this.log("Failed to seed %d keys",t.length),await new Promise(n=>setTimeout(n,50))})(),this.readyPromise)}async seedKey(e){let t=this.getFret();if(!t)throw new Error("FRET service not available for seeding keys");let n=await Yt(e),s=t.getNeighbors(n,"both",1)}toCacheKey(e){return C(e,"base64url")}getKnownPeers(){let e=this.getLibp2p();if(!e)return[];let t=e.peerId,n=e.peerStore?.getPeers?.()??[],s=(e.getConnections?.()??[]).map(a=>a.remotePeer),o=[...n.map(a=>a.id),...s];return o.filter((a,c)=>o.findIndex(l=>l.toString()===a.toString())===c).filter(a=>a.toString()!==t.toString())}getStatus(){let e=this.getLibp2p();if(!e)return{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0};let n=(e.peerStore?.getPeers?.()??[]).filter(s=>s.id.toString()!==e.peerId.toString()).length;return n===0?{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0}:{mode:"healthy",connections:n}}async awaitHealthy(e,t){let n=Date.now();for(;Date.now()-n<t;){let o=this.getLibp2p();if(o){let i=o.getConnections?.()??[],a=new Set(i.map(c=>c.remotePeer.toString()));if(a.size>=e)return this.log("awaitHealthy: satisfied with %d connections",a.size),!0}await new Promise(i=>setTimeout(i,100))}let s=this.getLibp2p();if(s){let o=s.getConnections?.()??[],i=new Set(o.map(c=>c.remotePeer.toString())),a=i.size>=e;return this.log("awaitHealthy: timeout - %d connections (needed %d)",i.size,e),a}return!1}reportBadPeer(e,t=1,n=10*6e4){let s=e.toString(),i=(this.blacklist.get(s)?.score??0)+Math.max(1,t);this.blacklist.set(s,{score:i,expires:Date.now()+n})}isBlacklisted(e){let t=e.toString(),n=this.blacklist.get(t);return n?n.expires<=Date.now()?(this.blacklist.delete(t),!1):n.score>=3:!1}recordCoordinator(e,t){let n=this.toCacheKey(e);this.coordinatorCache.set(n,{id:t,expires:Date.now()+this.cfg.cacheTTLs.coordinatorMs})}async findNearestPeerToKey(e){let t=this.getFret(),n=this.getLibp2p();if(!n)throw new Error("Libp2p not initialized");if(t){let a=await Yt(e),c=t.getNeighbors(a,"both",1);if(c.length>0){let l=c[0];if(l){let u=oe(l);if(!this.isBlacklisted(u))return u}}}let s=(n.getConnections?.()??[]).map(a=>a.remotePeer),o=[n.peerId,...s,...this.getKnownPeers()].filter((a,c,l)=>l.findIndex(u=>u.toString()===a.toString())===c).filter(a=>!this.isBlacklisted(a));return o.length===0?n.peerId:o.reduce((a,c)=>this.lexLess(this.xor(a.toMultihash().bytes,e),this.xor(c.toMultihash().bytes,e))?a:c,o[0])}async getCluster(e){let t=this.toCacheKey(e),n=this.clusterCache.get(t);if(n&&n.expires>Date.now())return n.ids;let s=this.getFret(),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");if(s){let f=await Yt(e),h=s.getDiagnostics?.()??{},m=typeof h.estimate=="number"?h.estimate:typeof h.n=="number"?h.n:void 0,g=Math.max(1,Math.min(this.cfg.clusterSize,Number.isFinite(m)?m:this.cfg.clusterSize)),b=s.assembleCohort(f,g).map(E=>{try{return oe(E)}catch(x){return this.log("Invalid peer ID in cohort: %s, %o",E,x),null}}).filter(E=>E!==null&&!this.isBlacklisted(E));if(b.length>0)return this.clusterCache.set(t,{ids:b,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),this.lastEstimate=m!=null?{estimate:m,samples:h.samples??0,updated:Date.now()}:this.lastEstimate,b}let i=await this.findNearestPeerToKey(e),a=i.toMultihash().bytes,c=(o.getConnections?.()??[]).map(f=>f.remotePeer),u=[i,o.peerId,...c,...this.getKnownPeers()].filter((f,h,m)=>!this.isBlacklisted(f)&&m.findIndex(g=>g.toString()===f.toString())===h).sort((f,h)=>this.lexLess(this.xor(f.toMultihash().bytes,a),this.xor(h.toMultihash().bytes,a))?-1:1),d=Math.min(this.cfg.clusterSize,u.length),p=u.slice(0,d);return this.clusterCache.set(t,{ids:p,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),p}async getCoordinator(e){let t=this.toCacheKey(e),n=this.coordinatorCache.get(t);if(n){if(n.expires>Date.now())return n.id;this.coordinatorCache.delete(t)}let s=await this.getCluster(e),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");let i=s.find(a=>!this.isBlacklisted(a))??o.peerId;return this.recordCoordinator(e,i),i}xor(e,t){let n=Math.max(e.length,t.length),s=new Uint8Array(n);for(let o=0;o<n;o++){let i=e[e.length-1-o]??0,a=t[t.length-1-o]??0;s[n-1-o]=i^a}return s}lexLess(e,t){let n=Math.max(e.length,t.length);for(let s=0;s<n;s++){let o=e[s]??0,i=t[s]??0;if(o<i)return!0;if(o>i)return!1}return!1}};function _6(r={}){return e=>new z1(e,r)}var $1=class{peerStatuses=new Map;unreachableThreshold=3;rapidChurnThreshold=5;rapidChurnWindow=1e4;peerTimeoutMs=6e4;recordSuccess(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastSeen=t,n.consecutiveFailures=0):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:0}),this.cleanupOldPeers()}recordFailure(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.consecutiveFailures++,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:1})}recordGoodbye(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastGoodbye=t,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,lastGoodbye:t,consecutiveFailures:0})}detectPartition(){let e=Date.now(),t=this.getRecentGoodbyes(this.rapidChurnWindow),n=Array.from(this.peerStatuses.values()).filter(o=>o.consecutiveFailures>=this.unreachableThreshold&&!o.lastGoodbye);return t.length+n.length>=this.rapidChurnThreshold}getUnreachablePeers(){return Array.from(this.peerStatuses.values()).filter(e=>e.consecutiveFailures>=this.unreachableThreshold&&!e.lastGoodbye).map(e=>e.peerId)}getRecentGoodbyes(e){let t=Date.now()-e;return Array.from(this.peerStatuses.values()).filter(n=>n.lastGoodbye&&n.lastGoodbye>t)}cleanupOldPeers(){let e=Date.now()-this.peerTimeoutMs;for(let[t,n]of this.peerStatuses.entries())n.lastSeen<e&&this.peerStatuses.delete(t)}getStatistics(){let e=this.getUnreachablePeers().length,t=this.getRecentGoodbyes(this.rapidChurnWindow).length;return{totalPeers:this.peerStatuses.size,unreachable:e,recentGoodbyes:t}}reset(){this.peerStatuses.clear()}};function hG(r){return r?typeof r=="function"?r():r:new Hc}async function s_(r,e){let t=hG(r.storage),n=async(S,w)=>{},s=new qc(S=>new yi(S,t,n)),o,i,a={async update(S){if(!o)throw new Error("ClusterMember not initialized");return await o.update(S)}},c={async get(S,w){return await(i??s).get(S,w)},async pend(S,w){return await(i??s).pend(S,w)},async cancel(S,w){return await(i??s).cancel(S,w)},async commit(S,w){return await(i??s).commit(S,w)}},l=r.id?await oe(r.id):void 0,u=r.listenAddrs??e.listenAddrs,d=r.transports??e.transports,p={start:!1,...l?{peerId:l}:{},addresses:{listen:u},connectionManager:{autoDial:!0,minConnections:1,maxConnections:16,inboundConnectionUpgradeTimeout:1e4,dialQueue:{concurrency:2,attempts:2}},transports:d,connectionEncrypters:[sC()],streamMuxers:[dC()],services:{identify:yC({protocolPrefix:`/optimystic/${r.networkName}`}),ping:SC(),pubsub:r_({allowPublishToZeroTopicPeers:!0,heartbeatInterval:7e3}),...r.relay?{relay:HI()}:{},cluster:S=>F2({protocolPrefix:`/optimystic/${r.networkName}`,configuredClusterSize:r.clusterSize??10,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5,responsibilityK:r.responsibilityK??1})({logger:S.logger,registrar:S.registrar,cluster:a}),repo:S=>H2({protocolPrefix:`/optimystic/${r.networkName}`,responsibilityK:r.responsibilityK??1})({logger:S.logger,registrar:S.registrar,repo:c}),sync:S=>ey({protocolPrefix:`/optimystic/${r.networkName}`})({logger:S.logger,registrar:S.registrar,repo:c}),networkManager:S=>{let I=_6({clusterSize:r.clusterSize??10,expectedRemotes:(r.bootstrapNodes?.length??0)>0,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})(S);try{I.setLibp2p?.(S.libp2p)}catch{}return I},fret:S=>{let I=Zg({k:15,m:8,capacity:2048,profile:r.fretProfile??((r.bootstrapNodes?.length??0)>0?"core":"edge"),networkName:r.networkName,bootstraps:r.bootstrapNodes??[]})(S);try{I.setLibp2p(S.libp2p)}catch{}return I}},peerDiscovery:[...r.bootstrapNodes?.length?[n_({list:r.bootstrapNodes})]:[]]},f=await f8(p);try{f.services?.fret?.setLibp2p?.(f)}catch{}try{f.services?.networkManager?.setLibp2p?.(f)}catch{}await f.start();let h=new Sl(f),m=`/optimystic/${r.networkName}`,g=S=>Ks.create(S,h,m),y=new $1,b=f.services?.fret;o=K2({storageRepo:s,peerNetwork:h,peerId:f.peerId,protocolPrefix:m,partitionDetector:y,fretService:b,validator:r.validator});let E=$2(h,g,{clusterSize:r.clusterSize??10,superMajorityThreshold:r.clusterPolicy?.superMajorityThreshold??.67,simpleMajorityThreshold:.51,minAbsoluteClusterSize:2,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5,partitionDetectionWindow:6e4},b),x=async(S,w)=>{let I=new js(S,h,m);try{let A=await I.requestBlock({blockId:w,rev:void 0});if(A.success&&A.archive){let G=Object.keys(A.archive.revisions).map(Number);if(G.length>0){let J=Math.max(...G),$=A.archive.revisions[J];if($?.action)return{actionId:$.action.actionId,rev:J}}}}catch{}};if(i=E({storageRepo:s,localCluster:o,localPeerId:f.peerId,clusterLatestCallback:x}),r.arachnode?.enableRingZulu??!0){let S=f.logger?.forComponent?.("db-p2p:arachnode"),w=f.services?.fret;if(w){let I=new ml(w),A=new pl(t,r.arachnode?.storage??{}),G=new fl(I,A,{minCapacity:100*1024*1024,thresholds:{moveOut:.85,moveIn:.4}}),J=f.peerId.toString(),$=await G.createArachnodeInfo(J);I.setArachnodeInfo($),S?.("Announced Arachnode membership: Ring %d",$.ringDepth);let k=new dl(I,{connect:(M,O)=>f.dialProtocol(M,[O])},`/optimystic/${r.networkName}`),_=async(M,O)=>await k.restore(M,O);s.createBlockStorage=M=>new yi(M,t,_);let T=setInterval(async()=>{let M=await G.shouldTransition();if(M.shouldMove){S?.("Ring transition needed: moving %s to Ring %d",M.direction,M.newRingDepth);let O=await G.createArachnodeInfo(J);I.setArachnodeInfo(O)}},6e4),L=f.stop.bind(f);f.stop=async()=>{clearInterval(T),await L()}}else S?.("FRET service not available, Arachnode disabled")}return f.coordinatedRepo=i,f.storageRepo=s,f.keyNetwork=h,f}async function dG(r){let e=r.port??0;return await s_(r,{listenAddrs:[`/ip4/0.0.0.0/tcp/${e}`],transports:[YS(),qI()]})}function o_(r,e){let t=Math.max(r.length,e.length),n=new Uint8Array(t);for(let s=0;s<t;s++){let o=r[r.length-1-s]??0,i=e[e.length-1-s]??0;n[t-1-s]=o^i}return n}function i_(r,e){let t=Math.max(r.length,e.length);for(let n=0;n<t;n++){let s=r[n]??0,o=e[n]??0;if(s<o)return!0;if(s>o)return!1}return!1}function a_(r,e){return r.map(t=>({p:t,d:o_(t.id.toMultihash().bytes,e)})).sort((t,n)=>i_(t.d,n.d)?-1:1).map(t=>t.p)}function fG(r,e,t,n){let s=[e,...t],o=a_(s,r);if(s.length<=3)return{inCluster:o[0].id.equals(e.id),nearest:o};let i=Math.min(n,Math.max(1,Math.floor(s.length/2))),a=o.slice(0,i);return{inCluster:a.some(l=>l.id.equals(e.id)),nearest:a}}function pG(r){let e={id:r.peerId,addrs:r.getMultiaddrs().map(o=>o.toString())},t=r.getConnections(),n={};for(let o of t){let i=o.remotePeer,a=i.toString(),c=n[a]??(n[a]={id:i,addrs:new Set}),l=o.remoteAddr?.toString?.();l&&c.addrs.add(l)}let s=Object.values(n).map(o=>({id:o.id,addrs:Array.from(o.addrs)}));return[e,...s]}var mG=ur("network:get-manager");function gG(r){let e=r.services?.networkManager;if(e==null)throw new Error("networkManager service is not registered on this libp2p node");try{e.setLibp2p?.(r)}catch(t){mG("getNetworkManager setLibp2p failed - %o",t)}return e}return M6(yG);})();
35
35
  /*! Bundled license information:
36
36
 
37
37
  @noble/hashes/utils.js: