@optimystic/db-p2p 0.0.1 → 0.1.1

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,31 +1,31 @@
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 aE=Object.create;var Xc=Object.defineProperty;var cE=Object.getOwnPropertyDescriptor;var lE=Object.getOwnPropertyNames;var uE=Object.getPrototypeOf,hE=Object.prototype.hasOwnProperty;var re=(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 A=(r,e)=>()=>(r&&(e=r(r=0)),e);var He=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ve=(r,e)=>{for(var t in e)Xc(r,t,{get:e[t],enumerable:!0})},gg=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lE(e))!hE.call(r,n)&&n!==t&&Xc(r,n,{get:()=>e[n],enumerable:!(s=cE(e,n))||s.enumerable});return r};var we=(r,e,t)=>(t=r!=null?aE(uE(r)):{},gg(e||!r||!r.__esModule?Xc(t,"default",{value:r,enumerable:!0}):t,r)),dE=r=>gg(Xc({},"__esModule",{value:!0}),r);function Bs(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}var ra=A(()=>{});function ie(r=0){return Bs(pd.Buffer.alloc(r))}function je(r=0){return Bs(pd.Buffer.allocUnsafe(r))}var pd,nt=A(()=>{pd=re("node:buffer");ra()});function Le(r){if(r<vE)return 1;if(r<EE)return 2;if(r<SE)return 3;if(r<md)return 4;if(r<gd)return 5;if(r<yd)return 6;if(r<bd)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ko(r,e,t=0){switch(Le(r)){case 8:e[t++]=r&255|pe,r/=128;case 7:e[t++]=r&255|pe,r/=128;case 6:e[t++]=r&255|pe,r/=128;case 5:e[t++]=r&255|pe,r/=128;case 4:e[t++]=r&255|pe,r>>>=7;case 3:e[t++]=r&255|pe,r>>>=7;case 2:e[t++]=r&255|pe,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function IE(r,e,t=0){switch(Le(r)){case 8:e.set(t++,r&255|pe),r/=128;case 7:e.set(t++,r&255|pe),r/=128;case 6:e.set(t++,r&255|pe),r/=128;case 5:e.set(t++,r&255|pe),r/=128;case 4:e.set(t++,r&255|pe),r>>>=7;case 3:e.set(t++,r&255|pe),r>>>=7;case 2:e.set(t++,r&255|pe),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function wd(r,e){let t=r[e],s=0;if(s+=t&bt,t<pe||(t=r[e+1],s+=(t&bt)<<7,t<pe)||(t=r[e+2],s+=(t&bt)<<14,t<pe)||(t=r[e+3],s+=(t&bt)<<21,t<pe)||(t=r[e+4],s+=(t&bt)*md,t<pe)||(t=r[e+5],s+=(t&bt)*gd,t<pe)||(t=r[e+6],s+=(t&bt)*yd,t<pe)||(t=r[e+7],s+=(t&bt)*bd,t<pe))return s;throw new RangeError("Could not decode varint")}function _E(r,e){let t=r.get(e),s=0;if(s+=t&bt,t<pe||(t=r.get(e+1),s+=(t&bt)<<7,t<pe)||(t=r.get(e+2),s+=(t&bt)<<14,t<pe)||(t=r.get(e+3),s+=(t&bt)<<21,t<pe)||(t=r.get(e+4),s+=(t&bt)*md,t<pe)||(t=r.get(e+5),s+=(t&bt)*gd,t<pe)||(t=r.get(e+6),s+=(t&bt)*yd,t<pe)||(t=r.get(e+7),s+=(t&bt)*bd,t<pe))return s;throw new RangeError("Could not decode varint")}function rr(r,e,t=0){return e==null&&(e=je(Le(r))),e instanceof Uint8Array?ko(r,e,t):IE(r,e,t)}function as(r,e=0){return r instanceof Uint8Array?wd(r,e):_E(r,e)}var vE,EE,SE,md,gd,yd,bd,pe,bt,wr=A(()=>{nt();vE=Math.pow(2,7),EE=Math.pow(2,14),SE=Math.pow(2,21),md=Math.pow(2,28),gd=Math.pow(2,35),yd=Math.pow(2,42),bd=Math.pow(2,49),pe=128,bt=127});function Ye(r,e){return Bs(wg.Buffer.concat(r,e))}var wg,Kr=A(()=>{wg=re("node:buffer");ra()});function ae(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 Kt=A(()=>{});function xg(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let s of r){let n=t+s.byteLength;if(e<n)return{buf:s,index:e-t};t=n}throw new RangeError("index is out of bounds")}function el(r){return!!r?.[vg]}var vg,W,ot=A(()=>{nt();Kr();Kt();vg=Symbol.for("@achingbrain/uint8arraylist");W=class r{bufs;length;[vg]=!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 s of e)if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.push(s);else if(el(s))t+=s.byteLength,this.bufs.push(...s.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 s of e.reverse())if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.unshift(s);else if(el(s))t+=s.byteLength,this.bufs.unshift(...s.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=xg(this.bufs,e);return t.buf[t.index]}set(e,t){let s=xg(this.bufs,e);s.buf[s.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let s=0;s<e.length;s++)this.set(t+s,e[s]);else if(el(e))for(let s=0;s<e.length;s++)this.set(t+s,e.get(s));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:s,length:n}=this._subList(e,t);return Ye(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:Ye(s,n)}sublist(e,t){let{bufs:s,length:n}=this._subList(e,t),o=new r;return o.length=n,o.bufs=[...s],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 s=[],n=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=n,c=a+i.byteLength;if(n=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){s.push(i);break}let h=e-a;s.push(i.subarray(h,h+(t-e)));break}if(l){if(e===0){s.push(i);continue}s.push(i.subarray(e-a));continue}if(u){if(t===c){s.push(i);break}s.push(i.subarray(0,t-a));break}s.push(i)}return{bufs:s,length:t-e}}indexOf(e,t=0){if(!el(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let s=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 n=s.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<n;h++)i[s[h]]=h;let a=i,c=this.byteLength-s.byteLength,l=s.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let d=l;d>=0;d--){let f=this.get(h+d);if(s[d]!==f){u=Math.max(1,d-a[f]);break}}if(u===0)return h}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 s=je(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt8(0,t),this.write(s,e)}getInt16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt16(0,t)}setInt16(e,t,s){let n=ie(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,s),this.write(n,e)}getInt32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt32(0,t)}setInt32(e,t,s){let n=ie(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,s),this.write(n,e)}getBigInt64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigInt64(0,t)}setBigInt64(e,t,s){let n=ie(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,s),this.write(n,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 s=je(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint8(0,t),this.write(s,e)}getUint16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint16(0,t)}setUint16(e,t,s){let n=ie(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,s),this.write(n,e)}getUint32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint32(0,t)}setUint32(e,t,s){let n=ie(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,s),this.write(n,e)}getBigUint64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0,t)}setBigUint64(e,t,s){let n=ie(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,s),this.write(n,e)}getFloat32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat32(0,t)}setFloat32(e,t,s){let n=ie(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,s),this.write(n,e)}getFloat64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat64(0,t)}setFloat64(e,t,s){let n=ie(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,s),this.write(n,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(!ae(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let s=new r;return s.bufs=e,t==null&&(t=e.reduce((n,o)=>n+o.byteLength,0)),s.length=t,s}}});var T9,Sg=A(()=>{T9=Symbol.for("@libp2p/connection")});var Ig=A(()=>{});var _g=A(()=>{});var Ag=A(()=>{});var k9,Cg=A(()=>{k9=Symbol.for("@libp2p/content-routing")});var Ge,Mo,oa,Oo,Tg=A(()=>{Ge=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"}},oa=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},Oo=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});var Pg=A(()=>{});var kg=A(()=>{});var Dg=A(()=>{});var Mg=A(()=>{});var Og=A(()=>{});var R9,Lg=A(()=>{R9=Symbol.for("@libp2p/peer-discovery")});var B9,Rg=A(()=>{B9=Symbol.for("@libp2p/peer-id")});var Ng=A(()=>{});var U9,Bg=A(()=>{U9=Symbol.for("@libp2p/peer-routing")});var Fg=A(()=>{});var Ug=A(()=>{});var Kg=A(()=>{});var Hg=A(()=>{});var zg=A(()=>{});var qg=A(()=>{});var $g=A(()=>{});var q9,Gg,Vg=A(()=>{q9=Symbol.for("@libp2p/transport");(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Gg||(Gg={}))});var Wg,J,jg=A(()=>{Wg=re("node:events"),J=(r,...e)=>{try{(0,Wg.setMaxListeners)(r,...e)}catch{}}});var Xe,Ze=A(()=>{jg();Xe=class extends EventTarget{#e=new Map;constructor(){super(),J(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,s){super.addEventListener(e,t,s);let n=this.#e.get(e);n==null&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(s!==!0&&s!==!1&&s?.once)??!1})}removeEventListener(e,t,s){super.removeEventListener(e.toString(),t??null,s);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:o})=>o!==t),this.#e.set(e,n))}dispatchEvent(e){let t=super.dispatchEvent(e),s=this.#e.get(e.type);return s==null||(s=s.filter(({once:n})=>!n),this.#e.set(e.type,s)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}});var j9,Y9,Us=A(()=>{Sg();Ig();_g();Ag();Cg();Tg();Pg();kg();Dg();Mg();Og();Lg();Rg();Ng();Bg();Fg();Ug();Kg();Hg();zg();qg();$g();Vg();Ze();j9=Symbol.for("@libp2p/service-capabilities"),Y9=Symbol.for("@libp2p/service-dependencies")});function Yg(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")}function Xg(r){return new TextEncoder().encode(r)}function Zg(r){return new TextDecoder().decode(r)}var vD,ls=A(()=>{vD=new Uint8Array(0)});function PE(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var n=0;n<r.length;n++){var o=r.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,w=p.length;y!==w&&p[y]===0;)y++,m++;for(var b=(w-y)*u+1>>>0,x=new Uint8Array(b);y!==w;){for(var E=p[y],P=0,T=b-1;(E!==0||P<g)&&T!==-1;T--,P++)E+=256*x[T]>>>0,x[T]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");g=P,y++}for(var D=b-g;D!==b&&x[D]===0;)D++;for(var v=c.repeat(m);D<b;++D)v+=r.charAt(x[D]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var w=(p.length-m)*l+1>>>0,b=new Uint8Array(w);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var E=0,P=w-1;(x!==0||E<y)&&P!==-1;P--,E++)x+=a*b[P]>>>0,b[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=E,m++}if(p[m]!==" "){for(var T=w-y;T!==w&&b[T]===0;)T++;for(var D=new Uint8Array(g+(w-T)),v=g;T!==w;)D[v++]=b[T++];return D}}}function f(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var kE,DE,Jg,e3=A(()=>{kE=PE,DE=kE,Jg=DE});function t3(r,e){return new Id({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Lo({name:r,prefix:e,encode:t,decode:s}){return new _d(r,e,t,s)}function Ks({name:r,prefix:e,alphabet:t}){let{encode:s,decode:n}=Jg(t,r);return Lo({prefix:e,name:r,encode:s,decode:o=>nr(n(o))})}function ME(r,e,t,s){let n=r.length;for(;r[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,c=0;for(let l=0;l<n;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${s} 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 OE(r,e,t){let s=e[e.length-1]==="=",n=(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[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),s)for(;(o.length*t&7)!==0;)o+="=";return o}function LE(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:s}){let n=LE(s);return Lo({prefix:e,name:r,encode(o){return OE(o,s,t)},decode(o){return ME(o,n,t,r)}})}var Ed,Sd,Id,_d,xr=A(()=>{ls();e3();Ed=class{name;prefix;baseEncode;constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Sd=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,s){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=s}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 t3(this,e)}},Id=class{decoders;constructor(e){this.decoders=e}or(e){return t3(this,e)}decode(e){let t=e[0],s=this.decoders[t];if(s!=null)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};_d=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new Ed(e,t,s),this.decoder=new Sd(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var Ad={};ve(Ad,{base58btc:()=>me,base58flickr:()=>RE});var me,RE,Vt=A(()=>{xr();me=Ks({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),RE=Ks({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var Cd={};ve(Cd,{base32:()=>or,base32hex:()=>UE,base32hexpad:()=>HE,base32hexpadupper:()=>zE,base32hexupper:()=>KE,base32pad:()=>BE,base32padupper:()=>FE,base32upper:()=>NE,base32z:()=>qE});var or,NE,BE,FE,UE,KE,HE,zE,qE,Ro=A(()=>{xr();or=Re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),NE=Re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),BE=Re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),FE=Re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),UE=Re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),KE=Re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),HE=Re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zE=Re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),qE=Re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Td={};ve(Td,{base36:()=>ia,base36upper:()=>$E});var ia,$E,Pd=A(()=>{xr();ia=Ks({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),$E=Ks({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});function n3(r,e,t){e=e||[],t=t||0;for(var s=t;r>=jE;)e[t++]=r&255|r3,r/=128;for(;r&WE;)e[t++]=r&255|r3,r>>>=7;return e[t]=r|0,n3.bytes=t-s+1,e}function kd(r,s){var t=0,s=s||0,n=0,o=s,i,a=r.length;do{if(o>=a)throw kd.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=n<28?(i&s3)<<n:(i&s3)*Math.pow(2,n),n+=7}while(i>=XE);return kd.bytes=o-s,t}var GE,r3,VE,WE,jE,YE,XE,s3,ZE,QE,JE,eS,tS,rS,sS,nS,oS,iS,aS,cS,aa,o3=A(()=>{GE=n3,r3=128,VE=127,WE=~VE,jE=Math.pow(2,31);YE=kd,XE=128,s3=127;ZE=Math.pow(2,7),QE=Math.pow(2,14),JE=Math.pow(2,21),eS=Math.pow(2,28),tS=Math.pow(2,35),rS=Math.pow(2,42),sS=Math.pow(2,49),nS=Math.pow(2,56),oS=Math.pow(2,63),iS=function(r){return r<ZE?1:r<QE?2:r<JE?3:r<eS?4:r<tS?5:r<rS?6:r<sS?7:r<nS?8:r<oS?9:10},aS={encode:GE,decode:YE,encodingLength:iS},cS=aS,aa=cS});function ca(r,e=0){return[aa.decode(r,e),aa.decode.bytes]}function No(r,e,t=0){return aa.encode(r,e,t),e}function Bo(r){return aa.encodingLength(r)}var al=A(()=>{o3()});function Hr(r,e){let t=e.byteLength,s=Bo(r),n=s+Bo(t),o=new Uint8Array(n+t);return No(r,o,0),No(t,o,s),o.set(e,n),new Fo(r,t,e,o)}function Ht(r){let e=nr(r),[t,s]=ca(e),[n,o]=ca(e.subarray(s)),i=e.subarray(s+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new Fo(t,n,i,e)}function i3(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Yg(r.bytes,t.bytes)}}var Fo,ir=A(()=>{ls();al();Fo=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}}});var Dd=A(()=>{});function a3(r,e){let{bytes:t,version:s}=r;switch(s){case 0:return uS(t,Md(r),e??me.encoder);default:return hS(t,Md(r),e??or.encoder)}}function Md(r){let e=c3.get(r);if(e==null){let t=new Map;return c3.set(r,t),t}return e}function lS(r,e){switch(r[0]){case"Q":{let t=e??me;return[me.prefix,t.decode(`${me.prefix}${r}`)]}case me.prefix:{let t=e??me;return[me.prefix,t.decode(r)]}case or.prefix:{let t=e??or;return[or.prefix,t.decode(r)]}case ia.prefix:{let t=e??ia;return[ia.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 uS(r,e,t){let{prefix:s}=t;if(s!==me.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(s);if(n==null){let o=t.encode(r).slice(1);return e.set(s,o),o}else return n}function hS(r,e,t){let{prefix:s}=t,n=e.get(s);if(n==null){let o=t.encode(r);return e.set(s,o),o}else return n}function l3(r,e,t){let s=Bo(r),n=s+Bo(e),o=new Uint8Array(n+t.byteLength);return No(r,o,0),No(e,o,s),o.set(t,n),o}var c3,De,la,dS,fS,zr=A(()=>{Ro();Pd();Vt();ls();ir();al();Dd();c3=new WeakMap;De=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=n,this["/"]=n}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!==la)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==dS)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,s=Hr(e,t);return r.createV1(this.code,s)}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 s=t;return s!=null&&e.code===s.code&&e.version===s.version&&i3(e.multihash,s.multihash)}toString(e){return a3(this,e)}toJSON(){return{"/":a3(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:s,code:n,multihash:o,bytes:i}=t;return new r(s,n,o,i??l3(s,n,o.bytes))}else if(t[fS]===!0){let{version:s,multihash:n,code:o}=t,i=Ht(n);return r.create(s,o,i)}else return null}static create(e,t,s){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(s.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==la)throw new Error(`Version 0 CID must use dag-pb (code: ${la}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=l3(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,la,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,s]=r.decodeFirst(e);if(s.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),s=t.size-t.multihashSize,n=nr(e.subarray(s,s+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new Fo(t.multihashCode,t.digestSize,o,n);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,s=()=>{let[h,d]=ca(e.subarray(t));return t+=d,h},n=s(),o=la;if(n===18?(n=0,t=0):o=s(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=s(),c=s(),l=t+c,u=l-i;return{version:n,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[s,n]=lS(e,t),o=r.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Md(o).set(s,e),o}};la=112,dS=18;fS=Symbol.for("@ipld/js-cid/CID")});var Od={};ve(Od,{identity:()=>Er});function mS(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 Hr(u3,h3(r))}var u3,pS,h3,Er,pn=A(()=>{ls();ir();u3=0,pS="identity",h3=nr;Er={code:u3,name:pS,encode:h3,digest:mS}});var Ld={};ve(Ld,{base10:()=>gS});var gS,d3=A(()=>{xr();gS=Ks({prefix:"9",name:"base10",alphabet:"0123456789"})});var Rd={};ve(Rd,{base16:()=>yS,base16upper:()=>bS});var yS,bS,f3=A(()=>{xr();yS=Re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),bS=Re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var Nd={};ve(Nd,{base2:()=>wS});var wS,p3=A(()=>{xr();wS=Re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var Bd={};ve(Bd,{base256emoji:()=>IS});function ES(r){return r.reduce((e,t)=>(e+=xS[t],e),"")}function SS(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=vS[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var m3,xS,vS,IS,g3=A(()=>{xr();m3=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}"),xS=m3.reduce((r,e,t)=>(r[t]=e,r),[]),vS=m3.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);IS=Lo({prefix:"\u{1F680}",name:"base256emoji",encode:ES,decode:SS})});var Kd={};ve(Kd,{base64:()=>Fd,base64pad:()=>_S,base64url:()=>Ud,base64urlpad:()=>AS});var Fd,_S,Ud,AS,cl=A(()=>{xr();Fd=Re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_S=Re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ud=Re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),AS=Re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var Hd={};ve(Hd,{base8:()=>CS});var CS,y3=A(()=>{xr();CS=Re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var zd={};ve(zd,{identity:()=>TS});var TS,b3=A(()=>{ls();xr();TS=Lo({prefix:"\0",name:"identity",encode:r=>Zg(r),decode:r=>Xg(r)})});var WD,jD,w3=A(()=>{WD=new TextEncoder,jD=new TextDecoder});var x3=A(()=>{ls()});function $d({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new qd(r,e,t,s,n)}function v3(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 Hr(e,r)}var DS,qd,Gd=A(()=>{ir();DS=20;qd=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,o){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??DS,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 s=this.encode(e);return s instanceof Uint8Array?v3(s,this.code,t?.truncate):s.then(n=>v3(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var Wd={};ve(Wd,{sha256:()=>Qe,sha512:()=>MS});var Vd,Qe,MS,us=A(()=>{Vd=we(re("crypto"),1);ls();Gd();Qe=$d({name:"sha2-256",code:18,encode:r=>nr(Vd.default.createHash("sha256").update(r).digest())}),MS=$d({name:"sha2-512",code:19,encode:r=>nr(Vd.default.createHash("sha512").update(r).digest())})});var S3=A(()=>{});var I3=A(()=>{});var _3=A(()=>{});var A3=A(()=>{});var C3=A(()=>{S3();I3();_3();Dd();A3()});var jd=A(()=>{ls();zr();ir();Gd();al();C3()});var ua,aM,Yd=A(()=>{d3();f3();p3();g3();Ro();Pd();Vt();cl();y3();b3();w3();x3();pn();us();jd();ua={...zd,...Nd,...Hd,...Ld,...Rd,...Cd,...Td,...Ad,...Kd,...Bd},aM={...Wd,...Od}});function P3(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var T3,Xd,OS,ll,Zd=A(()=>{Yd();nt();T3=P3("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Xd=P3("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=je(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),OS={utf8:T3,"utf-8":T3,hex:ua.base16,latin1:Xd,ascii:Xd,binary:Xd,...ua},ll=OS});function L(r,e="utf8"){let t=ll[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?Bs(k3.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var k3,ge=A(()=>{k3=re("node:buffer");Zd();ra()});function K(r,e="utf8"){let t=ll[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?D3.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var D3,Se=A(()=>{D3=re("node:buffer");Zd()});function hs(r,e={offset:0}){let t=r[e.offset]&LS;if(e.offset++,M3[t]!=null)return M3[t](r,e);throw new Error("No decoder for tag "+t)}function da(r,e){let t=0;if((r[e.offset]&Qd)===Qd){let s=r[e.offset]&RS,n="0x";e.offset++;for(let o=0;o<s;o++,e.offset++)n+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(n,16)}else t=r[e.offset],e.offset++;return t}function ha(r,e){da(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let s=hs(r,e);if(s===null)break;t.push(s)}return t}function NS(r,e){let t=da(r,e),s=e.offset,n=e.offset+t,o=[];for(let i=s;i<n;i++)i===s&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function BS(r,e){let t=da(r,e),s=e.offset+t,n=r[e.offset];e.offset++;let o=0,i=0;n<40?(o=0,i=n):n<80?(o=1,i=n-40):(o=2,i=n-80);let a=`${o}.${i}`,c=[];for(;e.offset<s;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function FS(r,e){return e.offset++,null}function US(r,e){let t=da(r,e),s=r[e.offset];e.offset++;let n=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,s!==0)throw new Error("Unused bits in bit string is unimplemented");return n}function KS(r,e){let t=da(r,e),s=r.subarray(e.offset,e.offset+t);return e.offset+=t,s}function HS(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new W;for(let s=0;s<e.length;s+=2)t.append(Uint8Array.from([parseInt(`${e[s]}${e[s+1]}`,16)]));return t}function ul(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=HS(r.byteLength);return new W(Uint8Array.from([e.byteLength|Qd]),e)}function Dt(r){let e=new W,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new W(Uint8Array.from([2]),ul(e),e)}function fa(r){let e=Uint8Array.from([0]),t=new W(e,r);return new W(Uint8Array.from([3]),ul(t),t)}function O3(r){return new W(Uint8Array.from([4]),ul(r),r)}function Sr(r,e=48){let t=new W;for(let s of r)t.append(s);return new W(Uint8Array.from([e]),ul(t),t)}var LS,Qd,RS,M3,Jd=A(()=>{ot();LS=parseInt("11111",2),Qd=parseInt("10000000",2),RS=parseInt("01111111",2),M3={0:ha,1:ha,2:NS,3:US,4:KS,5:FS,6:BS,16:ha,22:ha,48:ha}});async function L3(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 R3(r,e,t){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let n=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},s,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function N3(r,e,t,s){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);s?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,e,t.subarray());return s?.signal?.throwIfAborted(),o}var ef=A(()=>{});function nf(r){let e=hs(r);return B3(e)}function B3(r){let e=r[1][1][0],t=1,s,n;if(e.byteLength===tf*2+1)return s=K(e.subarray(t,t+tf),"base64url"),n=K(e.subarray(t+tf),"base64url"),new mn({...GS,key_ops:["verify"],x:s,y:n});if(e.byteLength===rf*2+1)return s=K(e.subarray(t,t+rf),"base64url"),n=K(e.subarray(t+rf),"base64url"),new mn({...VS,key_ops:["verify"],x:s,y:n});if(e.byteLength===sf*2+1)return s=K(e.subarray(t,t+sf),"base64url"),n=K(e.subarray(t+sf),"base64url"),new mn({...WS,key_ops:["verify"],x:s,y:n});throw new Ge(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function F3(r){return Sr([Dt(Uint8Array.from([1])),O3(L(r.d??"","base64url")),Sr([K3(r.crv)],160),Sr([fa(new W(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function U3(r){return Sr([Dt(Uint8Array.from([1])),Sr([K3(r.crv)],160),Sr([fa(new W(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function K3(r){if(r==="P-256")return zS;if(r==="P-384")return qS;if(r==="P-521")return $S;throw new Ge(`Invalid curve ${r}`)}async function H3(r="P-256"){let e=await L3(r);return new hl(e.privateKey)}var zS,qS,$S,GS,VS,WS,tf,rf,sf,of=A(()=>{Us();ot();ge();Se();Jd();z3();ef();zS=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),qS=Uint8Array.from([6,5,43,129,4,0,34]),$S=Uint8Array.from([6,5,43,129,4,0,35]),GS={ext:!0,kty:"EC",crv:"P-256"},VS={ext:!0,kty:"EC",crv:"P-384"},WS={ext:!0,kty:"EC",crv:"P-521"},tf=32,rf=48,sf=66});var mn,hl,z3=A(()=>{Vt();zr();pn();Kt();ft();of();ef();mn=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=U3(this.jwk)),this._raw}toMultihash(){return Er.digest(Ve(this))}toCID(){return De.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}async verify(e,t,s){return N3(this.jwk,t,e,s)}},hl=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new mn({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=F3(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}async sign(e,t){return R3(this.jwk,e,t)}}});function ZS(r){let t=gn.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",x:"",d:K(r,"base64url"),kty:"OKP"}}).export({format:"jwk"});if(t.x==null||t.x==="")throw new Error("Could not export JWK public key");return L(t.x,"base64url")}function q3(){let r=jS("ed25519",{publicKeyEncoding:{type:"spki",format:"jwk"},privateKeyEncoding:{type:"pkcs8",format:"jwk"}}),e=L(r.privateKey.d,"base64url"),t=L(r.publicKey.x,"base64url");return{privateKey:Ye([e,t],e.byteLength+t.byteLength),publicKey:t}}function $3(r,e){if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');let t,s;if(r.byteLength===dl)t=r.subarray(0,32),s=r.subarray(32);else if(r.byteLength===YS)t=r.subarray(0,32),s=ZS(t);else throw new TypeError('"key" must be 64 or 32 bytes in length.');let n=gn.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",d:K(t,"base64url"),x:K(s,"base64url"),kty:"OKP"}});return gn.default.sign(null,e instanceof Uint8Array?e:e.subarray(),n)}function G3(r,e,t){if(r.byteLength!==pa)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!==XS)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 s=gn.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:K(r,"base64url"),kty:"OKP"}});return gn.default.verify(null,t instanceof Uint8Array?t:t.subarray(),s,e)}var gn,jS,pa,dl,YS,XS,af=A(()=>{gn=we(re("crypto"),1);Kr();ge();Se();jS=gn.default.generateKeyPairSync,pa=32,dl=64,YS=32,XS=64});function cf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var W3=A(()=>{Kr();ge()});var ma,fl,j3=A(()=>{Vt();zr();pn();Kt();W3();ft();lf();af();ma=class{type="Ed25519";raw;constructor(e){this.raw=pl(e,pa)}toMultihash(){return Er.digest(Ve(this))}toCID(){return De.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}verify(e,t,s){s?.signal?.throwIfAborted();let n=G3(this.raw,t,e);return cf(n)?n.then(o=>(s?.signal?.throwIfAborted(),o)):n}},fl=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=pl(e,dl),this.publicKey=new ma(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let s=$3(this.raw,e);return cf(s)?s.then(n=>(t?.signal?.throwIfAborted(),n)):(t?.signal?.throwIfAborted(),s)}}});function uf(r){return r=pl(r,pa),new ma(r)}async function Y3(){let{privateKey:r,publicKey:e}=q3();return new fl(r,e)}function pl(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Ge(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var lf=A(()=>{Us();j3();af()});function X3(r,e,t){hf[0]=r,e[t]=Hs[0],e[t+1]=Hs[1],e[t+2]=Hs[2],e[t+3]=Hs[3]}function Z3(r,e){return Hs[0]=r[e],Hs[1]=r[e+1],Hs[2]=r[e+2],Hs[3]=r[e+3],hf[0]}function Q3(r,e,t){df[0]=r,e[t]=wt[0],e[t+1]=wt[1],e[t+2]=wt[2],e[t+3]=wt[3],e[t+4]=wt[4],e[t+5]=wt[5],e[t+6]=wt[6],e[t+7]=wt[7]}function J3(r,e){return wt[0]=r[e],wt[1]=r[e+1],wt[2]=r[e+2],wt[3]=r[e+3],wt[4]=r[e+4],wt[5]=r[e+5],wt[6]=r[e+6],wt[7]=r[e+7],df[0]}var hf,Hs,df,wt,ff=A(()=>{hf=new Float32Array([-0]),Hs=new Uint8Array(hf.buffer);df=new Float64Array([-0]),wt=new Uint8Array(df.buffer)});var QS,JS,Wt,yn,e6,pf=A(()=>{QS=BigInt(Number.MAX_SAFE_INTEGER),JS=BigInt(Number.MIN_SAFE_INTEGER),Wt=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,s=~this.hi>>>0;return t===0&&(s=s+1>>>0),-(t+s*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,s=~this.hi>>>0;return t===0&&(s=s+1>>>0),-(BigInt(t)+(BigInt(s)<<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,s=this.hi>>>24;return s===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:s<128?9:10}static fromBigInt(e){if(e===0n)return yn;if(e<QS&&e>JS)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let s=e>>32n,n=e-(s<<32n);return t&&(s=~s|0n,n=~n|0n,++n>e6&&(n=0n,++s>e6&&(s=0n))),new r(Number(n),Number(s))}static fromNumber(e){if(e===0)return yn;let t=e<0;t&&(e=-e);let s=e>>>0,n=(e-s)/4294967296>>>0;return t&&(n=~n>>>0,s=~s>>>0,++s>4294967295&&(s=0,++n>4294967295&&(n=0))),new r(s,n)}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):yn}},yn=new Wt(0,0);yn.toBigInt=function(){return 0n};yn.zzEncode=yn.zzDecode=function(){return this};yn.length=function(){return 1};e6=4294967296n});function t6(r){let e=0,t=0;for(let s=0;s<r.length;++s)t=r.charCodeAt(s),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(s+1)&64512)===56320?(++s,e+=4):e+=3;return e}function r6(r,e,t){if(t-e<1)return"";let n,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&&((n??(n=[])).push(String.fromCharCode.apply(String,o)),i=0);return n!=null?(i>0&&n.push(String.fromCharCode.apply(String,o.slice(0,i))),n.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function mf(r,e,t){let s=t,n,o;for(let i=0;i<r.length;++i)n=r.charCodeAt(i),n<128?e[t++]=n:n<2048?(e[t++]=n>>6|192,e[t++]=n&63|128):(n&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(n=65536+((n&1023)<<10)+(o&1023),++i,e[t++]=n>>18|240,e[t++]=n>>12&63|128,e[t++]=n>>6&63|128,e[t++]=n&63|128):(e[t++]=n>>12|224,e[t++]=n>>6&63|128,e[t++]=n&63|128);return t-s}var gf=A(()=>{});function Ir(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ml(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function bf(r){return new yf(r instanceof Uint8Array?r:r.subarray())}var yf,wf=A(()=>{wr();ff();pf();gf();yf=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,Ir(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 Ir(this,4);return ml(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ir(this,4);return ml(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ir(this,4);let e=Z3(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ir(this,4);let e=J3(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,s=this.pos+e;if(s>this.len)throw Ir(this,e);return this.pos+=e,t===s?new Uint8Array(0):this.buf.subarray(t,s)}string(){let e=this.bytes();return r6(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ir(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ir(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 Wt(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 Ir(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 Ir(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 Ir(this,8);let e=ml(this.buf,this.pos+=4),t=ml(this.buf,this.pos+=4);return new Wt(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=wd(this.buf,this.pos);return this.pos+=Le(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 le(r,e,t){let s=bf(r);return e.decode(s,void 0,t)}var n6=A(()=>{wf()});function xf(r){let e=r??8192,t=e>>>1,s,n=e;return function(i){if(i<1||i>t)return je(i);n+i>e&&(s=je(e),n=0);let a=s.subarray(n,n+=i);return(n&7)!==0&&(n=(n|7)+1),a}}var o6=A(()=>{nt()});function vf(){}function t8(r){return globalThis.Buffer!=null?je(r):e8(r)}function Ef(r,e,t){e[t]=r&255}function r8(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function gl(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 ga(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 s8(r,e,t){e.set(r,t)}function n8(r,e,t){e.set(r,t)}function o8(r,e,t){r.length<40?mf(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function _f(){return new ya}var bn,Sf,e8,ya,If,Af=A(()=>{wr();nt();ge();ff();pf();o6();gf();bn=class{fn;len;next;val;constructor(e,t,s){this.fn=e,this.len=t,this.next=void 0,this.val=s}};Sf=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},e8=xf();ya=class{len;head;tail;states;constructor(){this.len=0,this.head=new bn(vf,0,0),this.tail=this.head,this.states=null}_push(e,t,s){return this.tail=this.tail.next=new bn(e,t,s),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new If((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(gl,10,Wt.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Wt.fromBigInt(e);return this._push(gl,t.length(),t)}uint64Number(e){return this._push(ko,Le(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=Wt.fromBigInt(e).zzEncode();return this._push(gl,t.length(),t)}sint64Number(e){let t=Wt.fromNumber(e).zzEncode();return this._push(gl,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ef,1,e?1:0)}fixed32(e){return this._push(ga,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Wt.fromBigInt(e);return this._push(ga,4,t.lo)._push(ga,4,t.hi)}fixed64Number(e){let t=Wt.fromNumber(e);return this._push(ga,4,t.lo)._push(ga,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(X3,4,e)}double(e){return this._push(Q3,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Ef,1,0):this.uint32(t)._push(s8,t,e)}string(e){let t=t6(e);return t!==0?this.uint32(t)._push(mf,t,e):this._push(Ef,1,0)}fork(){return this.states=new Sf(this),this.head=this.tail=new bn(vf,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 bn(vf,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,s=this.len;return this.reset().uint32(s),s!==0&&(this.tail.next=e.next,this.tail=t,this.len+=s),this}finish(){let e=this.head.next,t=t8(this.len),s=0;for(;e!=null;)e.fn(e.val,t,s),s+=e.len,e=e.next;return t}};If=class extends bn{next;constructor(e,t){super(r8,e,t),this.next=void 0}};globalThis.Buffer!=null&&(ya.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(n8,e,r),this},ya.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(o8,e,r),this})});function ue(r,e){let t=_f();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var i6=A(()=>{Af()});function yl(r,e,t,s){return{name:r,type:e,encode:t,decode:s}}var Uo,Cf=A(()=>{(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"})(Uo||(Uo={}))});function Tf(r){function e(n){if(r[n.toString()]==null)throw new Error("Invalid enum value");return r[n]}let t=function(o,i){let a=e(o);i.int32(a)},s=function(o){let i=o.int32();return e(i)};return yl("enum",Uo.VARINT,t,s)}var a6=A(()=>{Cf()});function he(r,e){return yl("message",Uo.LENGTH_DELIMITED,r,e)}var c6=A(()=>{Cf()});var Ie,ba,zs=A(()=>{n6();i6();a6();c6();wf();Af();Ie=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},ba=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}});var ze,Pf,qr,kf,Df=A(()=>{zs();(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ze||(ze={}));(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Pf||(Pf={}));(function(r){r.codec=()=>Tf(Pf)})(ze||(ze={}));(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.Type!=null&&(s.uint32(8),ze.codec().encode(t.Type,s)),t.Data!=null&&(s.uint32(18),s.bytes(t.Data)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={},i=s==null?t.len:t.pos+s;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=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(qr||(qr={}));(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.Type!=null&&(s.uint32(8),ze.codec().encode(t.Type,s)),t.Data!=null&&(s.uint32(18),s.bytes(t.Data)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={},i=s==null?t.len:t.pos+s;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=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(kf||(kf={}))});function wa(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function $r(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function Ee(r,e,t=""){let s=wa(r),n=r?.length,o=e!==void 0;if(!s||o&&n!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function bl(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");$r(r.outputLen),$r(r.blockLen)}function Ko(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 h6(r,e){Ee(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 wn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function wl(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function _r(r,e){return r<<32-e|r>>>e}function xn(r){if(Ee(r),d6)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=i8[r[t]];return e}function u6(r){if(r>=ds._0&&r<=ds._9)return r-ds._0;if(r>=ds.A&&r<=ds.F)return r-(ds.A-10);if(r>=ds.a&&r<=ds.f)return r-(ds.a-10)}function vn(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(d6)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 s=new Uint8Array(t);for(let n=0,o=0;n<t;n++,o+=2){let i=u6(r.charCodeAt(o)),a=u6(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)}s[n]=i*16+a}return s}function Ar(...r){let e=0;for(let s=0;s<r.length;s++){let n=r[s];Ee(n),e+=n.length}let t=new Uint8Array(e);for(let s=0,n=0;s<r.length;s++){let o=r[s];t.set(o,n),n+=o.length}return t}function f6(r,e={}){let t=(n,o)=>r(o).update(n).digest(),s=r(void 0);return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=n=>r(n),Object.assign(t,e),Object.freeze(t)}function Ho(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 d6,i8,ds,p6,qs=A(()=>{d6=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",i8=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));ds={_0:48,_9:57,A:65,F:70,a:97,f:102};p6=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])})});function Gr(r){if(isNaN(r)||r<=0)throw new Ge("random bytes length must be a Number bigger than 0");return Ho(r)}var m6=A(()=>{Us();qs()});function g6(r,e,t){return r&e^~r&t}function y6(r,e,t){return r&e^r&t^e&t}var xl,fs,b6=A(()=>{qs();xl=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,s,n){this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=wl(this.buffer)}update(e){Ko(this),Ee(e);let{view:t,buffer:s,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(n-this.pos,o-i);if(a===n){let c=wl(e);for(;n<=o-i;i+=n)this.process(c,i);continue}s.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ko(this),h6(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,wn(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(s,0),i=0);for(let h=i;h<n;h++)t[h]=0;s.setBigUint64(n-8,BigInt(this.length*8),o),this.process(s,0);let a=wl(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 h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:s,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%t&&e.buffer.set(s),e}clone(){return this._cloneInto()}},fs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var a8,$s,Mf,Of,zo,Lf=A(()=>{b6();qs();a8=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]),$s=new Uint32Array(64),Mf=class extends xl{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:s,D:n,E:o,F:i,G:a,H:c}=this;return[e,t,s,n,o,i,a,c]}set(e,t,s,n,o,i,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)$s[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let d=$s[h-15],f=$s[h-2],p=_r(d,7)^_r(d,18)^d>>>3,m=_r(f,17)^_r(f,19)^f>>>10;$s[h]=m+$s[h-7]+p+$s[h-16]|0}let{A:s,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let d=_r(a,6)^_r(a,11)^_r(a,25),f=u+d+g6(a,c,l)+a8[h]+$s[h]|0,m=(_r(s,2)^_r(s,13)^_r(s,22))+y6(s,n,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=n,n=s,s=f+m|0}s=s+this.A|0,n=n+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(s,n,o,i,a,c,l,u)}roundClean(){wn($s)}destroy(){this.set(0,0,0,0,0,0,0,0),wn(this.buffer)}},Of=class extends Mf{A=fs[0]|0;B=fs[1]|0;C=fs[2]|0;D=fs[3]|0;E=fs[4]|0;F=fs[5]|0;G=fs[6]|0;H=fs[7]|0;constructor(){super(32)}},zo=f6(()=>new Of,p6(1))});var qo,xa,w6=A(()=>{Vt();zr();Kt();Rf();qo=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=va.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return De.createV1(114,this._multihash)}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}verify(e,t,s){return v6(this.jwk,t,e,s)}},xa=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=va.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}sign(e,t){return x6(this.jwk,e,t)}}});var va={};ve(va,{MAX_RSA_KEY_SIZE:()=>Nf,generateRSAKeyPair:()=>Gf,jwkToJWKKeyPair:()=>S6,jwkToPkcs1:()=>h8,jwkToPkix:()=>Kf,jwkToRSAPrivateKey:()=>$f,pkcs1MessageToJwk:()=>Ff,pkcs1MessageToRSAPrivateKey:()=>Hf,pkcs1ToJwk:()=>u8,pkcs1ToRSAPrivateKey:()=>E6,pkixMessageToJwk:()=>Uf,pkixMessageToRSAPublicKey:()=>qf,pkixToJwk:()=>d8,pkixToRSAPublicKey:()=>zf});function u8(r){let e=hs(r);return Ff(e)}function Ff(r){return{n:K(r[1],"base64url"),e:K(r[2],"base64url"),d:K(r[3],"base64url"),p:K(r[4],"base64url"),q:K(r[5],"base64url"),dp:K(r[6],"base64url"),dq:K(r[7],"base64url"),qi:K(r[8],"base64url"),kty:"RSA"}}function h8(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 Ge("JWK was missing components");return Sr([Dt(Uint8Array.from([0])),Dt(L(r.n,"base64url")),Dt(L(r.e,"base64url")),Dt(L(r.d,"base64url")),Dt(L(r.p,"base64url")),Dt(L(r.q,"base64url")),Dt(L(r.dp,"base64url")),Dt(L(r.dq,"base64url")),Dt(L(r.qi,"base64url"))]).subarray()}function d8(r){let e=hs(r,{offset:0});return Uf(e)}function Uf(r){let e=hs(r[1],{offset:0});return{kty:"RSA",n:K(e[0],"base64url"),e:K(e[1],"base64url")}}function Kf(r){if(r.n==null||r.e==null)throw new Ge("JWK was missing components");return Sr([l8,fa(Sr([Dt(L(r.n,"base64url")),Dt(L(r.e,"base64url"))]))]).subarray()}function E6(r){let e=hs(r);return Hf(e)}function Hf(r){let e=Ff(r);return $f(e)}function zf(r,e){if(r.byteLength>=c8)throw new Mo("Key size is too large");let t=hs(r,{offset:0});return qf(t,r,e)}function qf(r,e,t){let s=Uf(r);if(t==null){let n=zo(qr.encode({Type:ze.RSA,Data:e}));t=Hr(Bf,n)}return new qo(s,t)}function $f(r){if(_6(r)>Nf)throw new Ge("Key size is too large");let e=S6(r),t=zo(qr.encode({Type:ze.RSA,Data:Kf(e.publicKey)})),s=Hr(Bf,t);return new xa(e.privateKey,new qo(e.publicKey,s))}async function Gf(r){if(r>Nf)throw new Ge("Key size is too large");let e=await I6(r),t=zo(qr.encode({Type:ze.RSA,Data:Kf(e.publicKey)})),s=Hr(Bf,t);return new xa(e.privateKey,new qo(e.publicKey,s))}function S6(r){if(r==null)throw new Ge("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Nf,Bf,c8,l8,Vf=A(()=>{Us();Lf();ir();ge();Se();Df();Jd();w6();Rf();Nf=8192,Bf=18,c8=1062,l8=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0])});async function I6(r,e){let t=await f8("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function x6(r,e,t){t?.signal?.throwIfAborted();let s=vl.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)s.update(e);else for(let n of e)s.update(n);return s.sign({format:"jwk",key:r})}function v6(r,e,t,s){s?.signal?.throwIfAborted();let n=vl.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)n.update(t);else for(let o of t)n.update(o);return n.verify({format:"jwk",key:r},e)}function _6(r){if(r.kty!=="RSA")throw new Ge("Invalid key type");if(r.n==null)throw new Ge("Invalid key modulus");return L(r.n,"base64url").length*8}var vl,A6,f8,Rf=A(()=>{vl=we(re("node:crypto"),1),A6=re("node:util");Us();ge();Vf();f8=(0,A6.promisify)(vl.default.generateKeyPair)});function Ea(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function C6(r){if(typeof r=="bigint"){if(!El(r))throw new Error("positive bigint expected, got "+r)}else $r(r);return r}function Sa(r){let e=C6(r).toString(16);return e.length&1?"0"+e:e}function T6(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?jf:BigInt("0x"+r)}function $o(r){return T6(xn(r))}function Yf(r){return T6(xn(p8(Ee(r)).reverse()))}function Sl(r,e){$r(e),r=C6(r);let t=vn(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Xf(r,e){return Sl(r,e).reverse()}function p8(r){return Uint8Array.from(r)}function m8(r,e,t){return El(r)&&El(e)&&El(t)&&e<=r&&r<t}function P6(r,e,t,s){if(!m8(e,t,s))throw new Error("expected valid "+r+": "+t+" <= n < "+s+", got "+e)}function Zf(r){let e;for(e=0;r>jf;r>>=Wf,e+=1);return e}function k6(r,e,t){if($r(r,"hashLen"),$r(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let s=g=>new Uint8Array(g),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=s(r),l=s(r),u=0,h=()=>{c.fill(1),l.fill(0),u=0},d=(...g)=>t(l,Ar(c,...g)),f=(g=n)=>{l=d(o,g),c=d(),g.length!==0&&(l=d(i,g),c=d())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,y=[];for(;g<e;){c=d();let w=c.slice();y.push(w),g+=c.length}return Ar(...y)};return(g,y)=>{h(),f(g);let w;for(;!(w=y(p()));)f();return h(),w}}function _a(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function s(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 n=(o,i)=>Object.entries(o).forEach(([a,c])=>s(a,c,i));n(e,!1),n(t,!0)}function Qf(r){let e=new WeakMap;return(t,...s)=>{let n=e.get(t);if(n!==void 0)return n;let o=r(t,...s);return e.set(t,o),o}}var jf,Wf,El,Ia,Il=A(()=>{qs();qs();jf=BigInt(0),Wf=BigInt(1);El=r=>typeof r=="bigint"&&jf<=r;Ia=r=>(Wf<<BigInt(r))-Wf});function Cr(r,e){let t=r%e;return t>=Mt?t:e+t}function jt(r,e,t){let s=r;for(;e-- >Mt;)s*=s,s%=t;return s}function D6(r,e){if(r===Mt)throw new Error("invert: expected non-zero number");if(e<=Mt)throw new Error("invert: expected positive modulus, got "+e);let t=Cr(r,e),s=e,n=Mt,o=xt,i=xt,a=Mt;for(;t!==Mt;){let l=s/t,u=s%t,h=n-i*l,d=o-a*l;s=t,t=u,n=i,o=a,i=h,a=d}if(s!==xt)throw new Error("invert: does not exist");return Cr(n,e)}function ep(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function F6(r,e){let t=(r.ORDER+xt)/L6,s=r.pow(e,t);return ep(r,s,e),s}function b8(r,e){let t=(r.ORDER-R6)/N6,s=r.mul(e,En),n=r.pow(s,t),o=r.mul(e,n),i=r.mul(r.mul(o,En),n),a=r.mul(o,r.sub(i,r.ONE));return ep(r,a,e),a}function w8(r){let e=Go(r),t=U6(r),s=t(e,e.neg(e.ONE)),n=t(e,s),o=t(e,e.neg(s)),i=(r+g8)/B6;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,s),h=a.mul(l,n),d=a.mul(l,o),f=a.eql(a.sqr(u),c),p=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(d,h,p);let m=a.eql(a.sqr(u),c),g=a.cmov(l,u,m);return ep(a,g,c),g}}function U6(r){if(r<O6)throw new Error("sqrt is not defined for small field");let e=r-xt,t=0;for(;e%En===Mt;)e/=En,t++;let s=En,n=Go(r);for(;M6(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return F6;let o=n.pow(s,e),i=(e+xt)/En;return function(c,l){if(c.is0(l))return l;if(M6(c,l)!==1)throw new Error("Cannot find square root");let u=t,h=c.mul(c.ONE,o),d=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===u)throw new Error("Cannot find square root");let g=xt<<BigInt(u-p-1),y=c.pow(h,g);u=p,h=c.sqr(y),d=c.mul(d,h),f=c.mul(f,y)}return f}}function x8(r){return r%L6===O6?F6:r%N6===R6?b8:r%B6===y8?w8(r):U6(r)}function tp(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=v8.reduce((s,n)=>(s[n]="function",s),e);return _a(r,t),r}function E8(r,e,t){if(t<Mt)throw new Error("invalid exponent, negatives unsupported");if(t===Mt)return r.ONE;if(t===xt)return e;let s=r.ONE,n=e;for(;t>Mt;)t&xt&&(s=r.mul(s,n)),n=r.sqr(n),t>>=xt;return s}function _l(r,e,t=!1){let s=new Array(e.length).fill(t?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(s[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(s[c]=r.mul(i,s[c]),r.mul(i,a)),o),s}function M6(r,e){let t=(r.ORDER-xt)/En,s=r.pow(e,t),n=r.eql(s,r.ONE),o=r.eql(s,r.ZERO),i=r.eql(s,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function S8(r,e){e!==void 0&&$r(e);let t=e!==void 0?e:r.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function Go(r,e={}){return new Jf(r,e)}function K6(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 rp(r){let e=K6(r);return e+Math.ceil(e/2)}function sp(r,e,t=!1){Ee(r);let s=r.length,n=K6(e),o=rp(e);if(s<16||s<o||s>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+s);let i=t?Yf(r):$o(r),a=Cr(i,e-xt)+xt;return t?Xf(a,n):Sl(a,n)}var Mt,xt,En,O6,L6,R6,g8,N6,y8,B6,v8,Jf,Al=A(()=>{Il();Mt=BigInt(0),xt=BigInt(1),En=BigInt(2),O6=BigInt(3),L6=BigInt(4),R6=BigInt(5),g8=BigInt(7),N6=BigInt(8),y8=BigInt(9),B6=BigInt(16);v8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Jf=class{ORDER;BITS;BYTES;isLE;ZERO=Mt;ONE=xt;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Mt)throw new Error("invalid field: expected ORDER > 0, got "+e);let s;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(s=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:n,nByteLength:o}=S8(e,s);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Cr(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Mt<=e&&e<this.ORDER}is0(e){return e===Mt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&xt)===xt}neg(e){return Cr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Cr(e*e,this.ORDER)}add(e,t){return Cr(e+t,this.ORDER)}sub(e,t){return Cr(e-t,this.ORDER)}mul(e,t){return Cr(e*t,this.ORDER)}pow(e,t){return E8(this,e,t)}div(e,t){return Cr(e*D6(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 D6(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=x8(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Xf(e,this.BYTES):Sl(e,this.BYTES)}fromBytes(e,t=!1){Ee(e);let{_lengths:s,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(s){if(!s.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?Yf(e):$o(e);if(a&&(c=Cr(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return _l(this,e)}cmov(e,t,s){return s?t:e}}});function Aa(r,e){let t=e.negate();return r?t:e}function ap(r,e){let t=_l(r.Fp,e.map(s=>s.Z));return e.map((s,n)=>r.fromAffine(s.toAffine(t[n])))}function $6(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function np(r,e){$6(r,e);let t=Math.ceil(e/r)+1,s=2**(r-1),n=2**r,o=Ia(r),i=BigInt(r);return{windows:t,windowSize:s,mask:o,maxNumber:n,shiftBy:i}}function H6(r,e,t){let{windowSize:s,mask:n,maxNumber:o,shiftBy:i}=t,a=Number(r&n),c=r>>i;a>s&&(a-=o,c+=Sn);let l=e*s,u=l+Math.abs(a)-1,h=a===0,d=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:d,isNegF:f,offsetF:l}}function ip(r){return G6.get(r)||1}function z6(r){if(r!==Vo)throw new Error("invalid wNAF")}function V6(r,e,t,s){let n=e,o=r.ZERO,i=r.ZERO;for(;t>Vo||s>Vo;)t&Sn&&(o=o.add(n)),s&Sn&&(i=i.add(n)),n=n.double(),t>>=Sn,s>>=Sn;return{p1:o,p2:i}}function q6(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return tp(e),e}else return Go(r,{isLE:t})}function W6(r,e,t={},s){if(s===void 0&&(s=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>Vo))throw new Error(`CURVE.${c} must be positive bigint`)}let n=q6(e.p,t.Fp,s),o=q6(e.n,t.Fn,s),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!n.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:n,Fn:o}}function j6(r,e){return function(s){let n=r(s);return{secretKey:n,publicKey:e(n)}}}var Vo,Sn,op,G6,Cl,Y6=A(()=>{Il();Al();Vo=BigInt(0),Sn=BigInt(1);op=new WeakMap,G6=new WeakMap;Cl=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,s=this.ZERO){let n=e;for(;t>Vo;)t&Sn&&(s=s.add(n)),n=n.double(),t>>=Sn;return s}precomputeWindow(e,t){let{windows:s,windowSize:n}=np(t,this.bits),o=[],i=e,a=i;for(let c=0;c<s;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE,i=np(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:d,offsetF:f}=H6(s,a,i);s=c,u?o=o.add(Aa(d,t[f])):n=n.add(Aa(h,t[l]))}return z6(s),{p:n,f:o}}wNAFUnsafe(e,t,s,n=this.ZERO){let o=np(e,this.bits);for(let i=0;i<o.windows&&s!==Vo;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=H6(s,i,o);if(s=a,!l){let h=t[c];n=n.add(u?h.negate():h)}}return z6(s),n}getPrecomputes(e,t,s){let n=op.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof s=="function"&&(n=s(n)),op.set(t,n))),n}cached(e,t,s){let n=ip(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){let o=ip(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,s),t,n)}createCache(e,t){$6(t,this.bits),G6.set(e,t),op.delete(e)}hasCache(e){return ip(e)!==1}}});var Tl,cp,X6=A(()=>{qs();Tl=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(bl(e),Ee(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 s=this.blockLen,n=new Uint8Array(s);n.set(t.length>s?e.create().update(t).digest():t);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),wn(n)}update(e){return Ko(this),this.iHash.update(e),this}digestInto(e){Ko(this),Ee(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:s,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},cp=(r,e,t)=>new Tl(r,e).update(t).digest();cp.create=(r,e)=>new Tl(r,e)});function I8(r,e,t){let[[s,n],[o,i]]=e,a=Z6(i*r,t),c=Z6(-n*r,t),l=r-a*s-c*o,u=-a*n-c*i,h=l<ps,d=u<ps;h&&(l=-l),d&&(u=-u);let f=Ia(Math.ceil(Zf(t)/2))+Wo;if(l<ps||l>=f||u<ps||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:d,k2:u}}function up(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function lp(r,e){let t={};for(let s of Object.keys(e))t[s]=r[s]===void 0?e[s]:r[s];return Ea(t.lowS,"lowS"),Ea(t.prehash,"prehash"),t.format!==void 0&&up(t.format),t}function J6(r,e={}){let t=W6("weierstrass",r,e),{Fp:s,Fn:n}=t,o=t.CURVE,{h:i,n:a}=o;_a(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!s.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=ty(s,n);function u(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(B,I,S){let{x:_,y:k}=I.toAffine(),O=s.toBytes(_);if(Ea(S,"isCompressed"),S){u();let N=!s.isOdd(k);return Ar(ey(N),O)}else return Ar(Uint8Array.of(4),O,s.toBytes(k))}function d(B){Ee(B,void 0,"Point");let{publicKey:I,publicKeyUncompressed:S}=l,_=B.length,k=B[0],O=B.subarray(1);if(_===I&&(k===2||k===3)){let N=s.fromBytes(O);if(!s.isValid(N))throw new Error("bad point: is not on curve, wrong x");let C=m(N),R;try{R=s.sqrt(C)}catch(ee){let te=ee instanceof Error?": "+ee.message:"";throw new Error("bad point: is not on curve, sqrt error"+te)}u();let U=s.isOdd(R);return(k&1)===1!==U&&(R=s.neg(R)),{x:N,y:R}}else if(_===S&&k===4){let N=s.BYTES,C=s.fromBytes(O.subarray(0,N)),R=s.fromBytes(O.subarray(N,N*2));if(!g(C,R))throw new Error("bad point: is not on curve");return{x:C,y:R}}else throw new Error(`bad point: got length ${_}, expected compressed=${I} or uncompressed=${S}`)}let f=e.toBytes||h,p=e.fromBytes||d;function m(B){let I=s.sqr(B),S=s.mul(I,B);return s.add(s.add(S,s.mul(B,o.a)),o.b)}function g(B,I){let S=s.sqr(I),_=m(B);return s.eql(S,_)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=s.mul(s.pow(o.a,Pl),_8),w=s.mul(s.sqr(o.b),BigInt(27));if(s.is0(s.add(y,w)))throw new Error("bad curve params: a or b");function b(B,I,S=!1){if(!s.isValid(I)||S&&s.is0(I))throw new Error(`bad point coordinate ${B}`);return I}function x(B){if(!(B instanceof v))throw new Error("Weierstrass Point expected")}function E(B){if(!c||!c.basises)throw new Error("no endo");return I8(B,c.basises,n.ORDER)}let P=Qf((B,I)=>{let{X:S,Y:_,Z:k}=B;if(s.eql(k,s.ONE))return{x:S,y:_};let O=B.is0();I==null&&(I=O?s.ONE:s.inv(k));let N=s.mul(S,I),C=s.mul(_,I),R=s.mul(k,I);if(O)return{x:s.ZERO,y:s.ZERO};if(!s.eql(R,s.ONE))throw new Error("invZ was invalid");return{x:N,y:C}}),T=Qf(B=>{if(B.is0()){if(e.allowInfinityPoint&&!s.is0(B.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:S}=B.toAffine();if(!s.isValid(I)||!s.isValid(S))throw new Error("bad point: x or y not field elements");if(!g(I,S))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function D(B,I,S,_,k){return S=new v(s.mul(S.X,B),S.Y,S.Z),I=Aa(_,I),S=Aa(k,S),I.add(S)}class v{static BASE=new v(o.Gx,o.Gy,s.ONE);static ZERO=new v(s.ZERO,s.ONE,s.ZERO);static Fp=s;static Fn=n;X;Y;Z;constructor(I,S,_){this.X=b("x",I),this.Y=b("y",S,!0),this.Z=b("z",_),Object.freeze(this)}static CURVE(){return o}static fromAffine(I){let{x:S,y:_}=I||{};if(!I||!s.isValid(S)||!s.isValid(_))throw new Error("invalid affine point");if(I instanceof v)throw new Error("projective point not allowed");return s.is0(S)&&s.is0(_)?v.ZERO:new v(S,_,s.ONE)}static fromBytes(I){let S=v.fromAffine(p(Ee(I,void 0,"point")));return S.assertValidity(),S}static fromHex(I){return v.fromBytes(vn(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,S=!0){return F.createCache(this,I),S||this.multiply(Pl),this}assertValidity(){T(this)}hasEvenY(){let{y:I}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(I)}equals(I){x(I);let{X:S,Y:_,Z:k}=this,{X:O,Y:N,Z:C}=I,R=s.eql(s.mul(S,C),s.mul(O,k)),U=s.eql(s.mul(_,C),s.mul(N,k));return R&&U}negate(){return new v(this.X,s.neg(this.Y),this.Z)}double(){let{a:I,b:S}=o,_=s.mul(S,Pl),{X:k,Y:O,Z:N}=this,C=s.ZERO,R=s.ZERO,U=s.ZERO,z=s.mul(k,k),ee=s.mul(O,O),te=s.mul(N,N),Z=s.mul(k,O);return Z=s.add(Z,Z),U=s.mul(k,N),U=s.add(U,U),C=s.mul(I,U),R=s.mul(_,te),R=s.add(C,R),C=s.sub(ee,R),R=s.add(ee,R),R=s.mul(C,R),C=s.mul(Z,C),U=s.mul(_,U),te=s.mul(I,te),Z=s.sub(z,te),Z=s.mul(I,Z),Z=s.add(Z,U),U=s.add(z,z),z=s.add(U,z),z=s.add(z,te),z=s.mul(z,Z),R=s.add(R,z),te=s.mul(O,N),te=s.add(te,te),z=s.mul(te,Z),C=s.sub(C,z),U=s.mul(te,ee),U=s.add(U,U),U=s.add(U,U),new v(C,R,U)}add(I){x(I);let{X:S,Y:_,Z:k}=this,{X:O,Y:N,Z:C}=I,R=s.ZERO,U=s.ZERO,z=s.ZERO,ee=o.a,te=s.mul(o.b,Pl),Z=s.mul(S,O),se=s.mul(_,N),xe=s.mul(k,C),$e=s.add(S,_),oe=s.add(O,N);$e=s.mul($e,oe),oe=s.add(Z,se),$e=s.sub($e,oe),oe=s.add(S,k);let rt=s.add(O,C);return oe=s.mul(oe,rt),rt=s.add(Z,xe),oe=s.sub(oe,rt),rt=s.add(_,k),R=s.add(N,C),rt=s.mul(rt,R),R=s.add(se,xe),rt=s.sub(rt,R),z=s.mul(ee,oe),R=s.mul(te,xe),z=s.add(R,z),R=s.sub(se,z),z=s.add(se,z),U=s.mul(R,z),se=s.add(Z,Z),se=s.add(se,Z),xe=s.mul(ee,xe),oe=s.mul(te,oe),se=s.add(se,xe),xe=s.sub(Z,xe),xe=s.mul(ee,xe),oe=s.add(oe,xe),Z=s.mul(se,oe),U=s.add(U,Z),Z=s.mul(rt,oe),R=s.mul($e,R),R=s.sub(R,Z),Z=s.mul($e,se),z=s.mul(rt,z),z=s.add(z,Z),new v(R,U,z)}subtract(I){return this.add(I.negate())}is0(){return this.equals(v.ZERO)}multiply(I){let{endo:S}=e;if(!n.isValidNot0(I))throw new Error("invalid scalar: out of range");let _,k,O=N=>F.cached(this,N,C=>ap(v,C));if(S){let{k1neg:N,k1:C,k2neg:R,k2:U}=E(I),{p:z,f:ee}=O(C),{p:te,f:Z}=O(U);k=ee.add(Z),_=D(S.beta,z,te,N,R)}else{let{p:N,f:C}=O(I);_=N,k=C}return ap(v,[_,k])[0]}multiplyUnsafe(I){let{endo:S}=e,_=this;if(!n.isValid(I))throw new Error("invalid scalar: out of range");if(I===ps||_.is0())return v.ZERO;if(I===Wo)return _;if(F.hasCache(this))return this.multiply(I);if(S){let{k1neg:k,k1:O,k2neg:N,k2:C}=E(I),{p1:R,p2:U}=V6(v,_,O,C);return D(S.beta,R,U,k,N)}else return F.unsafe(_,I)}toAffine(I){return P(this,I)}isTorsionFree(){let{isTorsionFree:I}=e;return i===Wo?!0:I?I(v,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return i===Wo?this:I?I(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(I=!0){return Ea(I,"isCompressed"),this.assertValidity(),f(v,this,I)}toHex(I=!0){return xn(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let M=n.BITS,F=new Cl(v,e.endo?Math.ceil(M/2):M);return v.BASE.precompute(8),v}function ey(r){return Uint8Array.of(r?2:3)}function ty(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function A8(r,e={}){let{Fn:t}=r,s=e.randomBytes||Ho,n=Object.assign(ty(r.Fp,t),{seed:rp(t.ORDER)});function o(f){try{let p=t.fromBytes(f);return t.isValidNot0(p)}catch{return!1}}function i(f,p){let{publicKey:m,publicKeyUncompressed:g}=n;try{let y=f.length;return p===!0&&y!==m||p===!1&&y!==g?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=s(n.seed)){return sp(Ee(f,n.seed,"seed"),t.ORDER)}function c(f,p=!0){return r.BASE.multiply(t.fromBytes(f)).toBytes(p)}function l(f){let{secretKey:p,publicKey:m,publicKeyUncompressed:g}=n;if(!wa(f)||"_lengths"in t&&t._lengths||p===m)return;let y=Ee(f,void 0,"key").length;return y===m||y===g}function u(f,p,m=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(f);return r.fromBytes(p).multiply(g).toBytes(m)}let h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},d=j6(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:h,lengths:n})}function ry(r,e,t={}){bl(e),_a(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let s=t.randomBytes||Ho,n=t.hmac||((S,_)=>cp(e,S,_)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:f}=A8(r,t),p={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Q6<o.ORDER;function g(S){let _=a>>Wo;return S>_}function y(S,_){if(!i.isValidNot0(_))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return _}function w(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function b(S,_){up(_);let k=f.signature,O=_==="compact"?k:_==="recovered"?k+1:void 0;return Ee(S,O)}class x{r;s;recovery;constructor(_,k,O){if(this.r=y("r",_),this.s=y("s",k),O!=null){if(w(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(_,k=p.format){b(_,k);let O;if(k==="der"){let{r:U,s:z}=Gs.toSig(Ee(_));return new x(U,z)}k==="recovered"&&(O=_[0],k="compact",_=_.subarray(1));let N=f.signature/2,C=_.subarray(0,N),R=_.subarray(N,N*2);return new x(i.fromBytes(C),i.fromBytes(R),O)}static fromHex(_,k){return this.fromBytes(vn(_),k)}assertRecovery(){let{recovery:_}=this;if(_==null)throw new Error("invalid recovery id: must be present");return _}addRecoveryBit(_){return new x(this.r,this.s,_)}recoverPublicKey(_){let{r:k,s:O}=this,N=this.assertRecovery(),C=N===2||N===3?k+a:k;if(!o.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let R=o.toBytes(C),U=r.fromBytes(Ar(ey((N&1)===0),R)),z=i.inv(C),ee=P(Ee(_,void 0,"msgHash")),te=i.create(-ee*z),Z=i.create(O*z),se=r.BASE.multiplyUnsafe(te).add(U.multiplyUnsafe(Z));if(se.is0())throw new Error("invalid recovery: point at infinify");return se.assertValidity(),se}hasHighS(){return g(this.s)}toBytes(_=p.format){if(up(_),_==="der")return vn(Gs.hexFromSig(this));let{r:k,s:O}=this,N=i.toBytes(k),C=i.toBytes(O);return _==="recovered"?(w(),Ar(Uint8Array.of(this.assertRecovery()),N,C)):Ar(N,C)}toHex(_){return xn(this.toBytes(_))}}let E=t.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");let k=$o(_),O=_.length*8-c;return O>0?k>>BigInt(O):k},P=t.bits2int_modN||function(_){return i.create(E(_))},T=Ia(c);function D(S){return P6("num < 2^"+c,S,ps,T),i.toBytes(S)}function v(S,_){return Ee(S,void 0,"message"),_?Ee(e(S),void 0,"prehashed message"):S}function M(S,_,k){let{lowS:O,prehash:N,extraEntropy:C}=lp(k,p);S=v(S,N);let R=P(S),U=i.fromBytes(_);if(!i.isValidNot0(U))throw new Error("invalid private key");let z=[D(U),D(R)];if(C!=null&&C!==!1){let se=C===!0?s(f.secretKey):C;z.push(Ee(se,void 0,"extraEntropy"))}let ee=Ar(...z),te=R;function Z(se){let xe=E(se);if(!i.isValidNot0(xe))return;let $e=i.inv(xe),oe=r.BASE.multiply(xe).toAffine(),rt=i.create(oe.x);if(rt===ps)return;let To=i.create($e*i.create(te+rt*U));if(To===ps)return;let ea=(oe.x===rt?0:2)|Number(oe.y&Wo),ta=To;return O&&g(To)&&(ta=i.neg(To),ea^=1),new x(rt,ta,m?void 0:ea)}return{seed:ee,k2sig:Z}}function F(S,_,k={}){let{seed:O,k2sig:N}=M(S,_,k);return k6(e.outputLen,i.BYTES,n)(O,N).toBytes(k.format)}function B(S,_,k,O={}){let{lowS:N,prehash:C,format:R}=lp(O,p);if(k=Ee(k,void 0,"publicKey"),_=v(_,C),!wa(S)){let U=S instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}b(S,R);try{let U=x.fromBytes(S,R),z=r.fromBytes(k);if(N&&U.hasHighS())return!1;let{r:ee,s:te}=U,Z=P(_),se=i.inv(te),xe=i.create(Z*se),$e=i.create(ee*se),oe=r.BASE.multiplyUnsafe(xe).add(z.multiplyUnsafe($e));return oe.is0()?!1:i.create(oe.x)===ee}catch{return!1}}function I(S,_,k={}){let{prehash:O}=lp(k,p);return _=v(_,O),x.fromBytes(S,"recovered").recoverPublicKey(_).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:f,Point:r,sign:F,verify:B,recoverPublicKey:I,Signature:x,hash:e})}var Z6,hp,Gs,ps,Wo,Q6,Pl,_8,sy=A(()=>{X6();qs();Il();Y6();Al();Z6=(r,e)=>(r+(r>=0?e:-e)/Q6)/e;hp=class extends Error{constructor(e=""){super(e)}},Gs={Err:hp,_tlv:{encode:(r,e)=>{let{Err:t}=Gs;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let s=e.length/2,n=Sa(s);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let o=s>127?Sa(n.length/2|128):"";return Sa(r)+o+n+e},decode(r,e){let{Err:t}=Gs,s=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==r)throw new t("tlv.decode: wrong tlv");let n=e[s++],o=!!(n&128),i=0;if(!o)i=n;else{let c=n&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(s,s+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(s+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(s,s+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+i)}}},_int:{encode(r){let{Err:e}=Gs;if(r<ps)throw new e("integer: negative integers are not allowed");let t=Sa(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}=Gs;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 $o(r)}},toSig(r){let{Err:e,_int:t,_tlv:s}=Gs,n=Ee(r,void 0,"signature"),{v:o,l:i}=s.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=s.decode(2,o),{v:l,l:u}=s.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}=Gs,s=e.encode(2,t.encode(r.r)),n=e.encode(2,t.encode(r.s)),o=s+n;return e.encode(48,o)}},ps=BigInt(0),Wo=BigInt(1),Q6=BigInt(2),Pl=BigInt(3),_8=BigInt(4)});function T8(r){let e=fp.p,t=BigInt(3),s=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,h=jt(u,t,e)*u%e,d=jt(h,t,e)*u%e,f=jt(d,ny,e)*l%e,p=jt(f,n,e)*f%e,m=jt(p,o,e)*p%e,g=jt(m,a,e)*m%e,y=jt(g,c,e)*g%e,w=jt(y,a,e)*m%e,b=jt(w,t,e)*u%e,x=jt(b,i,e)*p%e,E=jt(x,s,e)*l%e,P=jt(E,ny,e);if(!dp.eql(dp.sqr(P),r))throw new Error("Cannot find square root");return P}var fp,C8,ny,dp,P8,ms,pp=A(()=>{Lf();Al();sy();fp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},C8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ny=BigInt(2);dp=Go(fp.p,{sqrt:T8}),P8=J6(fp,{Fp:dp,endo:C8}),ms=ry(P8,zo)});var kl,Dl,oy=A(()=>{kl=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Dl=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}});function iy(r,e,t){t?.signal?.throwIfAborted();let s=mp.default.createHash("sha256");if(e instanceof Uint8Array)s.update(e);else for(let o of e)s.update(o);let n=s.digest();try{return ms.sign(n,r,{prehash:!1,format:"der"})}catch(o){throw new kl(String(o))}}function ay(r,e,t,s){s?.signal?.throwIfAborted();let n=mp.default.createHash("sha256");if(t instanceof Uint8Array)n.update(t);else for(let i of t)n.update(i);let o=n.digest();try{return ms.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new Dl(String(i))}}var mp,cy=A(()=>{mp=we(re("node:crypto"),1);pp();oy()});var Ca,Ml,ly=A(()=>{Vt();zr();pn();Kt();ft();gp();cy();Ca=class{type="secp256k1";raw;_key;constructor(e){this._key=dy(e),this.raw=uy(this._key)}toMultihash(){return Er.digest(Ve(this))}toCID(){return De.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}verify(e,t,s){return ay(this._key,t,e,s)}},Ml=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=hy(e),this.publicKey=new Ca(t??fy(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}sign(e,t){return iy(this.raw,e,t)}}});function yp(r){return new Ca(r)}async function py(){let r=k8();return new Ml(r)}function uy(r){return ms.Point.fromBytes(r).toBytes()}function hy(r){try{return ms.getPublicKey(r,!0),r}catch(e){throw new oa(String(e))}}function dy(r){try{return ms.Point.fromBytes(r),r}catch(e){throw new Mo(String(e))}}function fy(r){try{return ms.getPublicKey(r,!0)}catch(e){throw new oa(String(e))}}function k8(){return ms.utils.randomSecretKey()}var gp=A(()=>{Us();pp();ly()});async function my(r,e){if(r==="Ed25519")return Y3();if(r==="secp256k1")return py();if(r==="RSA")return Gf(D8(e));if(r==="ECDSA")return H3(M8(e));throw new Oo}function Je(r,e){let{Type:t,Data:s}=qr.decode(r),n=s??new Uint8Array;switch(t){case ze.RSA:return zf(n,e);case ze.Ed25519:return uf(n);case ze.secp256k1:return yp(n);case ze.ECDSA:return nf(n);default:throw new Oo}}function gy(r){let{Type:e,Data:t}=qr.decode(r.digest),s=t??new Uint8Array;switch(e){case ze.Ed25519:return uf(s);case ze.secp256k1:return yp(s);case ze.ECDSA:return nf(s);default:throw new Oo}}function Ve(r){return qr.encode({Type:ze[r.type],Data:r.raw})}function D8(r){return r==null?2048:parseInt(r,10)}function M8(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 Ge("Unsupported curve, should be P-256, P-384 or P-521")}var ft=A(()=>{Us();of();lf();Df();Vf();gp()});var yy,by=A(()=>{yy=Symbol.for("@libp2p/connection")});var wy=A(()=>{});var xy=A(()=>{});var bp,vy=A(()=>{bp=Symbol.for("@libp2p/content-routing")});var Ey=A(()=>{});var Sy=A(()=>{});var Ta,Iy=A(()=>{Ta=Symbol.for("@libp2p/peer-discovery")});function Vs(r){return!!r?.[Ol]}var Ol,_y=A(()=>{Ol=Symbol.for("@libp2p/peer-id")});var Ay=A(()=>{});var wp,Cy=A(()=>{wp=Symbol.for("@libp2p/peer-routing")});var xp,Ty=A(()=>{xp="keep-alive"});var In,jo,Ot,aR,Py=A(()=>{In="StrictSign",jo="StrictNoSign";(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(Ot||(Ot={}));aR=Symbol.for("@libp2p/pubsub")});var ky=A(()=>{});var Dy=A(()=>{});var My=A(()=>{});var Oy=A(()=>{});var Ly,_n,Ry=A(()=>{Ly=Symbol.for("@libp2p/transport");(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(_n||(_n={}))});var Lt,Ll,Rl,V,Nl,Yo,Ws,Bl,Fl,An,Xo,js,Ul,Kl,Cn,Yt,Hl,Vr,Tr,zl,Zo,Pa,ql,Qo,$l,Ny=A(()=>{Lt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},Ll=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Rl=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},V=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Nl=class extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},Yo=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},Ws=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Bl=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},Fl=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},An=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Xo=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},js=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Ul=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Kl=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Cn=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Yt=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},Hl=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Vr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Tr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},zl=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}},Zo=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Pa=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},ql=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Qo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},$l=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});function Gl(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function By(...r){let e=[];for(let t of r)Gl(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 Fy(...r){let e=[];for(let t of r)Gl(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 Uy=A(()=>{});var et,ka,X=A(()=>{by();wy();xy();vy();Ey();Sy();Iy();_y();Ay();Cy();Ty();Py();ky();Dy();My();Oy();Ry();Ny();Ze();Uy();et=Symbol.for("@libp2p/service-capabilities"),ka=Symbol.for("@libp2p/service-dependencies")});var Ky,O8,Da,Ma,Oa,La,L8,Ra,Hy=A(()=>{X();Vt();zr();pn();Kt();ge();Se();Ky=Symbol.for("nodejs.util.inspect.custom"),O8=114,Da=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()})`}[Ol]=!0;toString(){return this.string==null&&(this.string=me.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return De.createV1(O8,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ae(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ae(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ky](){return`PeerId(${this.toString()})`}},Ma=class extends Da{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Oa=class extends Da{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},La=class extends Da{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},L8=2336,Ra=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Er.digest(L(this.url))}[Ky](){return`PeerId(${this.url})`}[Ol]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return De.createV1(L8,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=K(e)),e.toString()===this.toString())}}});var Ep={};ve(Ep,{peerIdFromCID:()=>Wr,peerIdFromMultihash:()=>Pr,peerIdFromPrivateKey:()=>vp,peerIdFromPublicKey:()=>gs,peerIdFromString:()=>$});function $(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ht(me.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Wr(De.parse(r));if(e==null)throw new V('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ht(e.decode(r))}return Pr(t)}function gs(r){if(r.type==="Ed25519")return new Oa({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new La({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Ma({multihash:r.toCID().multihash,publicKey:r});throw new $l}function vp(r){return gs(r.publicKey)}function Pr(r){if(B8(r))return new Ma({multihash:r});if(N8(r))try{let e=gy(r);if(e.type==="Ed25519")return new Oa({multihash:r,publicKey:e});if(e.type==="secp256k1")return new La({multihash:r,publicKey:e})}catch{let t=K(r.digest);return new Ra(new URL(t))}throw new Kl("Supplied PeerID Multihash is invalid")}function Wr(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==R8&&r.code!==zy)throw new Ul("Supplied PeerID CID is invalid");if(r.code===zy){let e=K(r.multihash.digest);return new Ra(new URL(e))}return Pr(r.multihash)}function N8(r){return r.code===Er.code}function B8(r){return r.code===Qe.code}var R8,zy,ce=A(()=>{ft();X();Vt();zr();ir();pn();us();Se();Hy();R8=114,zy=2336});var Zp=A(()=>{"use strict"});var b5=He((SK,y5)=>{var oi=1e3,ii=oi*60,ai=ii*60,Mn=ai*24,p_=Mn*7,m_=Mn*365.25;y5.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return g_(r);if(t==="number"&&isFinite(r))return e.long?b_(r):y_(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function g_(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]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return t*m_;case"weeks":case"week":case"w":return t*p_;case"days":case"day":case"d":return t*Mn;case"hours":case"hour":case"hrs":case"hr":case"h":return t*ai;case"minutes":case"minute":case"mins":case"min":case"m":return t*ii;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 y_(r){var e=Math.abs(r);return e>=Mn?Math.round(r/Mn)+"d":e>=ai?Math.round(r/ai)+"h":e>=ii?Math.round(r/ii)+"m":e>=oi?Math.round(r/oi)+"s":r+"ms"}function b_(r){var e=Math.abs(r);return e>=Mn?Xl(r,e,Mn,"day"):e>=ai?Xl(r,e,ai,"hour"):e>=ii?Xl(r,e,ii,"minute"):e>=oi?Xl(r,e,oi,"second"):r+" ms"}function Xl(r,e,t,s){var n=e>=t*1.5;return Math.round(r/t)+" "+s+(n?"s":"")}});var Jp=He((IK,w5)=>{function w_(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=n,t.enabled=a,t.humanize=b5(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let h=0;for(let d=0;d<u.length;d++)h=(h<<5)-h+u.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(u){let h,d=null,f,p;function m(...g){if(!m.enabled)return;let y=m,w=Number(new Date),b=w-(h||w);y.diff=b,y.prev=h,y.curr=w,h=w,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,(P,T)=>{if(P==="%%")return"%";x++;let D=t.formatters[T];if(typeof D=="function"){let v=g[x];P=D.call(y,v),g.splice(x,1),x--}return P}),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=s,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(u)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function s(u,h){let d=t(this.namespace+(typeof h>"u"?":":h)+u);return d.log=this.log,d}function n(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let h=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of h)d[0]==="-"?t.skips.push(d.slice(1)):t.names.push(d)}function o(u,h){let d=0,f=0,p=-1,m=0;for(;d<u.length;)if(f<h.length&&(h[f]===u[d]||h[f]==="*"))h[f]==="*"?(p=f,m=d,f++):(d++,f++);else if(p!==-1)f=p+1,m++,d=m;else return!1;for(;f<h.length&&h[f]==="*";)f++;return f===h.length}function i(){let u=[...t.names,...t.skips.map(h=>"-"+h)].join(",");return t.enable(""),u}function a(u){for(let h of t.skips)if(o(u,h))return!1;for(let h of t.names)if(o(u,h))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}w5.exports=w_});var x5=He((qt,Zl)=>{qt.formatArgs=v_;qt.save=E_;qt.load=S_;qt.useColors=x_;qt.storage=I_();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 x_(){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 v_(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Zl.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,s=0;r[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(s=t))}),r.splice(s,0,e)}qt.log=console.debug||console.log||(()=>{});function E_(r){try{r?qt.storage.setItem("debug",r):qt.storage.removeItem("debug")}catch{}}function S_(){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 I_(){try{return localStorage}catch{}}Zl.exports=Jp()(qt);var{formatters:__}=Zl.exports;__.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var E5=He((_K,v5)=>{"use strict";v5.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",s=e.indexOf(t+r),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}});var _5=He((AK,I5)=>{"use strict";var A_=re("os"),S5=re("tty"),cr=E5(),{env:it}=process,Xs;cr("no-color")||cr("no-colors")||cr("color=false")||cr("color=never")?Xs=0:(cr("color")||cr("colors")||cr("color=true")||cr("color=always"))&&(Xs=1);"FORCE_COLOR"in it&&(it.FORCE_COLOR==="true"?Xs=1:it.FORCE_COLOR==="false"?Xs=0:Xs=it.FORCE_COLOR.length===0?1:Math.min(parseInt(it.FORCE_COLOR,10),3));function e0(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function t0(r,e){if(Xs===0)return 0;if(cr("color=16m")||cr("color=full")||cr("color=truecolor"))return 3;if(cr("color=256"))return 2;if(r&&!e&&Xs===void 0)return 0;let t=Xs||0;if(it.TERM==="dumb")return t;if(process.platform==="win32"){let s=A_.release().split(".");return Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in it)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(s=>s in it)||it.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in it)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(it.TEAMCITY_VERSION)?1:0;if(it.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in it){let s=parseInt((it.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(it.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(it.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(it.TERM)||"COLORTERM"in it?1:t}function C_(r){let e=t0(r,r&&r.isTTY);return e0(e)}I5.exports={supportsColor:C_,stdout:e0(t0(!0,S5.isatty(1))),stderr:e0(t0(!0,S5.isatty(2)))}});var C5=He((at,Jl)=>{var T_=re("tty"),Ql=re("util");at.init=R_;at.log=M_;at.formatArgs=k_;at.save=O_;at.load=L_;at.useColors=P_;at.destroy=Ql.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");at.colors=[6,2,3,4,5,1];try{let r=_5();r&&(r.stderr||r).level>=2&&(at.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{}at.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,o)=>o.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function P_(){return"colors"in at.inspectOpts?!!at.inspectOpts.colors:T_.isatty(process.stderr.fd)}function k_(r){let{namespace:e,useColors:t}=this;if(t){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),o=` ${n};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
2
+ "use strict";var OptimysticDbP2P=(()=>{var yS=Object.create;var yl=Object.defineProperty;var bS=Object.getOwnPropertyDescriptor;var wS=Object.getOwnPropertyNames;var xS=Object.getPrototypeOf,vS=Object.prototype.hasOwnProperty;var oe=(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 A=(r,e)=>()=>(r&&(e=r(r=0)),e);var We=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),_e=(r,e)=>{for(var t in e)yl(r,t,{get:e[t],enumerable:!0})},u3=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of wS(e))!vS.call(r,n)&&n!==t&&yl(r,n,{get:()=>e[n],enumerable:!(s=bS(e,n))||s.enumerable});return r};var xe=(r,e,t)=>(t=r!=null?yS(xS(r)):{},u3(e||!r||!r.__esModule?yl(t,"default",{value:r,enumerable:!0}):t,r)),ES=r=>u3(yl({},"__esModule",{value:!0}),r);function Ws(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}var wa=A(()=>{});function ee(r=0){return Ws(J1.Buffer.alloc(r))}function tt(r=0){return Ws(J1.Buffer.allocUnsafe(r))}var J1,rt=A(()=>{J1=oe("node:buffer");wa()});function Ue(r){if(r<DS)return 1;if(r<MS)return 2;if(r<OS)return 3;if(r<ef)return 4;if(r<tf)return 5;if(r<rf)return 6;if(r<sf)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $o(r,e,t=0){switch(Ue(r)){case 8:e[t++]=r&255|ge,r/=128;case 7:e[t++]=r&255|ge,r/=128;case 6:e[t++]=r&255|ge,r/=128;case 5:e[t++]=r&255|ge,r/=128;case 4:e[t++]=r&255|ge,r>>>=7;case 3:e[t++]=r&255|ge,r>>>=7;case 2:e[t++]=r&255|ge,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function RS(r,e,t=0){switch(Ue(r)){case 8:e.set(t++,r&255|ge),r/=128;case 7:e.set(t++,r&255|ge),r/=128;case 6:e.set(t++,r&255|ge),r/=128;case 5:e.set(t++,r&255|ge),r/=128;case 4:e.set(t++,r&255|ge),r>>>=7;case 3:e.set(t++,r&255|ge),r>>>=7;case 2:e.set(t++,r&255|ge),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function nf(r,e){let t=r[e],s=0;if(s+=t&vt,t<ge||(t=r[e+1],s+=(t&vt)<<7,t<ge)||(t=r[e+2],s+=(t&vt)<<14,t<ge)||(t=r[e+3],s+=(t&vt)<<21,t<ge)||(t=r[e+4],s+=(t&vt)*ef,t<ge)||(t=r[e+5],s+=(t&vt)*tf,t<ge)||(t=r[e+6],s+=(t&vt)*rf,t<ge)||(t=r[e+7],s+=(t&vt)*sf,t<ge))return s;throw new RangeError("Could not decode varint")}function LS(r,e){let t=r.get(e),s=0;if(s+=t&vt,t<ge||(t=r.get(e+1),s+=(t&vt)<<7,t<ge)||(t=r.get(e+2),s+=(t&vt)<<14,t<ge)||(t=r.get(e+3),s+=(t&vt)<<21,t<ge)||(t=r.get(e+4),s+=(t&vt)*ef,t<ge)||(t=r.get(e+5),s+=(t&vt)*tf,t<ge)||(t=r.get(e+6),s+=(t&vt)*rf,t<ge)||(t=r.get(e+7),s+=(t&vt)*sf,t<ge))return s;throw new RangeError("Could not decode varint")}function hr(r,e,t=0){return e==null&&(e=tt(Ue(r))),e instanceof Uint8Array?$o(r,e,t):RS(r,e,t)}function ms(r,e=0){return r instanceof Uint8Array?nf(r,e):LS(r,e)}var DS,MS,OS,ef,tf,rf,sf,ge,vt,Ar=A(()=>{rt();DS=Math.pow(2,7),MS=Math.pow(2,14),OS=Math.pow(2,21),ef=Math.pow(2,28),tf=Math.pow(2,35),rf=Math.pow(2,42),sf=Math.pow(2,49),ge=128,vt=127});function st(r,e){return Ws(f3.Buffer.concat(r,e))}var f3,Vr=A(()=>{f3=oe("node:buffer");wa()});function de(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 Gt=A(()=>{});function p3(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let s of r){let n=t+s.byteLength;if(e<n)return{buf:s,index:e-t};t=n}throw new RangeError("index is out of bounds")}function vl(r){return!!r?.[m3]}var m3,W,at=A(()=>{rt();Vr();Gt();m3=Symbol.for("@achingbrain/uint8arraylist");W=class r{bufs;length;[m3]=!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 s of e)if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.push(s);else if(vl(s))t+=s.byteLength,this.bufs.push(...s.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 s of e.reverse())if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.unshift(s);else if(vl(s))t+=s.byteLength,this.bufs.unshift(...s.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=p3(this.bufs,e);return t.buf[t.index]}set(e,t){let s=p3(this.bufs,e);s.buf[s.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let s=0;s<e.length;s++)this.set(t+s,e[s]);else if(vl(e))for(let s=0;s<e.length;s++)this.set(t+s,e.get(s));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:s,length:n}=this._subList(e,t);return st(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:st(s,n)}sublist(e,t){let{bufs:s,length:n}=this._subList(e,t),o=new r;return o.length=n,o.bufs=[...s],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 s=[],n=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=n,c=a+i.byteLength;if(n=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){s.push(i);break}let h=e-a;s.push(i.subarray(h,h+(t-e)));break}if(l){if(e===0){s.push(i);continue}s.push(i.subarray(e-a));continue}if(u){if(t===c){s.push(i);break}s.push(i.subarray(0,t-a));break}s.push(i)}return{bufs:s,length:t-e}}indexOf(e,t=0){if(!vl(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let s=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 n=s.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<n;h++)i[s[h]]=h;let a=i,c=this.byteLength-s.byteLength,l=s.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let d=l;d>=0;d--){let f=this.get(h+d);if(s[d]!==f){u=Math.max(1,d-a[f]);break}}if(u===0)return h}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 s=tt(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt8(0,t),this.write(s,e)}getInt16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt16(0,t)}setInt16(e,t,s){let n=ee(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,s),this.write(n,e)}getInt32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt32(0,t)}setInt32(e,t,s){let n=ee(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,s),this.write(n,e)}getBigInt64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigInt64(0,t)}setBigInt64(e,t,s){let n=ee(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,s),this.write(n,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 s=tt(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint8(0,t),this.write(s,e)}getUint16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint16(0,t)}setUint16(e,t,s){let n=ee(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,s),this.write(n,e)}getUint32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint32(0,t)}setUint32(e,t,s){let n=ee(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,s),this.write(n,e)}getBigUint64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0,t)}setBigUint64(e,t,s){let n=ee(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,s),this.write(n,e)}getFloat32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat32(0,t)}setFloat32(e,t,s){let n=ee(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,s),this.write(n,e)}getFloat64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat64(0,t)}setFloat64(e,t,s){let n=ee(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,s),this.write(n,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(!de(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let s=new r;return s.bufs=e,t==null&&(t=e.reduce((n,o)=>n+o.byteLength,0)),s.length=t,s}}});var GM,y3=A(()=>{GM=Symbol.for("@libp2p/connection")});var b3=A(()=>{});var w3=A(()=>{});var x3=A(()=>{});var WM,v3=A(()=>{WM=Symbol.for("@libp2p/content-routing")});var Je,Vo,Ea,Wo,E3=A(()=>{Je=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Vo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Ea=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},Wo=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});var S3=A(()=>{});var I3=A(()=>{});var _3=A(()=>{});var A3=A(()=>{});var T3=A(()=>{});var QM,C3=A(()=>{QM=Symbol.for("@libp2p/peer-discovery")});var e9,P3=A(()=>{e9=Symbol.for("@libp2p/peer-id")});var k3=A(()=>{});var r9,D3=A(()=>{r9=Symbol.for("@libp2p/peer-routing")});var M3=A(()=>{});var O3=A(()=>{});var R3=A(()=>{});var L3=A(()=>{});var N3=A(()=>{});var B3=A(()=>{});var F3=A(()=>{});var i9,U3,K3=A(()=>{i9=Symbol.for("@libp2p/transport");(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(U3||(U3={}))});var H3,Y,z3=A(()=>{H3=oe("node:events"),Y=(r,...e)=>{try{(0,H3.setMaxListeners)(r,...e)}catch{}}});var Ae,Oe=A(()=>{z3();Ae=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,s){super.addEventListener(e,t,s);let n=this.#e.get(e);n==null&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(s!==!0&&s!==!1&&s?.once)??!1})}removeEventListener(e,t,s){super.removeEventListener(e.toString(),t??null,s);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:o})=>o!==t),this.#e.set(e,n))}dispatchEvent(e){let t=super.dispatchEvent(e),s=this.#e.get(e.type);return s==null||(s=s.filter(({once:n})=>!n),this.#e.set(e.type,s)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}});var h9,d9,Ys=A(()=>{y3();b3();w3();x3();v3();E3();S3();I3();_3();A3();T3();C3();P3();k3();D3();M3();O3();R3();L3();N3();B3();F3();K3();Oe();h9=Symbol.for("@libp2p/service-capabilities"),d9=Symbol.for("@libp2p/service-dependencies")});function q3(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 fr(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 $3(r){return new TextEncoder().encode(r)}function G3(r){return new TextDecoder().decode(r)}var F9,ys=A(()=>{F9=new Uint8Array(0)});function US(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var n=0;n<r.length;n++){var o=r.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var E=p[y],P=0,C=w-1;(E!==0||P<g)&&C!==-1;C--,P++)E+=256*x[C]>>>0,x[C]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");g=P,y++}for(var D=w-g;D!==w&&x[D]===0;)D++;for(var v=c.repeat(m);D<w;++D)v+=r.charAt(x[D]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*l+1>>>0,w=new Uint8Array(b);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var E=0,P=b-1;(x!==0||E<y)&&P!==-1;P--,E++)x+=a*w[P]>>>0,w[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=E,m++}if(p[m]!==" "){for(var C=b-y;C!==b&&w[C]===0;)C++;for(var D=new Uint8Array(g+(b-C)),v=g;C!==b;)D[v++]=w[C++];return D}}}function f(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var KS,HS,W3,j3=A(()=>{KS=US,HS=KS,W3=HS});function Y3(r,e){return new uf({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function jo({name:r,prefix:e,encode:t,decode:s}){return new hf(r,e,t,s)}function Xs({name:r,prefix:e,alphabet:t}){let{encode:s,decode:n}=W3(t,r);return jo({prefix:e,name:r,encode:s,decode:o=>fr(n(o))})}function zS(r,e,t,s){let n=r.length;for(;r[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,c=0;for(let l=0;l<n;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${s} 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 qS(r,e,t){let s=e[e.length-1]==="=",n=(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[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),s)for(;(o.length*t&7)!==0;)o+="=";return o}function $S(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:s}){let n=$S(s);return jo({prefix:e,name:r,encode(o){return qS(o,s,t)},decode(o){return zS(o,n,t,r)}})}var cf,lf,uf,hf,Tr=A(()=>{ys();j3();cf=class{name;prefix;baseEncode;constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},lf=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,s){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=s}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 Y3(this,e)}},uf=class{decoders;constructor(e){this.decoders=e}or(e){return Y3(this,e)}decode(e){let t=e[0],s=this.decoders[t];if(s!=null)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};hf=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new cf(e,t,s),this.decoder=new lf(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var df={};_e(df,{base58btc:()=>ye,base58flickr:()=>GS});var ye,GS,Qt=A(()=>{Tr();ye=Xs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),GS=Xs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var ff={};_e(ff,{base32:()=>pr,base32hex:()=>YS,base32hexpad:()=>ZS,base32hexpadupper:()=>QS,base32hexupper:()=>XS,base32pad:()=>WS,base32padupper:()=>jS,base32upper:()=>VS,base32z:()=>JS});var pr,VS,WS,jS,YS,XS,ZS,QS,JS,Yo=A(()=>{Tr();pr=Ke({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),VS=Ke({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),WS=Ke({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jS=Ke({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),YS=Ke({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),XS=Ke({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ZS=Ke({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),QS=Ke({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),JS=Ke({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var pf={};_e(pf,{base36:()=>Sa,base36upper:()=>eI});var Sa,eI,mf=A(()=>{Tr();Sa=Xs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),eI=Xs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});function Q3(r,e,t){e=e||[],t=t||0;for(var s=t;r>=nI;)e[t++]=r&255|X3,r/=128;for(;r&sI;)e[t++]=r&255|X3,r>>>=7;return e[t]=r|0,Q3.bytes=t-s+1,e}function gf(r,s){var t=0,s=s||0,n=0,o=s,i,a=r.length;do{if(o>=a)throw gf.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=n<28?(i&Z3)<<n:(i&Z3)*Math.pow(2,n),n+=7}while(i>=iI);return gf.bytes=o-s,t}var tI,X3,rI,sI,nI,oI,iI,Z3,aI,cI,lI,uI,hI,dI,fI,pI,mI,gI,yI,bI,Ia,J3=A(()=>{tI=Q3,X3=128,rI=127,sI=~rI,nI=Math.pow(2,31);oI=gf,iI=128,Z3=127;aI=Math.pow(2,7),cI=Math.pow(2,14),lI=Math.pow(2,21),uI=Math.pow(2,28),hI=Math.pow(2,35),dI=Math.pow(2,42),fI=Math.pow(2,49),pI=Math.pow(2,56),mI=Math.pow(2,63),gI=function(r){return r<aI?1:r<cI?2:r<lI?3:r<uI?4:r<hI?5:r<dI?6:r<fI?7:r<pI?8:r<mI?9:10},yI={encode:tI,decode:oI,encodingLength:gI},bI=yI,Ia=bI});function _a(r,e=0){return[Ia.decode(r,e),Ia.decode.bytes]}function Xo(r,e,t=0){return Ia.encode(r,e,t),e}function Zo(r){return Ia.encodingLength(r)}var Cl=A(()=>{J3()});function Wr(r,e){let t=e.byteLength,s=Zo(r),n=s+Zo(t),o=new Uint8Array(n+t);return Xo(r,o,0),Xo(t,o,s),o.set(e,n),new Qo(r,t,e,o)}function ct(r){let e=fr(r),[t,s]=_a(e),[n,o]=_a(e.subarray(s)),i=e.subarray(s+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new Qo(t,n,i,e)}function ey(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&q3(r.bytes,t.bytes)}}var Qo,Vt=A(()=>{ys();Cl();Qo=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}}});var yf=A(()=>{});function ty(r,e){let{bytes:t,version:s}=r;switch(s){case 0:return xI(t,bf(r),e??ye.encoder);default:return vI(t,bf(r),e??pr.encoder)}}function bf(r){let e=ry.get(r);if(e==null){let t=new Map;return ry.set(r,t),t}return e}function wI(r,e){switch(r[0]){case"Q":{let t=e??ye;return[ye.prefix,t.decode(`${ye.prefix}${r}`)]}case ye.prefix:{let t=e??ye;return[ye.prefix,t.decode(r)]}case pr.prefix:{let t=e??pr;return[pr.prefix,t.decode(r)]}case Sa.prefix:{let t=e??Sa;return[Sa.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 xI(r,e,t){let{prefix:s}=t;if(s!==ye.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(s);if(n==null){let o=t.encode(r).slice(1);return e.set(s,o),o}else return n}function vI(r,e,t){let{prefix:s}=t,n=e.get(s);if(n==null){let o=t.encode(r);return e.set(s,o),o}else return n}function sy(r,e,t){let s=Zo(r),n=s+Zo(e),o=new Uint8Array(n+t.byteLength);return Xo(r,o,0),Xo(e,o,s),o.set(t,n),o}var ry,Re,Aa,EI,SI,Cr=A(()=>{Yo();mf();Qt();ys();Vt();Cl();yf();ry=new WeakMap;Re=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=n,this["/"]=n}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!==Aa)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==EI)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,s=Wr(e,t);return r.createV1(this.code,s)}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 s=t;return s!=null&&e.code===s.code&&e.version===s.version&&ey(e.multihash,s.multihash)}toString(e){return ty(this,e)}toJSON(){return{"/":ty(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:s,code:n,multihash:o,bytes:i}=t;return new r(s,n,o,i??sy(s,n,o.bytes))}else if(t[SI]===!0){let{version:s,multihash:n,code:o}=t,i=ct(n);return r.create(s,o,i)}else return null}static create(e,t,s){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(s.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Aa)throw new Error(`Version 0 CID must use dag-pb (code: ${Aa}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=sy(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Aa,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,s]=r.decodeFirst(e);if(s.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),s=t.size-t.multihashSize,n=fr(e.subarray(s,s+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new Qo(t.multihashCode,t.digestSize,o,n);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,s=()=>{let[h,d]=_a(e.subarray(t));return t+=d,h},n=s(),o=Aa;if(n===18?(n=0,t=0):o=s(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=s(),c=s(),l=t+c,u=l-i;return{version:n,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[s,n]=wI(e,t),o=r.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return bf(o).set(s,e),o}};Aa=112,EI=18;SI=Symbol.for("@ipld/js-cid/CID")});var wf={};_e(wf,{identity:()=>Pr});function _I(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 Wr(ny,oy(r))}var ny,II,oy,Pr,In=A(()=>{ys();Vt();ny=0,II="identity",oy=fr;Pr={code:ny,name:II,encode:oy,digest:_I}});var xf={};_e(xf,{base10:()=>AI});var AI,iy=A(()=>{Tr();AI=Xs({prefix:"9",name:"base10",alphabet:"0123456789"})});var vf={};_e(vf,{base16:()=>TI,base16upper:()=>CI});var TI,CI,ay=A(()=>{Tr();TI=Ke({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),CI=Ke({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var Ef={};_e(Ef,{base2:()=>PI});var PI,cy=A(()=>{Tr();PI=Ke({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var Sf={};_e(Sf,{base256emoji:()=>RI});function MI(r){return r.reduce((e,t)=>(e+=kI[t],e),"")}function OI(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=DI[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var ly,kI,DI,RI,uy=A(()=>{Tr();ly=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}"),kI=ly.reduce((r,e,t)=>(r[t]=e,r),[]),DI=ly.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);RI=jo({prefix:"\u{1F680}",name:"base256emoji",encode:MI,decode:OI})});var Af={};_e(Af,{base64:()=>If,base64pad:()=>LI,base64url:()=>_f,base64urlpad:()=>NI});var If,LI,_f,NI,Pl=A(()=>{Tr();If=Ke({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),LI=Ke({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_f=Ke({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),NI=Ke({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var Tf={};_e(Tf,{base8:()=>BI});var BI,hy=A(()=>{Tr();BI=Ke({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var Cf={};_e(Cf,{identity:()=>FI});var FI,dy=A(()=>{ys();Tr();FI=jo({prefix:"\0",name:"identity",encode:r=>G3(r),decode:r=>$3(r)})});var uO,hO,fy=A(()=>{uO=new TextEncoder,hO=new TextDecoder});var py=A(()=>{ys()});function kf({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new Pf(r,e,t,s,n)}function my(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 Wr(e,r)}var HI,Pf,Df=A(()=>{Vt();HI=20;Pf=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,o){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??HI,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 s=this.encode(e);return s instanceof Uint8Array?my(s,this.code,t?.truncate):s.then(n=>my(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var Of={};_e(Of,{sha256:()=>et,sha512:()=>zI});var Mf,et,zI,jr=A(()=>{Mf=xe(oe("crypto"),1);ys();Df();et=kf({name:"sha2-256",code:18,encode:r=>fr(Mf.default.createHash("sha256").update(r).digest())}),zI=kf({name:"sha2-512",code:19,encode:r=>fr(Mf.default.createHash("sha512").update(r).digest())})});var yy=A(()=>{});var by=A(()=>{});var wy=A(()=>{});var xy=A(()=>{});var vy=A(()=>{yy();by();wy();yf();xy()});var Rf=A(()=>{ys();Cr();Vt();Df();Cl();vy()});var Ta,IO,Lf=A(()=>{iy();ay();cy();uy();Yo();mf();Qt();Pl();hy();dy();fy();py();In();jr();Rf();Ta={...Cf,...Ef,...Tf,...xf,...vf,...ff,...pf,...df,...Af,...Sf},IO={...Of,...wf}});function Sy(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var Ey,Nf,qI,kl,Bf=A(()=>{Lf();rt();Ey=Sy("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Nf=Sy("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}),qI={utf8:Ey,"utf-8":Ey,hex:Ta.base16,latin1:Nf,ascii:Nf,binary:Nf,...Ta},kl=qI});function R(r,e="utf8"){let t=kl[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?Ws(Iy.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var Iy,be=A(()=>{Iy=oe("node:buffer");Bf();wa()});function U(r,e="utf8"){let t=kl[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?_y.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var _y,Pe=A(()=>{_y=oe("node:buffer");Bf()});function bs(r,e={offset:0}){let t=r[e.offset]&$I;if(e.offset++,Ay[t]!=null)return Ay[t](r,e);throw new Error("No decoder for tag "+t)}function Pa(r,e){let t=0;if((r[e.offset]&Ff)===Ff){let s=r[e.offset]&GI,n="0x";e.offset++;for(let o=0;o<s;o++,e.offset++)n+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(n,16)}else t=r[e.offset],e.offset++;return t}function Ca(r,e){Pa(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let s=bs(r,e);if(s===null)break;t.push(s)}return t}function VI(r,e){let t=Pa(r,e),s=e.offset,n=e.offset+t,o=[];for(let i=s;i<n;i++)i===s&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function WI(r,e){let t=Pa(r,e),s=e.offset+t,n=r[e.offset];e.offset++;let o=0,i=0;n<40?(o=0,i=n):n<80?(o=1,i=n-40):(o=2,i=n-80);let a=`${o}.${i}`,c=[];for(;e.offset<s;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function jI(r,e){return e.offset++,null}function YI(r,e){let t=Pa(r,e),s=r[e.offset];e.offset++;let n=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,s!==0)throw new Error("Unused bits in bit string is unimplemented");return n}function XI(r,e){let t=Pa(r,e),s=r.subarray(e.offset,e.offset+t);return e.offset+=t,s}function ZI(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new W;for(let s=0;s<e.length;s+=2)t.append(Uint8Array.from([parseInt(`${e[s]}${e[s+1]}`,16)]));return t}function Dl(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=ZI(r.byteLength);return new W(Uint8Array.from([e.byteLength|Ff]),e)}function Rt(r){let e=new W,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new W(Uint8Array.from([2]),Dl(e),e)}function ka(r){let e=Uint8Array.from([0]),t=new W(e,r);return new W(Uint8Array.from([3]),Dl(t),t)}function Ty(r){return new W(Uint8Array.from([4]),Dl(r),r)}function kr(r,e=48){let t=new W;for(let s of r)t.append(s);return new W(Uint8Array.from([e]),Dl(t),t)}var $I,Ff,GI,Ay,Uf=A(()=>{at();$I=parseInt("11111",2),Ff=parseInt("10000000",2),GI=parseInt("01111111",2),Ay={0:Ca,1:Ca,2:VI,3:YI,4:XI,5:jI,6:WI,16:Ca,22:Ca,48:Ca}});async function Cy(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 Py(r,e,t){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let n=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},s,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function ky(r,e,t,s){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);s?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,e,t.subarray());return s?.signal?.throwIfAborted(),o}var Kf=A(()=>{});function $f(r){let e=bs(r);return Dy(e)}function Dy(r){let e=r[1][1][0],t=1,s,n;if(e.byteLength===Hf*2+1)return s=U(e.subarray(t,t+Hf),"base64url"),n=U(e.subarray(t+Hf),"base64url"),new _n({...t8,key_ops:["verify"],x:s,y:n});if(e.byteLength===zf*2+1)return s=U(e.subarray(t,t+zf),"base64url"),n=U(e.subarray(t+zf),"base64url"),new _n({...r8,key_ops:["verify"],x:s,y:n});if(e.byteLength===qf*2+1)return s=U(e.subarray(t,t+qf),"base64url"),n=U(e.subarray(t+qf),"base64url"),new _n({...s8,key_ops:["verify"],x:s,y:n});throw new Je(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function My(r){return kr([Rt(Uint8Array.from([1])),Ty(R(r.d??"","base64url")),kr([Ry(r.crv)],160),kr([ka(new W(Uint8Array.from([4]),R(r.x??"","base64url"),R(r.y??"","base64url")))],161)]).subarray()}function Oy(r){return kr([Rt(Uint8Array.from([1])),kr([Ry(r.crv)],160),kr([ka(new W(Uint8Array.from([4]),R(r.x??"","base64url"),R(r.y??"","base64url")))],161)]).subarray()}function Ry(r){if(r==="P-256")return QI;if(r==="P-384")return JI;if(r==="P-521")return e8;throw new Je(`Invalid curve ${r}`)}async function Ly(r="P-256"){let e=await Cy(r);return new Ml(e.privateKey)}var QI,JI,e8,t8,r8,s8,Hf,zf,qf,Gf=A(()=>{Ys();at();be();Pe();Uf();Ny();Kf();QI=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),JI=Uint8Array.from([6,5,43,129,4,0,34]),e8=Uint8Array.from([6,5,43,129,4,0,35]),t8={ext:!0,kty:"EC",crv:"P-256"},r8={ext:!0,kty:"EC",crv:"P-384"},s8={ext:!0,kty:"EC",crv:"P-521"},Hf=32,zf=48,qf=66});var _n,Ml,Ny=A(()=>{Qt();Cr();In();Gt();lt();Gf();Kf();_n=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Oy(this.jwk)),this._raw}toMultihash(){return Pr.digest(He(this))}toCID(){return Re.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}async verify(e,t,s){return ky(this.jwk,t,e,s)}},Ml=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new _n({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=My(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}async sign(e,t){return Py(this.jwk,e,t)}}});function a8(r){let t=An.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",x:"",d:U(r,"base64url"),kty:"OKP"}}).export({format:"jwk"});if(t.x==null||t.x==="")throw new Error("Could not export JWK public key");return R(t.x,"base64url")}function By(){let r=n8("ed25519",{publicKeyEncoding:{type:"spki",format:"jwk"},privateKeyEncoding:{type:"pkcs8",format:"jwk"}}),e=R(r.privateKey.d,"base64url"),t=R(r.publicKey.x,"base64url");return{privateKey:st([e,t],e.byteLength+t.byteLength),publicKey:t}}function Fy(r,e){if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');let t,s;if(r.byteLength===Ol)t=r.subarray(0,32),s=r.subarray(32);else if(r.byteLength===o8)t=r.subarray(0,32),s=a8(t);else throw new TypeError('"key" must be 64 or 32 bytes in length.');let n=An.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",d:U(t,"base64url"),x:U(s,"base64url"),kty:"OKP"}});return An.default.sign(null,e instanceof Uint8Array?e:e.subarray(),n)}function Uy(r,e,t){if(r.byteLength!==Da)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!==i8)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 s=An.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:U(r,"base64url"),kty:"OKP"}});return An.default.verify(null,t instanceof Uint8Array?t:t.subarray(),s,e)}var An,n8,Da,Ol,o8,i8,Vf=A(()=>{An=xe(oe("crypto"),1);Vr();be();Pe();n8=An.default.generateKeyPairSync,Da=32,Ol=64,o8=32,i8=64});function Wf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Hy=A(()=>{Vr();be()});var Ma,Rl,zy=A(()=>{Qt();Cr();In();Gt();Hy();lt();jf();Vf();Ma=class{type="Ed25519";raw;constructor(e){this.raw=Ll(e,Da)}toMultihash(){return Pr.digest(He(this))}toCID(){return Re.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}verify(e,t,s){s?.signal?.throwIfAborted();let n=Uy(this.raw,t,e);return Wf(n)?n.then(o=>(s?.signal?.throwIfAborted(),o)):n}},Rl=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Ll(e,Ol),this.publicKey=new Ma(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let s=Fy(this.raw,e);return Wf(s)?s.then(n=>(t?.signal?.throwIfAborted(),n)):(t?.signal?.throwIfAborted(),s)}}});function Yf(r){return r=Ll(r,Da),new Ma(r)}async function qy(){let{privateKey:r,publicKey:e}=By();return new Rl(r,e)}function Ll(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Je(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var jf=A(()=>{Ys();zy();Vf()});function $y(r,e,t){Xf[0]=r,e[t]=Zs[0],e[t+1]=Zs[1],e[t+2]=Zs[2],e[t+3]=Zs[3]}function Gy(r,e){return Zs[0]=r[e],Zs[1]=r[e+1],Zs[2]=r[e+2],Zs[3]=r[e+3],Xf[0]}function Vy(r,e,t){Zf[0]=r,e[t]=Et[0],e[t+1]=Et[1],e[t+2]=Et[2],e[t+3]=Et[3],e[t+4]=Et[4],e[t+5]=Et[5],e[t+6]=Et[6],e[t+7]=Et[7]}function Wy(r,e){return Et[0]=r[e],Et[1]=r[e+1],Et[2]=r[e+2],Et[3]=r[e+3],Et[4]=r[e+4],Et[5]=r[e+5],Et[6]=r[e+6],Et[7]=r[e+7],Zf[0]}var Xf,Zs,Zf,Et,Qf=A(()=>{Xf=new Float32Array([-0]),Zs=new Uint8Array(Xf.buffer);Zf=new Float64Array([-0]),Et=new Uint8Array(Zf.buffer)});var c8,l8,er,Tn,jy,Jf=A(()=>{c8=BigInt(Number.MAX_SAFE_INTEGER),l8=BigInt(Number.MIN_SAFE_INTEGER),er=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,s=~this.hi>>>0;return t===0&&(s=s+1>>>0),-(t+s*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,s=~this.hi>>>0;return t===0&&(s=s+1>>>0),-(BigInt(t)+(BigInt(s)<<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,s=this.hi>>>24;return s===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:s<128?9:10}static fromBigInt(e){if(e===0n)return Tn;if(e<c8&&e>l8)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let s=e>>32n,n=e-(s<<32n);return t&&(s=~s|0n,n=~n|0n,++n>jy&&(n=0n,++s>jy&&(s=0n))),new r(Number(n),Number(s))}static fromNumber(e){if(e===0)return Tn;let t=e<0;t&&(e=-e);let s=e>>>0,n=(e-s)/4294967296>>>0;return t&&(n=~n>>>0,s=~s>>>0,++s>4294967295&&(s=0,++n>4294967295&&(n=0))),new r(s,n)}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):Tn}},Tn=new er(0,0);Tn.toBigInt=function(){return 0n};Tn.zzEncode=Tn.zzDecode=function(){return this};Tn.length=function(){return 1};jy=4294967296n});function Yy(r){let e=0,t=0;for(let s=0;s<r.length;++s)t=r.charCodeAt(s),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(s+1)&64512)===56320?(++s,e+=4):e+=3;return e}function Xy(r,e,t){if(t-e<1)return"";let n,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&&((n??(n=[])).push(String.fromCharCode.apply(String,o)),i=0);return n!=null?(i>0&&n.push(String.fromCharCode.apply(String,o.slice(0,i))),n.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function ep(r,e,t){let s=t,n,o;for(let i=0;i<r.length;++i)n=r.charCodeAt(i),n<128?e[t++]=n:n<2048?(e[t++]=n>>6|192,e[t++]=n&63|128):(n&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(n=65536+((n&1023)<<10)+(o&1023),++i,e[t++]=n>>18|240,e[t++]=n>>12&63|128,e[t++]=n>>6&63|128,e[t++]=n&63|128):(e[t++]=n>>12|224,e[t++]=n>>6&63|128,e[t++]=n&63|128);return t-s}var tp=A(()=>{});function Dr(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Nl(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function sp(r){return new rp(r instanceof Uint8Array?r:r.subarray())}var rp,np=A(()=>{Ar();Qf();Jf();tp();rp=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,Dr(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 Dr(this,4);return Nl(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Dr(this,4);return Nl(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Dr(this,4);let e=Gy(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Dr(this,4);let e=Wy(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,s=this.pos+e;if(s>this.len)throw Dr(this,e);return this.pos+=e,t===s?new Uint8Array(0):this.buf.subarray(t,s)}string(){let e=this.bytes();return Xy(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Dr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Dr(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 er(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 Dr(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 Dr(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 Dr(this,8);let e=Nl(this.buf,this.pos+=4),t=Nl(this.buf,this.pos+=4);return new er(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=nf(this.buf,this.pos);return this.pos+=Ue(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 te(r,e,t){let s=sp(r);return e.decode(s,void 0,t)}var Qy=A(()=>{np()});function op(r){let e=r??8192,t=e>>>1,s,n=e;return function(i){if(i<1||i>t)return tt(i);n+i>e&&(s=tt(e),n=0);let a=s.subarray(n,n+=i);return(n&7)!==0&&(n=(n|7)+1),a}}var Jy=A(()=>{rt()});function ip(){}function h8(r){return globalThis.Buffer!=null?tt(r):u8(r)}function ap(r,e,t){e[t]=r&255}function d8(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function Bl(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 Oa(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 f8(r,e,t){e.set(r,t)}function p8(r,e,t){e.set(r,t)}function m8(r,e,t){r.length<40?ep(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(R(r),t)}function up(){return new Ra}var Cn,cp,u8,Ra,lp,hp=A(()=>{Ar();rt();be();Qf();Jf();Jy();tp();Cn=class{fn;len;next;val;constructor(e,t,s){this.fn=e,this.len=t,this.next=void 0,this.val=s}};cp=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},u8=op();Ra=class{len;head;tail;states;constructor(){this.len=0,this.head=new Cn(ip,0,0),this.tail=this.head,this.states=null}_push(e,t,s){return this.tail=this.tail.next=new Cn(e,t,s),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new lp((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(Bl,10,er.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=er.fromBigInt(e);return this._push(Bl,t.length(),t)}uint64Number(e){return this._push($o,Ue(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=er.fromBigInt(e).zzEncode();return this._push(Bl,t.length(),t)}sint64Number(e){let t=er.fromNumber(e).zzEncode();return this._push(Bl,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ap,1,e?1:0)}fixed32(e){return this._push(Oa,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=er.fromBigInt(e);return this._push(Oa,4,t.lo)._push(Oa,4,t.hi)}fixed64Number(e){let t=er.fromNumber(e);return this._push(Oa,4,t.lo)._push(Oa,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($y,4,e)}double(e){return this._push(Vy,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(ap,1,0):this.uint32(t)._push(f8,t,e)}string(e){let t=Yy(e);return t!==0?this.uint32(t)._push(ep,t,e):this._push(ap,1,0)}fork(){return this.states=new cp(this),this.head=this.tail=new Cn(ip,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 Cn(ip,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,s=this.len;return this.reset().uint32(s),s!==0&&(this.tail.next=e.next,this.tail=t,this.len+=s),this}finish(){let e=this.head.next,t=h8(this.len),s=0;for(;e!=null;)e.fn(e.val,t,s),s+=e.len,e=e.next;return t}};lp=class extends Cn{next;constructor(e,t){super(d8,e,t),this.next=void 0}};globalThis.Buffer!=null&&(Ra.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(p8,e,r),this},Ra.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(m8,e,r),this})});function re(r,e){let t=up();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var e6=A(()=>{hp()});function Fl(r,e,t,s){return{name:r,type:e,encode:t,decode:s}}var Jo,dp=A(()=>{(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"})(Jo||(Jo={}))});function Pn(r){function e(n){if(r[n.toString()]==null)throw new Error("Invalid enum value");return r[n]}let t=function(o,i){let a=e(o);i.int32(a)},s=function(o){let i=o.int32();return e(i)};return Fl("enum",Jo.VARINT,t,s)}var t6=A(()=>{dp()});function se(r,e){return Fl("message",Jo.LENGTH_DELIMITED,r,e)}var r6=A(()=>{dp()});var Se,La,ws=A(()=>{Qy();e6();t6();r6();np();hp();Se=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},La=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}});var je,fp,Yr,pp,mp=A(()=>{ws();(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"})(fp||(fp={}));(function(r){r.codec=()=>Pn(fp)})(je||(je={}));(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.Type!=null&&(s.uint32(8),je.codec().encode(t.Type,s)),t.Data!=null&&(s.uint32(18),s.bytes(t.Data)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={},i=s==null?t.len:t.pos+s;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=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(Yr||(Yr={}));(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.Type!=null&&(s.uint32(8),je.codec().encode(t.Type,s)),t.Data!=null&&(s.uint32(18),s.bytes(t.Data)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={},i=s==null?t.len:t.pos+s;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=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(pp||(pp={}))});function Na(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 Te(r,e,t=""){let s=Na(r),n=r?.length,o=e!==void 0;if(!s||o&&n!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Ul(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 ei(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 o6(r,e){Te(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 Kl(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Mr(r,e){return r<<32-e|r>>>e}function Dn(r){if(Te(r),i6)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=g8[r[t]];return e}function n6(r){if(r>=xs._0&&r<=xs._9)return r-xs._0;if(r>=xs.A&&r<=xs.F)return r-(xs.A-10);if(r>=xs.a&&r<=xs.f)return r-(xs.a-10)}function Mn(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(i6)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 s=new Uint8Array(t);for(let n=0,o=0;n<t;n++,o+=2){let i=n6(r.charCodeAt(o)),a=n6(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)}s[n]=i*16+a}return s}function Or(...r){let e=0;for(let s=0;s<r.length;s++){let n=r[s];Te(n),e+=n.length}let t=new Uint8Array(e);for(let s=0,n=0;s<r.length;s++){let o=r[s];t.set(o,n),n+=o.length}return t}function a6(r,e={}){let t=(n,o)=>r(o).update(n).digest(),s=r(void 0);return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=n=>r(n),Object.assign(t,e),Object.freeze(t)}function ti(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 i6,g8,xs,c6,Qs=A(()=>{i6=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",g8=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));xs={_0:48,_9:57,A:65,F:70,a:97,f:102};c6=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])})});function Zr(r){if(isNaN(r)||r<=0)throw new Je("random bytes length must be a Number bigger than 0");return ti(r)}var l6=A(()=>{Ys();Qs()});function u6(r,e,t){return r&e^~r&t}function h6(r,e,t){return r&e^r&t^e&t}var Hl,vs,d6=A(()=>{Qs();Hl=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,s,n){this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Kl(this.buffer)}update(e){ei(this),Te(e);let{view:t,buffer:s,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(n-this.pos,o-i);if(a===n){let c=Kl(e);for(;n<=o-i;i+=n)this.process(c,i);continue}s.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ei(this),o6(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,kn(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(s,0),i=0);for(let h=i;h<n;h++)t[h]=0;s.setBigUint64(n-8,BigInt(this.length*8),o),this.process(s,0);let a=Kl(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 h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:s,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%t&&e.buffer.set(s),e}clone(){return this._cloneInto()}},vs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var y8,Js,gp,yp,ri,bp=A(()=>{d6();Qs();y8=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]),Js=new Uint32Array(64),gp=class extends Hl{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:s,D:n,E:o,F:i,G:a,H:c}=this;return[e,t,s,n,o,i,a,c]}set(e,t,s,n,o,i,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)Js[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let d=Js[h-15],f=Js[h-2],p=Mr(d,7)^Mr(d,18)^d>>>3,m=Mr(f,17)^Mr(f,19)^f>>>10;Js[h]=m+Js[h-7]+p+Js[h-16]|0}let{A:s,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let d=Mr(a,6)^Mr(a,11)^Mr(a,25),f=u+d+u6(a,c,l)+y8[h]+Js[h]|0,m=(Mr(s,2)^Mr(s,13)^Mr(s,22))+h6(s,n,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=n,n=s,s=f+m|0}s=s+this.A|0,n=n+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(s,n,o,i,a,c,l,u)}roundClean(){kn(Js)}destroy(){this.set(0,0,0,0,0,0,0,0),kn(this.buffer)}},yp=class extends gp{A=vs[0]|0;B=vs[1]|0;C=vs[2]|0;D=vs[3]|0;E=vs[4]|0;F=vs[5]|0;G=vs[6]|0;H=vs[7]|0;constructor(){super(32)}},ri=a6(()=>new yp,c6(1))});var si,Ba,f6=A(()=>{Qt();Cr();Gt();wp();si=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Fa.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Re.createV1(114,this._multihash)}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}verify(e,t,s){return m6(this.jwk,t,e,s)}},Ba=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Fa.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}sign(e,t){return p6(this.jwk,e,t)}}});var Fa={};_e(Fa,{MAX_RSA_KEY_SIZE:()=>xp,generateRSAKeyPair:()=>Pp,jwkToJWKKeyPair:()=>y6,jwkToPkcs1:()=>v8,jwkToPkix:()=>Ip,jwkToRSAPrivateKey:()=>Cp,pkcs1MessageToJwk:()=>Ep,pkcs1MessageToRSAPrivateKey:()=>_p,pkcs1ToJwk:()=>x8,pkcs1ToRSAPrivateKey:()=>g6,pkixMessageToJwk:()=>Sp,pkixMessageToRSAPublicKey:()=>Tp,pkixToJwk:()=>E8,pkixToRSAPublicKey:()=>Ap});function x8(r){let e=bs(r);return Ep(e)}function Ep(r){return{n:U(r[1],"base64url"),e:U(r[2],"base64url"),d:U(r[3],"base64url"),p:U(r[4],"base64url"),q:U(r[5],"base64url"),dp:U(r[6],"base64url"),dq:U(r[7],"base64url"),qi:U(r[8],"base64url"),kty:"RSA"}}function v8(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 Je("JWK was missing components");return kr([Rt(Uint8Array.from([0])),Rt(R(r.n,"base64url")),Rt(R(r.e,"base64url")),Rt(R(r.d,"base64url")),Rt(R(r.p,"base64url")),Rt(R(r.q,"base64url")),Rt(R(r.dp,"base64url")),Rt(R(r.dq,"base64url")),Rt(R(r.qi,"base64url"))]).subarray()}function E8(r){let e=bs(r,{offset:0});return Sp(e)}function Sp(r){let e=bs(r[1],{offset:0});return{kty:"RSA",n:U(e[0],"base64url"),e:U(e[1],"base64url")}}function Ip(r){if(r.n==null||r.e==null)throw new Je("JWK was missing components");return kr([w8,ka(kr([Rt(R(r.n,"base64url")),Rt(R(r.e,"base64url"))]))]).subarray()}function g6(r){let e=bs(r);return _p(e)}function _p(r){let e=Ep(r);return Cp(e)}function Ap(r,e){if(r.byteLength>=b8)throw new Vo("Key size is too large");let t=bs(r,{offset:0});return Tp(t,r,e)}function Tp(r,e,t){let s=Sp(r);if(t==null){let n=ri(Yr.encode({Type:je.RSA,Data:e}));t=Wr(vp,n)}return new si(s,t)}function Cp(r){if(w6(r)>xp)throw new Je("Key size is too large");let e=y6(r),t=ri(Yr.encode({Type:je.RSA,Data:Ip(e.publicKey)})),s=Wr(vp,t);return new Ba(e.privateKey,new si(e.publicKey,s))}async function Pp(r){if(r>xp)throw new Je("Key size is too large");let e=await b6(r),t=ri(Yr.encode({Type:je.RSA,Data:Ip(e.publicKey)})),s=Wr(vp,t);return new Ba(e.privateKey,new si(e.publicKey,s))}function y6(r){if(r==null)throw new Je("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var xp,vp,b8,w8,kp=A(()=>{Ys();bp();Vt();be();Pe();mp();Uf();f6();wp();xp=8192,vp=18,b8=1062,w8=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0])});async function b6(r,e){let t=await S8("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function p6(r,e,t){t?.signal?.throwIfAborted();let s=zl.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)s.update(e);else for(let n of e)s.update(n);return s.sign({format:"jwk",key:r})}function m6(r,e,t,s){s?.signal?.throwIfAborted();let n=zl.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)n.update(t);else for(let o of t)n.update(o);return n.verify({format:"jwk",key:r},e)}function w6(r){if(r.kty!=="RSA")throw new Je("Invalid key type");if(r.n==null)throw new Je("Invalid key modulus");return R(r.n,"base64url").length*8}var zl,x6,S8,wp=A(()=>{zl=xe(oe("node:crypto"),1),x6=oe("node:util");Ys();be();kp();S8=(0,x6.promisify)(zl.default.generateKeyPair)});function Ua(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function v6(r){if(typeof r=="bigint"){if(!ql(r))throw new Error("positive bigint expected, got "+r)}else Xr(r);return r}function Ka(r){let e=v6(r).toString(16);return e.length&1?"0"+e:e}function E6(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Mp:BigInt("0x"+r)}function ni(r){return E6(Dn(r))}function Op(r){return E6(Dn(I8(Te(r)).reverse()))}function $l(r,e){Xr(e),r=v6(r);let t=Mn(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Rp(r,e){return $l(r,e).reverse()}function I8(r){return Uint8Array.from(r)}function _8(r,e,t){return ql(r)&&ql(e)&&ql(t)&&e<=r&&r<t}function S6(r,e,t,s){if(!_8(e,t,s))throw new Error("expected valid "+r+": "+t+" <= n < "+s+", got "+e)}function Lp(r){let e;for(e=0;r>Mp;r>>=Dp,e+=1);return e}function I6(r,e,t){if(Xr(r,"hashLen"),Xr(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let s=g=>new Uint8Array(g),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=s(r),l=s(r),u=0,h=()=>{c.fill(1),l.fill(0),u=0},d=(...g)=>t(l,Or(c,...g)),f=(g=n)=>{l=d(o,g),c=d(),g.length!==0&&(l=d(i,g),c=d())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,y=[];for(;g<e;){c=d();let b=c.slice();y.push(b),g+=c.length}return Or(...y)};return(g,y)=>{h(),f(g);let b;for(;!(b=y(p()));)f();return h(),b}}function za(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function s(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 n=(o,i)=>Object.entries(o).forEach(([a,c])=>s(a,c,i));n(e,!1),n(t,!0)}function Np(r){let e=new WeakMap;return(t,...s)=>{let n=e.get(t);if(n!==void 0)return n;let o=r(t,...s);return e.set(t,o),o}}var Mp,Dp,ql,Ha,Gl=A(()=>{Qs();Qs();Mp=BigInt(0),Dp=BigInt(1);ql=r=>typeof r=="bigint"&&Mp<=r;Ha=r=>(Dp<<BigInt(r))-Dp});function Rr(r,e){let t=r%e;return t>=Lt?t:e+t}function tr(r,e,t){let s=r;for(;e-- >Lt;)s*=s,s%=t;return s}function _6(r,e){if(r===Lt)throw new Error("invert: expected non-zero number");if(e<=Lt)throw new Error("invert: expected positive modulus, got "+e);let t=Rr(r,e),s=e,n=Lt,o=St,i=St,a=Lt;for(;t!==Lt;){let l=s/t,u=s%t,h=n-i*l,d=o-a*l;s=t,t=u,n=i,o=a,i=h,a=d}if(s!==St)throw new Error("invert: does not exist");return Rr(n,e)}function Fp(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function M6(r,e){let t=(r.ORDER+St)/C6,s=r.pow(e,t);return Fp(r,s,e),s}function C8(r,e){let t=(r.ORDER-P6)/k6,s=r.mul(e,On),n=r.pow(s,t),o=r.mul(e,n),i=r.mul(r.mul(o,On),n),a=r.mul(o,r.sub(i,r.ONE));return Fp(r,a,e),a}function P8(r){let e=oi(r),t=O6(r),s=t(e,e.neg(e.ONE)),n=t(e,s),o=t(e,e.neg(s)),i=(r+A8)/D6;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,s),h=a.mul(l,n),d=a.mul(l,o),f=a.eql(a.sqr(u),c),p=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(d,h,p);let m=a.eql(a.sqr(u),c),g=a.cmov(l,u,m);return Fp(a,g,c),g}}function O6(r){if(r<T6)throw new Error("sqrt is not defined for small field");let e=r-St,t=0;for(;e%On===Lt;)e/=On,t++;let s=On,n=oi(r);for(;A6(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return M6;let o=n.pow(s,e),i=(e+St)/On;return function(c,l){if(c.is0(l))return l;if(A6(c,l)!==1)throw new Error("Cannot find square root");let u=t,h=c.mul(c.ONE,o),d=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===u)throw new Error("Cannot find square root");let g=St<<BigInt(u-p-1),y=c.pow(h,g);u=p,h=c.sqr(y),d=c.mul(d,h),f=c.mul(f,y)}return f}}function k8(r){return r%C6===T6?M6:r%k6===P6?C8:r%D6===T8?P8(r):O6(r)}function Up(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=D8.reduce((s,n)=>(s[n]="function",s),e);return za(r,t),r}function M8(r,e,t){if(t<Lt)throw new Error("invalid exponent, negatives unsupported");if(t===Lt)return r.ONE;if(t===St)return e;let s=r.ONE,n=e;for(;t>Lt;)t&St&&(s=r.mul(s,n)),n=r.sqr(n),t>>=St;return s}function Vl(r,e,t=!1){let s=new Array(e.length).fill(t?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(s[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(s[c]=r.mul(i,s[c]),r.mul(i,a)),o),s}function A6(r,e){let t=(r.ORDER-St)/On,s=r.pow(e,t),n=r.eql(s,r.ONE),o=r.eql(s,r.ZERO),i=r.eql(s,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function O8(r,e){e!==void 0&&Xr(e);let t=e!==void 0?e:r.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function oi(r,e={}){return new Bp(r,e)}function R6(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 Kp(r){let e=R6(r);return e+Math.ceil(e/2)}function Hp(r,e,t=!1){Te(r);let s=r.length,n=R6(e),o=Kp(e);if(s<16||s<o||s>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+s);let i=t?Op(r):ni(r),a=Rr(i,e-St)+St;return t?Rp(a,n):$l(a,n)}var Lt,St,On,T6,C6,P6,A8,k6,T8,D6,D8,Bp,Wl=A(()=>{Gl();Lt=BigInt(0),St=BigInt(1),On=BigInt(2),T6=BigInt(3),C6=BigInt(4),P6=BigInt(5),A8=BigInt(7),k6=BigInt(8),T8=BigInt(9),D6=BigInt(16);D8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Bp=class{ORDER;BITS;BYTES;isLE;ZERO=Lt;ONE=St;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Lt)throw new Error("invalid field: expected ORDER > 0, got "+e);let s;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(s=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:n,nByteLength:o}=O8(e,s);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Rr(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Lt<=e&&e<this.ORDER}is0(e){return e===Lt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&St)===St}neg(e){return Rr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Rr(e*e,this.ORDER)}add(e,t){return Rr(e+t,this.ORDER)}sub(e,t){return Rr(e-t,this.ORDER)}mul(e,t){return Rr(e*t,this.ORDER)}pow(e,t){return M8(this,e,t)}div(e,t){return Rr(e*_6(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 _6(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=k8(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Rp(e,this.BYTES):$l(e,this.BYTES)}fromBytes(e,t=!1){Te(e);let{_lengths:s,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(s){if(!s.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?Op(e):ni(e);if(a&&(c=Rr(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Vl(this,e)}cmov(e,t,s){return s?t:e}}});function qa(r,e){let t=e.negate();return r?t:e}function Gp(r,e){let t=Vl(r.Fp,e.map(s=>s.Z));return e.map((s,n)=>r.fromAffine(s.toAffine(t[n])))}function F6(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function zp(r,e){F6(r,e);let t=Math.ceil(e/r)+1,s=2**(r-1),n=2**r,o=Ha(r),i=BigInt(r);return{windows:t,windowSize:s,mask:o,maxNumber:n,shiftBy:i}}function L6(r,e,t){let{windowSize:s,mask:n,maxNumber:o,shiftBy:i}=t,a=Number(r&n),c=r>>i;a>s&&(a-=o,c+=Rn);let l=e*s,u=l+Math.abs(a)-1,h=a===0,d=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:d,isNegF:f,offsetF:l}}function $p(r){return U6.get(r)||1}function N6(r){if(r!==ii)throw new Error("invalid wNAF")}function K6(r,e,t,s){let n=e,o=r.ZERO,i=r.ZERO;for(;t>ii||s>ii;)t&Rn&&(o=o.add(n)),s&Rn&&(i=i.add(n)),n=n.double(),t>>=Rn,s>>=Rn;return{p1:o,p2:i}}function B6(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Up(e),e}else return oi(r,{isLE:t})}function H6(r,e,t={},s){if(s===void 0&&(s=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>ii))throw new Error(`CURVE.${c} must be positive bigint`)}let n=B6(e.p,t.Fp,s),o=B6(e.n,t.Fn,s),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!n.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:n,Fn:o}}function z6(r,e){return function(s){let n=r(s);return{secretKey:n,publicKey:e(n)}}}var ii,Rn,qp,U6,jl,q6=A(()=>{Gl();Wl();ii=BigInt(0),Rn=BigInt(1);qp=new WeakMap,U6=new WeakMap;jl=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,s=this.ZERO){let n=e;for(;t>ii;)t&Rn&&(s=s.add(n)),n=n.double(),t>>=Rn;return s}precomputeWindow(e,t){let{windows:s,windowSize:n}=zp(t,this.bits),o=[],i=e,a=i;for(let c=0;c<s;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE,i=zp(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:d,offsetF:f}=L6(s,a,i);s=c,u?o=o.add(qa(d,t[f])):n=n.add(qa(h,t[l]))}return N6(s),{p:n,f:o}}wNAFUnsafe(e,t,s,n=this.ZERO){let o=zp(e,this.bits);for(let i=0;i<o.windows&&s!==ii;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=L6(s,i,o);if(s=a,!l){let h=t[c];n=n.add(u?h.negate():h)}}return N6(s),n}getPrecomputes(e,t,s){let n=qp.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof s=="function"&&(n=s(n)),qp.set(t,n))),n}cached(e,t,s){let n=$p(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){let o=$p(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,s),t,n)}createCache(e,t){F6(t,this.bits),U6.set(e,t),qp.delete(e)}hasCache(e){return $p(e)!==1}}});var Yl,Vp,$6=A(()=>{Qs();Yl=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Ul(e),Te(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 s=this.blockLen,n=new Uint8Array(s);n.set(t.length>s?e.create().update(t).digest():t);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),kn(n)}update(e){return ei(this),this.iHash.update(e),this}digestInto(e){ei(this),Te(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:s,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Vp=(r,e,t)=>new Yl(r,e).update(t).digest();Vp.create=(r,e)=>new Yl(r,e)});function R8(r,e,t){let[[s,n],[o,i]]=e,a=G6(i*r,t),c=G6(-n*r,t),l=r-a*s-c*o,u=-a*n-c*i,h=l<Es,d=u<Es;h&&(l=-l),d&&(u=-u);let f=Ha(Math.ceil(Lp(t)/2))+ai;if(l<Es||l>=f||u<Es||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:d,k2:u}}function jp(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Wp(r,e){let t={};for(let s of Object.keys(e))t[s]=r[s]===void 0?e[s]:r[s];return Ua(t.lowS,"lowS"),Ua(t.prehash,"prehash"),t.format!==void 0&&jp(t.format),t}function W6(r,e={}){let t=H6("weierstrass",r,e),{Fp:s,Fn:n}=t,o=t.CURVE,{h:i,n:a}=o;za(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!s.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Y6(s,n);function u(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(B,I,S){let{x:_,y:k}=I.toAffine(),O=s.toBytes(_);if(Ua(S,"isCompressed"),S){u();let N=!s.isOdd(k);return Or(j6(N),O)}else return Or(Uint8Array.of(4),O,s.toBytes(k))}function d(B){Te(B,void 0,"Point");let{publicKey:I,publicKeyUncompressed:S}=l,_=B.length,k=B[0],O=B.subarray(1);if(_===I&&(k===2||k===3)){let N=s.fromBytes(O);if(!s.isValid(N))throw new Error("bad point: is not on curve, wrong x");let T=m(N),L;try{L=s.sqrt(T)}catch(ne){let ae=ne instanceof Error?": "+ne.message:"";throw new Error("bad point: is not on curve, sqrt error"+ae)}u();let K=s.isOdd(L);return(k&1)===1!==K&&(L=s.neg(L)),{x:N,y:L}}else if(_===S&&k===4){let N=s.BYTES,T=s.fromBytes(O.subarray(0,N)),L=s.fromBytes(O.subarray(N,N*2));if(!g(T,L))throw new Error("bad point: is not on curve");return{x:T,y:L}}else throw new Error(`bad point: got length ${_}, expected compressed=${I} or uncompressed=${S}`)}let f=e.toBytes||h,p=e.fromBytes||d;function m(B){let I=s.sqr(B),S=s.mul(I,B);return s.add(s.add(S,s.mul(B,o.a)),o.b)}function g(B,I){let S=s.sqr(I),_=m(B);return s.eql(S,_)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=s.mul(s.pow(o.a,Xl),L8),b=s.mul(s.sqr(o.b),BigInt(27));if(s.is0(s.add(y,b)))throw new Error("bad curve params: a or b");function w(B,I,S=!1){if(!s.isValid(I)||S&&s.is0(I))throw new Error(`bad point coordinate ${B}`);return I}function x(B){if(!(B instanceof v))throw new Error("Weierstrass Point expected")}function E(B){if(!c||!c.basises)throw new Error("no endo");return R8(B,c.basises,n.ORDER)}let P=Np((B,I)=>{let{X:S,Y:_,Z:k}=B;if(s.eql(k,s.ONE))return{x:S,y:_};let O=B.is0();I==null&&(I=O?s.ONE:s.inv(k));let N=s.mul(S,I),T=s.mul(_,I),L=s.mul(k,I);if(O)return{x:s.ZERO,y:s.ZERO};if(!s.eql(L,s.ONE))throw new Error("invZ was invalid");return{x:N,y:T}}),C=Np(B=>{if(B.is0()){if(e.allowInfinityPoint&&!s.is0(B.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:S}=B.toAffine();if(!s.isValid(I)||!s.isValid(S))throw new Error("bad point: x or y not field elements");if(!g(I,S))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function D(B,I,S,_,k){return S=new v(s.mul(S.X,B),S.Y,S.Z),I=qa(_,I),S=qa(k,S),I.add(S)}class v{static BASE=new v(o.Gx,o.Gy,s.ONE);static ZERO=new v(s.ZERO,s.ONE,s.ZERO);static Fp=s;static Fn=n;X;Y;Z;constructor(I,S,_){this.X=w("x",I),this.Y=w("y",S,!0),this.Z=w("z",_),Object.freeze(this)}static CURVE(){return o}static fromAffine(I){let{x:S,y:_}=I||{};if(!I||!s.isValid(S)||!s.isValid(_))throw new Error("invalid affine point");if(I instanceof v)throw new Error("projective point not allowed");return s.is0(S)&&s.is0(_)?v.ZERO:new v(S,_,s.ONE)}static fromBytes(I){let S=v.fromAffine(p(Te(I,void 0,"point")));return S.assertValidity(),S}static fromHex(I){return v.fromBytes(Mn(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,S=!0){return F.createCache(this,I),S||this.multiply(Xl),this}assertValidity(){C(this)}hasEvenY(){let{y:I}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(I)}equals(I){x(I);let{X:S,Y:_,Z:k}=this,{X:O,Y:N,Z:T}=I,L=s.eql(s.mul(S,T),s.mul(O,k)),K=s.eql(s.mul(_,T),s.mul(N,k));return L&&K}negate(){return new v(this.X,s.neg(this.Y),this.Z)}double(){let{a:I,b:S}=o,_=s.mul(S,Xl),{X:k,Y:O,Z:N}=this,T=s.ZERO,L=s.ZERO,K=s.ZERO,z=s.mul(k,k),ne=s.mul(O,O),ae=s.mul(N,N),Q=s.mul(k,O);return Q=s.add(Q,Q),K=s.mul(k,N),K=s.add(K,K),T=s.mul(I,K),L=s.mul(_,ae),L=s.add(T,L),T=s.sub(ne,L),L=s.add(ne,L),L=s.mul(T,L),T=s.mul(Q,T),K=s.mul(_,K),ae=s.mul(I,ae),Q=s.sub(z,ae),Q=s.mul(I,Q),Q=s.add(Q,K),K=s.add(z,z),z=s.add(K,z),z=s.add(z,ae),z=s.mul(z,Q),L=s.add(L,z),ae=s.mul(O,N),ae=s.add(ae,ae),z=s.mul(ae,Q),T=s.sub(T,z),K=s.mul(ae,ne),K=s.add(K,K),K=s.add(K,K),new v(T,L,K)}add(I){x(I);let{X:S,Y:_,Z:k}=this,{X:O,Y:N,Z:T}=I,L=s.ZERO,K=s.ZERO,z=s.ZERO,ne=o.a,ae=s.mul(o.b,Xl),Q=s.mul(S,O),le=s.mul(_,N),Ee=s.mul(k,T),Ze=s.add(S,_),he=s.add(O,N);Ze=s.mul(Ze,he),he=s.add(Q,le),Ze=s.sub(Ze,he),he=s.add(S,k);let it=s.add(O,T);return he=s.mul(he,it),it=s.add(Q,Ee),he=s.sub(he,it),it=s.add(_,k),L=s.add(N,T),it=s.mul(it,L),L=s.add(le,Ee),it=s.sub(it,L),z=s.mul(ne,he),L=s.mul(ae,Ee),z=s.add(L,z),L=s.sub(le,z),z=s.add(le,z),K=s.mul(L,z),le=s.add(Q,Q),le=s.add(le,Q),Ee=s.mul(ne,Ee),he=s.mul(ae,he),le=s.add(le,Ee),Ee=s.sub(Q,Ee),Ee=s.mul(ne,Ee),he=s.add(he,Ee),Q=s.mul(le,he),K=s.add(K,Q),Q=s.mul(it,he),L=s.mul(Ze,L),L=s.sub(L,Q),Q=s.mul(Ze,le),z=s.mul(it,z),z=s.add(z,Q),new v(L,K,z)}subtract(I){return this.add(I.negate())}is0(){return this.equals(v.ZERO)}multiply(I){let{endo:S}=e;if(!n.isValidNot0(I))throw new Error("invalid scalar: out of range");let _,k,O=N=>F.cached(this,N,T=>Gp(v,T));if(S){let{k1neg:N,k1:T,k2neg:L,k2:K}=E(I),{p:z,f:ne}=O(T),{p:ae,f:Q}=O(K);k=ne.add(Q),_=D(S.beta,z,ae,N,L)}else{let{p:N,f:T}=O(I);_=N,k=T}return Gp(v,[_,k])[0]}multiplyUnsafe(I){let{endo:S}=e,_=this;if(!n.isValid(I))throw new Error("invalid scalar: out of range");if(I===Es||_.is0())return v.ZERO;if(I===ai)return _;if(F.hasCache(this))return this.multiply(I);if(S){let{k1neg:k,k1:O,k2neg:N,k2:T}=E(I),{p1:L,p2:K}=K6(v,_,O,T);return D(S.beta,L,K,k,N)}else return F.unsafe(_,I)}toAffine(I){return P(this,I)}isTorsionFree(){let{isTorsionFree:I}=e;return i===ai?!0:I?I(v,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return i===ai?this:I?I(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(I=!0){return Ua(I,"isCompressed"),this.assertValidity(),f(v,this,I)}toHex(I=!0){return Dn(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let M=n.BITS,F=new jl(v,e.endo?Math.ceil(M/2):M);return v.BASE.precompute(8),v}function j6(r){return Uint8Array.of(r?2:3)}function Y6(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function N8(r,e={}){let{Fn:t}=r,s=e.randomBytes||ti,n=Object.assign(Y6(r.Fp,t),{seed:Kp(t.ORDER)});function o(f){try{let p=t.fromBytes(f);return t.isValidNot0(p)}catch{return!1}}function i(f,p){let{publicKey:m,publicKeyUncompressed:g}=n;try{let y=f.length;return p===!0&&y!==m||p===!1&&y!==g?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=s(n.seed)){return Hp(Te(f,n.seed,"seed"),t.ORDER)}function c(f,p=!0){return r.BASE.multiply(t.fromBytes(f)).toBytes(p)}function l(f){let{secretKey:p,publicKey:m,publicKeyUncompressed:g}=n;if(!Na(f)||"_lengths"in t&&t._lengths||p===m)return;let y=Te(f,void 0,"key").length;return y===m||y===g}function u(f,p,m=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(f);return r.fromBytes(p).multiply(g).toBytes(m)}let h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},d=z6(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:h,lengths:n})}function X6(r,e,t={}){Ul(e),za(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let s=t.randomBytes||ti,n=t.hmac||((S,_)=>Vp(e,S,_)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:f}=N8(r,t),p={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*V6<o.ORDER;function g(S){let _=a>>ai;return S>_}function y(S,_){if(!i.isValidNot0(_))throw new Error(`invalid signature ${S}: 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 w(S,_){jp(_);let k=f.signature,O=_==="compact"?k:_==="recovered"?k+1:void 0;return Te(S,O)}class x{r;s;recovery;constructor(_,k,O){if(this.r=y("r",_),this.s=y("s",k),O!=null){if(b(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(_,k=p.format){w(_,k);let O;if(k==="der"){let{r:K,s:z}=en.toSig(Te(_));return new x(K,z)}k==="recovered"&&(O=_[0],k="compact",_=_.subarray(1));let N=f.signature/2,T=_.subarray(0,N),L=_.subarray(N,N*2);return new x(i.fromBytes(T),i.fromBytes(L),O)}static fromHex(_,k){return this.fromBytes(Mn(_),k)}assertRecovery(){let{recovery:_}=this;if(_==null)throw new Error("invalid recovery id: must be present");return _}addRecoveryBit(_){return new x(this.r,this.s,_)}recoverPublicKey(_){let{r:k,s:O}=this,N=this.assertRecovery(),T=N===2||N===3?k+a:k;if(!o.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let L=o.toBytes(T),K=r.fromBytes(Or(j6((N&1)===0),L)),z=i.inv(T),ne=P(Te(_,void 0,"msgHash")),ae=i.create(-ne*z),Q=i.create(O*z),le=r.BASE.multiplyUnsafe(ae).add(K.multiplyUnsafe(Q));if(le.is0())throw new Error("invalid recovery: point at infinify");return le.assertValidity(),le}hasHighS(){return g(this.s)}toBytes(_=p.format){if(jp(_),_==="der")return Mn(en.hexFromSig(this));let{r:k,s:O}=this,N=i.toBytes(k),T=i.toBytes(O);return _==="recovered"?(b(),Or(Uint8Array.of(this.assertRecovery()),N,T)):Or(N,T)}toHex(_){return Dn(this.toBytes(_))}}let E=t.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");let k=ni(_),O=_.length*8-c;return O>0?k>>BigInt(O):k},P=t.bits2int_modN||function(_){return i.create(E(_))},C=Ha(c);function D(S){return S6("num < 2^"+c,S,Es,C),i.toBytes(S)}function v(S,_){return Te(S,void 0,"message"),_?Te(e(S),void 0,"prehashed message"):S}function M(S,_,k){let{lowS:O,prehash:N,extraEntropy:T}=Wp(k,p);S=v(S,N);let L=P(S),K=i.fromBytes(_);if(!i.isValidNot0(K))throw new Error("invalid private key");let z=[D(K),D(L)];if(T!=null&&T!==!1){let le=T===!0?s(f.secretKey):T;z.push(Te(le,void 0,"extraEntropy"))}let ne=Or(...z),ae=L;function Q(le){let Ee=E(le);if(!i.isValidNot0(Ee))return;let Ze=i.inv(Ee),he=r.BASE.multiply(Ee).toAffine(),it=i.create(he.x);if(it===Es)return;let zo=i.create(Ze*i.create(ae+it*K));if(zo===Es)return;let ya=(he.x===it?0:2)|Number(he.y&ai),ba=zo;return O&&g(zo)&&(ba=i.neg(zo),ya^=1),new x(it,ba,m?void 0:ya)}return{seed:ne,k2sig:Q}}function F(S,_,k={}){let{seed:O,k2sig:N}=M(S,_,k);return I6(e.outputLen,i.BYTES,n)(O,N).toBytes(k.format)}function B(S,_,k,O={}){let{lowS:N,prehash:T,format:L}=Wp(O,p);if(k=Te(k,void 0,"publicKey"),_=v(_,T),!Na(S)){let K=S instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+K)}w(S,L);try{let K=x.fromBytes(S,L),z=r.fromBytes(k);if(N&&K.hasHighS())return!1;let{r:ne,s:ae}=K,Q=P(_),le=i.inv(ae),Ee=i.create(Q*le),Ze=i.create(ne*le),he=r.BASE.multiplyUnsafe(Ee).add(z.multiplyUnsafe(Ze));return he.is0()?!1:i.create(he.x)===ne}catch{return!1}}function I(S,_,k={}){let{prehash:O}=Wp(k,p);return _=v(_,O),x.fromBytes(S,"recovered").recoverPublicKey(_).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:f,Point:r,sign:F,verify:B,recoverPublicKey:I,Signature:x,hash:e})}var G6,Yp,en,Es,ai,V6,Xl,L8,Z6=A(()=>{$6();Qs();Gl();q6();Wl();G6=(r,e)=>(r+(r>=0?e:-e)/V6)/e;Yp=class extends Error{constructor(e=""){super(e)}},en={Err:Yp,_tlv:{encode:(r,e)=>{let{Err:t}=en;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let s=e.length/2,n=Ka(s);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let o=s>127?Ka(n.length/2|128):"";return Ka(r)+o+n+e},decode(r,e){let{Err:t}=en,s=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==r)throw new t("tlv.decode: wrong tlv");let n=e[s++],o=!!(n&128),i=0;if(!o)i=n;else{let c=n&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(s,s+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(s+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(s,s+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+i)}}},_int:{encode(r){let{Err:e}=en;if(r<Es)throw new e("integer: negative integers are not allowed");let t=Ka(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}=en;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 ni(r)}},toSig(r){let{Err:e,_int:t,_tlv:s}=en,n=Te(r,void 0,"signature"),{v:o,l:i}=s.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=s.decode(2,o),{v:l,l:u}=s.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}=en,s=e.encode(2,t.encode(r.r)),n=e.encode(2,t.encode(r.s)),o=s+n;return e.encode(48,o)}},Es=BigInt(0),ai=BigInt(1),V6=BigInt(2),Xl=BigInt(3),L8=BigInt(4)});function F8(r){let e=Zp.p,t=BigInt(3),s=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,h=tr(u,t,e)*u%e,d=tr(h,t,e)*u%e,f=tr(d,Q6,e)*l%e,p=tr(f,n,e)*f%e,m=tr(p,o,e)*p%e,g=tr(m,a,e)*m%e,y=tr(g,c,e)*g%e,b=tr(y,a,e)*m%e,w=tr(b,t,e)*u%e,x=tr(w,i,e)*p%e,E=tr(x,s,e)*l%e,P=tr(E,Q6,e);if(!Xp.eql(Xp.sqr(P),r))throw new Error("Cannot find square root");return P}var Zp,B8,Q6,Xp,U8,Ss,Qp=A(()=>{bp();Wl();Z6();Zp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},B8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Q6=BigInt(2);Xp=oi(Zp.p,{sqrt:F8}),U8=W6(Zp,{Fp:Xp,endo:B8}),Ss=X6(U8,ri)});var Zl,Ql,J6=A(()=>{Zl=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Ql=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}});function e5(r,e,t){t?.signal?.throwIfAborted();let s=Jp.default.createHash("sha256");if(e instanceof Uint8Array)s.update(e);else for(let o of e)s.update(o);let n=s.digest();try{return Ss.sign(n,r,{prehash:!1,format:"der"})}catch(o){throw new Zl(String(o))}}function t5(r,e,t,s){s?.signal?.throwIfAborted();let n=Jp.default.createHash("sha256");if(t instanceof Uint8Array)n.update(t);else for(let i of t)n.update(i);let o=n.digest();try{return Ss.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new Ql(String(i))}}var Jp,r5=A(()=>{Jp=xe(oe("node:crypto"),1);Qp();J6()});var $a,Jl,s5=A(()=>{Qt();Cr();In();Gt();lt();e0();r5();$a=class{type="secp256k1";raw;_key;constructor(e){this._key=i5(e),this.raw=n5(this._key)}toMultihash(){return Pr.digest(He(this))}toCID(){return Re.createV1(114,this.toMultihash())}toString(){return ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}verify(e,t,s){return t5(this._key,t,e,s)}},Jl=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=o5(e),this.publicKey=new $a(t??a5(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}sign(e,t){return e5(this.raw,e,t)}}});function t0(r){return new $a(r)}async function c5(){let r=K8();return new Jl(r)}function n5(r){return Ss.Point.fromBytes(r).toBytes()}function o5(r){try{return Ss.getPublicKey(r,!0),r}catch(e){throw new Ea(String(e))}}function i5(r){try{return Ss.Point.fromBytes(r),r}catch(e){throw new Vo(String(e))}}function a5(r){try{return Ss.getPublicKey(r,!0)}catch(e){throw new Ea(String(e))}}function K8(){return Ss.utils.randomSecretKey()}var e0=A(()=>{Ys();Qp();s5()});async function l5(r,e){if(r==="Ed25519")return qy();if(r==="secp256k1")return c5();if(r==="RSA")return Pp(H8(e));if(r==="ECDSA")return Ly(z8(e));throw new Wo}function nt(r,e){let{Type:t,Data:s}=Yr.decode(r),n=s??new Uint8Array;switch(t){case je.RSA:return Ap(n,e);case je.Ed25519:return Yf(n);case je.secp256k1:return t0(n);case je.ECDSA:return $f(n);default:throw new Wo}}function u5(r){let{Type:e,Data:t}=Yr.decode(r.digest),s=t??new Uint8Array;switch(e){case je.Ed25519:return Yf(s);case je.secp256k1:return t0(s);case je.ECDSA:return $f(s);default:throw new Wo}}function He(r){return Yr.encode({Type:je[r.type],Data:r.raw})}function H8(r){return r==null?2048:parseInt(r,10)}function z8(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 Je("Unsupported curve, should be P-256, P-384 or P-521")}var lt=A(()=>{Ys();Gf();jf();mp();kp();e0()});var h5,d5=A(()=>{h5=Symbol.for("@libp2p/connection")});var f5=A(()=>{});var p5=A(()=>{});var r0,m5=A(()=>{r0=Symbol.for("@libp2p/content-routing")});var g5=A(()=>{});var y5=A(()=>{});var Ga,b5=A(()=>{Ga=Symbol.for("@libp2p/peer-discovery")});function tn(r){return!!r?.[eu]}var eu,w5=A(()=>{eu=Symbol.for("@libp2p/peer-id")});var x5=A(()=>{});var s0,v5=A(()=>{s0=Symbol.for("@libp2p/peer-routing")});var ci,E5=A(()=>{ci="keep-alive"});var Ln,li,Nt,IN,S5=A(()=>{Ln="StrictSign",li="StrictNoSign";(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(Nt||(Nt={}));IN=Symbol.for("@libp2p/pubsub")});var I5=A(()=>{});var _5=A(()=>{});var A5=A(()=>{});var T5=A(()=>{});var tu,Nn,C5=A(()=>{tu=Symbol.for("@libp2p/transport");(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Nn||(Nn={}))});var Bt,ru,su,V,nu,ui,rn,ou,iu,Bn,hi,sn,au,cu,Fn,Ft,lu,Qr,Lr,uu,Is,Un,Va,hu,di,du,P5=A(()=>{Bt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},ru=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},su=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},V=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},nu=class extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},ui=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},rn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},ou=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},iu=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Bn=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},hi=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},sn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},au=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},cu=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Fn=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Ft=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},lu=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Qr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Lr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},uu=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}},Is=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Un=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},Va=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},hu=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},di=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},du=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});function fu(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function pu(...r){let e=[];for(let t of r)fu(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 mu(...r){let e=[];for(let t of r)fu(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 k5=A(()=>{});var Ye,Kn,X=A(()=>{d5();f5();p5();m5();g5();y5();b5();w5();x5();v5();E5();S5();I5();_5();A5();T5();C5();P5();Oe();k5();Ye=Symbol.for("@libp2p/service-capabilities"),Kn=Symbol.for("@libp2p/service-dependencies")});var D5,q8,Wa,ja,Ya,Xa,$8,Za,M5=A(()=>{X();Qt();Cr();In();Gt();be();Pe();D5=Symbol.for("nodejs.util.inspect.custom"),q8=114,Wa=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()})`}[eu]=!0;toString(){return this.string==null&&(this.string=ye.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Re.createV1(q8,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return de(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return de(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[D5](){return`PeerId(${this.toString()})`}},ja=class extends Wa{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ya=class extends Wa{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Xa=class extends Wa{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},$8=2336,Za=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Pr.digest(R(this.url))}[D5](){return`PeerId(${this.url})`}[eu]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Re.createV1($8,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=U(e)),e.toString()===this.toString())}}});var o0={};_e(o0,{peerIdFromCID:()=>Jr,peerIdFromMultihash:()=>Ut,peerIdFromPrivateKey:()=>n0,peerIdFromPublicKey:()=>_s,peerIdFromString:()=>G});function G(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=ct(ye.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Jr(Re.parse(r));if(e==null)throw new V('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=ct(e.decode(r))}return Ut(t)}function _s(r){if(r.type==="Ed25519")return new Ya({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Xa({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ja({multihash:r.toCID().multihash,publicKey:r});throw new du}function n0(r){return _s(r.publicKey)}function Ut(r){if(W8(r))return new ja({multihash:r});if(V8(r))try{let e=u5(r);if(e.type==="Ed25519")return new Ya({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Xa({multihash:r,publicKey:e})}catch{let t=U(r.digest);return new Za(new URL(t))}throw new cu("Supplied PeerID Multihash is invalid")}function Jr(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==G8&&r.code!==O5)throw new au("Supplied PeerID CID is invalid");if(r.code===O5){let e=U(r.multihash.digest);return new Za(new URL(e))}return Ut(r.multihash)}function V8(r){return r.code===Pr.code}function W8(r){return r.code===et.code}var G8,O5,ce=A(()=>{lt();X();Qt();Cr();Vt();In();jr();Pe();M5();G8=114,O5=2336});var R0=A(()=>{"use strict"});var lb=We((KH,cb)=>{var wi=1e3,xi=wi*60,vi=xi*60,Gn=vi*24,IA=Gn*7,_A=Gn*365.25;cb.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return AA(r);if(t==="number"&&isFinite(r))return e.long?CA(r):TA(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function AA(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]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return t*_A;case"weeks":case"week":case"w":return t*IA;case"days":case"day":case"d":return t*Gn;case"hours":case"hour":case"hrs":case"hr":case"h":return t*vi;case"minutes":case"minute":case"mins":case"min":case"m":return t*xi;case"seconds":case"second":case"secs":case"sec":case"s":return t*wi;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function TA(r){var e=Math.abs(r);return e>=Gn?Math.round(r/Gn)+"d":e>=vi?Math.round(r/vi)+"h":e>=xi?Math.round(r/xi)+"m":e>=wi?Math.round(r/wi)+"s":r+"ms"}function CA(r){var e=Math.abs(r);return e>=Gn?xu(r,e,Gn,"day"):e>=vi?xu(r,e,vi,"hour"):e>=xi?xu(r,e,xi,"minute"):e>=wi?xu(r,e,wi,"second"):r+" ms"}function xu(r,e,t,s){var n=e>=t*1.5;return Math.round(r/t)+" "+s+(n?"s":"")}});var N0=We((HH,ub)=>{function PA(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=n,t.enabled=a,t.humanize=lb(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let h=0;for(let d=0;d<u.length;d++)h=(h<<5)-h+u.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(u){let h,d=null,f,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(h||b);y.diff=w,y.prev=h,y.curr=b,h=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,(P,C)=>{if(P==="%%")return"%";x++;let D=t.formatters[C];if(typeof D=="function"){let v=g[x];P=D.call(y,v),g.splice(x,1),x--}return P}),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=s,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(u)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function s(u,h){let d=t(this.namespace+(typeof h>"u"?":":h)+u);return d.log=this.log,d}function n(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let h=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of h)d[0]==="-"?t.skips.push(d.slice(1)):t.names.push(d)}function o(u,h){let d=0,f=0,p=-1,m=0;for(;d<u.length;)if(f<h.length&&(h[f]===u[d]||h[f]==="*"))h[f]==="*"?(p=f,m=d,f++):(d++,f++);else if(p!==-1)f=p+1,m++,d=m;else return!1;for(;f<h.length&&h[f]==="*";)f++;return f===h.length}function i(){let u=[...t.names,...t.skips.map(h=>"-"+h)].join(",");return t.enable(""),u}function a(u){for(let h of t.skips)if(o(u,h))return!1;for(let h of t.names)if(o(u,h))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}ub.exports=PA});var hb=We((jt,vu)=>{jt.formatArgs=DA;jt.save=MA;jt.load=OA;jt.useColors=kA;jt.storage=RA();jt.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`."))}})();jt.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 kA(){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 DA(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+vu.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,s=0;r[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(s=t))}),r.splice(s,0,e)}jt.log=console.debug||console.log||(()=>{});function MA(r){try{r?jt.storage.setItem("debug",r):jt.storage.removeItem("debug")}catch{}}function OA(){let r;try{r=jt.storage.getItem("debug")||jt.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function RA(){try{return localStorage}catch{}}vu.exports=N0()(jt);var{formatters:LA}=vu.exports;LA.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var fb=We((zH,db)=>{"use strict";db.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",s=e.indexOf(t+r),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}});var gb=We((qH,mb)=>{"use strict";var NA=oe("os"),pb=oe("tty"),gr=fb(),{env:ut}=process,on;gr("no-color")||gr("no-colors")||gr("color=false")||gr("color=never")?on=0:(gr("color")||gr("colors")||gr("color=true")||gr("color=always"))&&(on=1);"FORCE_COLOR"in ut&&(ut.FORCE_COLOR==="true"?on=1:ut.FORCE_COLOR==="false"?on=0:on=ut.FORCE_COLOR.length===0?1:Math.min(parseInt(ut.FORCE_COLOR,10),3));function B0(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function F0(r,e){if(on===0)return 0;if(gr("color=16m")||gr("color=full")||gr("color=truecolor"))return 3;if(gr("color=256"))return 2;if(r&&!e&&on===void 0)return 0;let t=on||0;if(ut.TERM==="dumb")return t;if(process.platform==="win32"){let s=NA.release().split(".");return Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in ut)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(s=>s in ut)||ut.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in ut)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ut.TEAMCITY_VERSION)?1:0;if(ut.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ut){let s=parseInt((ut.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ut.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ut.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ut.TERM)||"COLORTERM"in ut?1:t}function BA(r){let e=F0(r,r&&r.isTTY);return B0(e)}mb.exports={supportsColor:BA,stdout:B0(F0(!0,pb.isatty(1))),stderr:B0(F0(!0,pb.isatty(2)))}});var bb=We((ht,Su)=>{var FA=oe("tty"),Eu=oe("util");ht.init=GA;ht.log=zA;ht.formatArgs=KA;ht.save=qA;ht.load=$A;ht.useColors=UA;ht.destroy=Eu.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ht.colors=[6,2,3,4,5,1];try{let r=gb();r&&(r.stderr||r).level>=2&&(ht.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{}ht.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,o)=>o.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function UA(){return"colors"in ht.inspectOpts?!!ht.inspectOpts.colors:FA.isatty(process.stderr.fd)}function KA(r){let{namespace:e,useColors:t}=this;if(t){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),o=` ${n};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
3
3
  `).join(`
4
- `+o),r.push(n+"m+"+Jl.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=D_()+e+" "+r[0]}function D_(){return at.inspectOpts.hideDate?"":new Date().toISOString()+" "}function M_(...r){return process.stderr.write(Ql.formatWithOptions(at.inspectOpts,...r)+`
5
- `)}function O_(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function L_(){return process.env.DEBUG}function R_(r){r.inspectOpts={};let e=Object.keys(at.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=at.inspectOpts[e[t]]}Jl.exports=Jp()(at);var{formatters:A5}=Jl.exports;A5.o=function(r){return this.inspectOpts.colors=this.useColors,Ql.inspect(r,this.inspectOpts).split(`
6
- `).map(e=>e.trim()).join(" ")};A5.O=function(r){return this.inspectOpts.colors=this.useColors,Ql.inspect(r,this.inspectOpts)}});var s0=He((CK,r0)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?r0.exports=x5():r0.exports=C5()});var T4=He((R$,C4)=>{C4.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),s=Object.create(null);function n(o,i){t[o]=i,e++,e>=r&&(e=0,s=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||s[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),s[o]!==void 0&&(s[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=s[o])!==void 0)return n(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:n(o,i)},clear:function(){t=Object.create(null),s=Object.create(null)}}}});var ub=He(wc=>{(function(){var r,e,t,s,n,o,i,a;a=function(c){var l,u,h,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,d=c&255,[l,u,h,d].join(".")},i=function(c){var l,u,h,d,f,p;for(l=[],h=d=0;d<=3&&c.length!==0;h=++d){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),f=p[0],u=p[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)},s=t("0"),o=t("a"),n=t("A"),e=function(c){var l,u,h,d,f;for(d=0,l=10,u="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,u="7")),f=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)d=d*l+(t(c[h])-s)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")d=d*l+(10+t(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")d=d*l+(10+t(c[h])-n)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");h++}if(h===f)throw new Error("empty octet");return[d,h]},r=(function(){function c(l,u){var h,d,f,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw h=m,new Error("Invalid mask: "+u)}for(d=f=32;f>=0;d=--f)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;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 h=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,h,d;for(d=i(this.first),h=i(this.last),u=0;d<=h;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),wc.ip2long=i,wc.long2ip=a,wc.Netmask=r}).call(wc)});var Fb=He((rZ,Bb)=>{function mr(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Bb.exports=mr;mr.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};mr.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};mr.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var s=this;return this._timer=setTimeout(function(){s._attempts++,s._operationTimeoutCb&&(s._timeout=setTimeout(function(){s._operationTimeoutCb(s._attempts)},s._operationTimeout),s._options.unref&&s._timeout.unref()),s._fn(s._attempts)},t),this._options.unref&&this._timer.unref(),!0};mr.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};mr.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};mr.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};mr.prototype.start=mr.prototype.try;mr.prototype.errors=function(){return this._errors};mr.prototype.attempts=function(){return this._attempts};mr.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,s=0;s<this._errors.length;s++){var n=this._errors[s],o=n.message,i=(r[o]||0)+1;r[o]=i,i>=t&&(e=n,t=i)}return e}});var Ub=He(uo=>{var p7=Fb();uo.operation=function(r){var e=uo.timeouts(r);return new p7(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};uo.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var s=[],n=0;n<e.retries;n++)s.push(this.createTimeout(n,e));return r&&r.forever&&!s.length&&s.push(this.createTimeout(n,e)),s.sort(function(o,i){return o-i}),s};uo.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,s=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return s=Math.min(s,e.maxTimeout),s};uo.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var s in r)typeof r[s]=="function"&&t.push(s)}for(var n=0;n<t.length;n++){var o=t[n],i=r[o];r[o]=function(c){var l=uo.operation(e),u=Array.prototype.slice.call(arguments,1),h=u.pop();u.push(function(d){l.retry(d)||(d&&(arguments[0]=l.mainError()),h.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,i),r[o].options=e}}});var Hb=He((nZ,Kb)=>{Kb.exports=Ub()});var sm=He(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.TAG_LENGTH=es.DATA_CHUNK_LENGTH=es.NONCE_LENGTH=es.KEY_LENGTH=void 0;es.KEY_LENGTH=32;es.NONCE_LENGTH=12;es.DATA_CHUNK_LENGTH=65536;es.TAG_LENGTH=16});var pw=He(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});th.ChaCha20Poly1305=void 0;var Ue=sm(),nm=class{constructor(e){this.ctx=e;let t=e.cpKey.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,Ue.KEY_LENGTH);let s=e.cpNonce.value;this.wasmNonceArr=new Uint8Array(e.memory.buffer,s,Ue.NONCE_LENGTH);let n=e.cpAssociatedData.value;this.wasmAdArr=new Uint8Array(e.memory.buffer,n,Ue.KEY_LENGTH);let o=e.cpInput.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,o,Ue.DATA_CHUNK_LENGTH);let i=e.chacha20Output.value;this.wasmChacha20OutputArr=new Uint8Array(e.memory.buffer,i,Ue.DATA_CHUNK_LENGTH);let a=e.poly1305Output.value;this.wasmPoly1305OutputArr=new Uint8Array(e.memory.buffer,a,Ue.TAG_LENGTH);let c=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,c,64)}seal(e,t,s,n,o){this.init(e,t,n);let i=s.length+Ue.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=n?.length??0;return this.sealUpdate(s,c,a),a.set(this.wasmPoly1305OutputArr,s.length),a}open(e,t,s,n,o){this.init(e,t,n);let i=s.subarray(0,s.length-Ue.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=n?.length??0;this.openUpdate(i,c,a);let l=s.subarray(s.length-Ue.TAG_LENGTH,s.length);return this.isSameTag(l)?a:null}init(e,t,s=new Uint8Array(0)){if(e.length!=Ue.KEY_LENGTH)throw Error(`Invalid chacha20poly1305 key length ${e.length}, expect ${Ue.KEY_LENGTH}`);if(s.length>Ue.KEY_LENGTH)throw Error(`Invalid ad length ${s.length}, expect <= ${Ue.KEY_LENGTH}`);if(t.length!==Ue.NONCE_LENGTH)throw Error(`Invalid nonce length ${t.length}, expect ${Ue.NONCE_LENGTH}`);this.wasmKeyArr.set(e),this.wasmNonceArr.set(t),this.wasmAdArr.set(s)}openUpdate(e,t,s){this.commonUpdate(e,this.ctx.openUpdate,t,s)}sealUpdate(e,t,s){this.commonUpdate(e,this.ctx.sealUpdate,t,s)}commonUpdate(e,t,s,n){let o=e.length;if(e.length<=Ue.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),t(!0,!0,o,o,s),n.set(o===Ue.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,o));return}for(let i=0;i<o;i+=Ue.DATA_CHUNK_LENGTH){let a=Math.min(o,i+Ue.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(i,a));let c=i===0,l=i+Ue.DATA_CHUNK_LENGTH>=o;t(c,l,a-i,o,s),n.set(a-i===Ue.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,a-i),i)}}isSameTag(e){let t=!0;for(let s=0;s<Ue.TAG_LENGTH;s++)if(this.wasmPoly1305OutputArr[s]!==e[s]){t=!1;break}return t}};th.ChaCha20Poly1305=nm});var mw=He(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});rh.Poly1305=void 0;var _s=sm(),om=class{constructor(e){this.ctx=e;let t=e.poly1305Key.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,_s.KEY_LENGTH);let s=e.poly1305Input.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,s,_s.DATA_CHUNK_LENGTH);let n=e.poly1305Output.value;this.wasmOutputArr=new Uint8Array(e.memory.buffer,n,_s.TAG_LENGTH);let o=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,o,64)}init(e){if(e.length!=_s.KEY_LENGTH)throw Error(`Invalid poly1305 key length ${e.length}, expect ${_s.KEY_LENGTH}`);this.wasmKeyArr.set(e),this.ctx.poly1305Init()}update(e){if(e.length<=_s.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),this.ctx.poly1305Update(e.length);return}for(let t=0;t<e.length;t+=_s.DATA_CHUNK_LENGTH){let s=Math.min(e.length,t+_s.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(t,s)),this.ctx.poly1305Update(s-t)}}digest(){this.ctx.poly1305Digest();let e=new Uint8Array(_s.TAG_LENGTH);return e.set(this.wasmOutputArr),e}};rh.Poly1305=om});var gw=He(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});sh.wasmCode=void 0;sh.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 im=He(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});nh.newInstance=void 0;var G7=gw(),V7=new WebAssembly.Module(G7.wasmCode),W7={env:{abort:function(r,e,t,s){throw Error(`abort: ${r}:${e}:${t}:${s}`)}}};function j7(){return new WebAssembly.Instance(V7,W7).exports}nh.newInstance=j7});var ww=He(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});oh.chacha20StreamXOR=void 0;var Y7=im(),ts=Y7.newInstance(),X7=ts.chacha20Input.value,Z7=ts.chacha20Output.value,Q7=ts.chacha20Key.value,J7=ts.chacha20Counter.value,{CHACHA20_INPUT_LENGTH:Mi,KEY_LENGTH:am,CHACHA20_COUNTER_LENGTH:bw}=ts,eT=new Uint8Array(ts.memory.buffer,X7,Mi),yw=new Uint8Array(ts.memory.buffer,Z7,Mi),tT=new Uint8Array(ts.memory.buffer,Q7,am),rT=new Uint8Array(ts.memory.buffer,J7,bw);function sT(r,e,t){if(r.length!=am)throw new Error("ChaCha: key size must be 32 bytes, expected "+am+" got "+r.length);if(e.length!=bw)throw new Error("ChaCha nonce with counter must be 16 bytes");tT.set(r),rT.set(e);let s=new Uint8Array(t.length),n=Math.floor(t.length/Mi);for(let o=0;o<=n;o++){let i=o*Mi,a=Math.min((o+1)*Mi,t.length);eT.set(n===0?t:t.subarray(i,a));let c=a-i,l=ts.chacha20StreamXORUpdate(c);s.set(l===Mi?yw:yw.subarray(0,l),i)}return s}oh.chacha20StreamXOR=sT});var xw=He(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.newInstance=rs.chacha20StreamXOR=rs.Poly1305=rs.ChaCha20Poly1305=void 0;var nT=pw();Object.defineProperty(rs,"ChaCha20Poly1305",{enumerable:!0,get:function(){return nT.ChaCha20Poly1305}});var oT=mw();Object.defineProperty(rs,"Poly1305",{enumerable:!0,get:function(){return oT.Poly1305}});var iT=ww();Object.defineProperty(rs,"chacha20StreamXOR",{enumerable:!0,get:function(){return iT.chacha20StreamXOR}});var aT=im();Object.defineProperty(rs,"newInstance",{enumerable:!0,get:function(){return aT.newInstance}})});var Cw=He((ite,Aw)=>{function bT(){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)}Aw.exports=bT});var Ov=He((joe,Mv)=>{"use strict";function Oe(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))}Oe.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var s=this.size();if(!(t>=s||t<-s))return t<0&&(t+=s),t=this._head+t&this._capacityMask,this._list[t]}};Oe.prototype.get=function(e){return this.peekAt(e)};Oe.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};Oe.prototype.peekFront=function(){return this.peek()};Oe.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(Oe.prototype,"length",{get:function(){return this.size()}});Oe.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Oe.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)};Oe.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}};Oe.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)};Oe.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var s=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),s}};Oe.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var s=this.size(),n=this._list.length;if(!(t>=s||t<-s)){t<0&&(t+=s),t=this._head+t&this._capacityMask;var o=this._list[t],i;if(e<s/2){for(i=e;i>0;i--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(i=s-1-e;i>0;i--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return o}}};Oe.prototype.remove=function(e,t){var s=e,n,o=t;if(s===(s|0)&&this._head!==this._tail){var i=this.size(),a=this._list.length;if(!(s>=i||s<-i||t<1)){if(s<0&&(s+=i),t===1||!t)return n=new Array(1),n[0]=this.removeOne(s),n;if(s===0&&s+t>=i)return n=this.toArray(),this.clear(),n;s+t>i&&(t=i-s);var c;for(n=new Array(t),c=0;c<t;c++)n[c]=this._list[this._head+s+c&this._capacityMask];if(s=this._head+s&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[s=s+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[s=s+1+a&this._capacityMask]=void 0;return n}if(s<i/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[s=s-1+a&this._capacityMask]);for(s=this._head-1+a&this._capacityMask;o>0;)this._list[s=s-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=s)}else{for(this._tail=s,s=s+t+a&this._capacityMask,c=i-(t+e);c>0;c--)this.push(this._list[s++]);for(s=this._tail;o>0;)this._list[s=s+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};Oe.prototype.splice=function(e,t){var s=e;if(s===(s|0)){var n=this.size();if(s<0&&(s+=n),!(s>n))if(arguments.length>2){var o,i,a,c=arguments.length,l=this._list.length,u=2;if(!n||s<n/2){for(i=new Array(s),o=0;o<s;o++)i[o]=this._list[this._head+o&this._capacityMask];for(t===0?(a=[],s>0&&(this._head=this._head+s+l&this._capacityMask)):(a=this.remove(s,t),this._head=this._head+s+l&this._capacityMask);c>u;)this.unshift(arguments[--c]);for(o=s;o>0;o--)this.unshift(i[o-1])}else{i=new Array(n-(s+t));var h=i.length;for(o=0;o<h;o++)i[o]=this._list[this._head+s+t+o&this._capacityMask];for(t===0?(a=[],s!=n&&(this._tail=this._head+s+l&this._capacityMask)):(a=this.remove(s,t),this._tail=this._tail-h+l&this._capacityMask);u<c;)this.push(arguments[u++]);for(o=0;o<h;o++)this.push(i[o])}return a}else return this.remove(s,t)}};Oe.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};Oe.prototype.isEmpty=function(){return this._head===this._tail};Oe.prototype.toArray=function(){return this._copyArray(!1)};Oe.prototype._fromArray=function(e){var t=e.length,s=this._nextPowerOf2(t);this._list=new Array(s),this._capacityMask=s-1,this._tail=t;for(var n=0;n<t;n++)this._list[n]=e[n]};Oe.prototype._copyArray=function(e,t){var s=this._list,n=s.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<n;c++)i[a++]=s[c];for(c=0;c<this._tail;c++)i[a++]=s[c]}else for(c=this._head;c<this._tail;c++)i[a++]=s[c];return i};Oe.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};Oe.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};Oe.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),s=1<<t+1;return Math.max(s,4)};Mv.exports=Oe});var Ok={};ve(Ok,{ArachnodeFretAdapter:()=>oc,BlockStorage:()=>ci,ClusterClient:()=>Tn,ClusterCoordinator:()=>za,ClusterMember:()=>eu,ClusterService:()=>tu,CoordinatorRepo:()=>ru,FileRawStorage:()=>qa,Libp2pKeyPeerNetwork:()=>ic,MemoryRawStorage:()=>$a,NetworkManagerService:()=>ld,ProtocolClient:()=>cs,RepoClient:()=>i0,RepoService:()=>nu,RestorationCoordinator:()=>rc,RingSelector:()=>sc,SYNC_PROTOCOL_PREFIX:()=>w4,SYNC_PROTOCOL_VERSION:()=>x4,StorageMonitor:()=>nc,StorageRepo:()=>Ga,SyncClient:()=>tc,SyncService:()=>vu,asyncIteratorToArray:()=>na,buildKnownPeers:()=>kk,buildSyncProtocol:()=>ec,clusterMember:()=>n0,clusterService:()=>o0,computeResponsibility:()=>Pk,coordinatorRepo:()=>a0,createLibp2pNode:()=>Tk,first:()=>vd,getNetworkManager:()=>Mk,lessThanLex:()=>oE,networkManagerService:()=>fg,reduce:()=>TE,repoService:()=>c0,sortPeersByDistance:()=>iE,syncService:()=>$0,xorDistanceBytes:()=>nE});function fe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Zc=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}},Po=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Zc(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 Zc(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 hd=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function dt(r={}){return fE(t=>{let s=t.shift();if(s==null)return{done:!0};if(s.error!=null)throw s.error;return{done:s.done===!0,value:s.value}},r)}function fE(r,e){e=e??{};let t=e.onEnd,s=new Po,n,o,i,a=fe(),c=async()=>{try{return s.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{o=w=>{o=null,s.push(w);try{g(r(s))}catch(b){y(b)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fe()})}},l=g=>o!=null?o(g):(s.push(g),n),u=g=>(s=new Po,o!=null?o({error:g}):(s.push({error:g}),n)),h=g=>{if(i)return n;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})},d=g=>i?n:(i=!0,g!=null?u(g):l({done:!0})),f=()=>(s=new Po,d(),{done:!0}),p=g=>(d(g),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:f,throw:p,push:h,end:d,get readableLength(){return s.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),s.isEmpty())return;let w,b;y!=null&&(w=new Promise((x,E)=>{b=()=>{E(new hd)},y.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}finally{b!=null&&y!=null&&y?.removeEventListener("abort",b)}}},t==null)return n;let m=n;return n={[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:h,end(g){return m.end(g),t!=null&&(t(g),t=void 0),n},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},n}var Qc=class extends Error{type;code;constructor(e,t,s){super(e??"The operation was aborted"),this.type="aborted",this.name=s??"AbortError",this.code=t??"ABORT_ERR"}};async function Ce(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Qc(t?.errorMessage,t?.errorCode,t?.errorName));let s,n=new Qc(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n)},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var dd=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=fe(),this.haveNext=fe()}[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=fe(),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=fe(),await Ce(this.readNext.promise,t?.signal,t)}};function Jc(){return new dd}function pE(r){return r[Symbol.asyncIterator]!=null}async function mE(r,e,t){try{await Promise.all(r.map(async s=>{for await(let n of s)await e.push(n,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(s){await e.end(s,{signal:t}).catch(()=>{})}}async function*gE(r){let e=new AbortController,t=Jc();mE(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*yE(r){for(let e of r)yield*e}function bE(...r){let e=[];for(let t of r)pE(t)||e.push(t);return e.length===r.length?yE(e):gE(r)}var dn=bE;function st(r,...e){if(r==null)throw new Error("Empty pipeline");if(fd(r)){let s=r;r=()=>s.source}else if(bg(r)||yg(r)){let s=r;r=()=>s}let t=[r,...e];if(t.length>1&&fd(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let s=1;s<t.length-1;s++)fd(t[s])&&(t[s]=xE(t[s]));return wE(...t)}var wE=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},yg=r=>r?.[Symbol.asyncIterator]!=null,bg=r=>r?.[Symbol.iterator]!=null,fd=r=>r==null?!1:r.sink!=null&&r.source!=null,xE=r=>e=>{let t=r.sink(e);if(t?.then!=null){let s=dt({objectMode:!0});t.then(()=>{s.end()},i=>{s.end(i)});let n,o=r.source;if(yg(o))n=async function*(){yield*o,s.end()};else if(bg(o))n=function*(){yield*o,s.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return dn(s,n())}return r.source};wr();ot();nt();var tl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Do=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},rl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},sa=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function sl(r){return r[Symbol.asyncIterator]!=null}function Eg(r,e){if(r.byteLength>e)throw new Do("Message length too long")}var ol=r=>{let e=Le(r),t=je(e);return rr(r,t),ol.bytes=e,t};ol.bytes=0;function sr(r,e){e=e??{};let t=e.lengthEncoder??ol,s=e?.maxDataLength??4194304;function*n(o){Eg(o,s);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return sl(r)?(async function*(){for await(let o of r)yield*n(o)})():(function*(){for(let o of r)yield*n(o)})()}sr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ol,s=e?.maxDataLength??4194304;return Eg(r,s),new W(t(r.byteLength),r)};wr();ot();var fn;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(fn||(fn={}));var xd=r=>{let e=as(r);return xd.bytes=Le(e),e};xd.bytes=0;function Gt(r,e){let t=new W,s=fn.LENGTH,n=-1,o=e?.lengthDecoder??xd,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(s===fn.LENGTH)try{if(n=o(t),n<0)throw new tl("Invalid message length");if(n>a)throw new Do("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(n),s=fn.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new rl("Message length length too long");break}throw l}if(s===fn.DATA){if(t.byteLength<n)break;let l=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(l),yield l,s=fn.LENGTH}}}return sl(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new sa("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new sa("Unexpected end of input")})()}Gt.fromReader=(r,e)=>{let t=1,s=(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 Gt(s,{...e??{},onLength:o=>{t=o}})};async function vd(r,e=()=>{throw new Error("No items found")},t){let s=new AbortController,n=typeof t=="number"?setTimeout(()=>s.abort(),t):void 0;try{for await(let o of r(s.signal))return o;return e()}finally{n!==void 0&&clearTimeout(n),s.abort()}}async function na(r){let e=[];for await(let t of r)e.push(t);return e}function TE(r,e,t){let s=t,n=0;for(let o of r)s=e(s,o,n),++n;return s}var cs=class{peerId;peerNetwork;constructor(e,t){this.peerId=e,this.peerNetwork=t}async processMessage(e,t,s){let n=await this.peerNetwork.connect(this.peerId,t,{signal:s?.signal});try{let o=st(n.source,Gt,async function*(a){for await(let c of a){let l=new TextDecoder().decode(c.subarray());yield JSON.parse(l)}}),i=dt();return st(i,sr,n.sink),i.push(new TextEncoder().encode(JSON.stringify(e))),i.end(),await vd(()=>o,()=>{throw new Error("No response received")})}finally{n.close()}}};ce();var Tn=class r extends cs{protocolPrefix;constructor(e,t,s){super(e,t),this.protocolPrefix=s}static create(e,t,s){return new r(e,t,s)}async update(e,t=0){let s={operation:"update",record:e},n=(this.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",o;try{o=await this.processMessage(s,n)}catch(i){if(n!=="/db-p2p/cluster/1.0.0")o=await this.processMessage(s,"/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=$(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 s=e?.message,n;if(s?.commit?.tailId)n=s.commit.tailId;else if(s?.pend?.transforms){let o=Object.keys(s.pend.transforms);o.length>0&&(n=o[0])}if(n){let o=new TextEncoder().encode(n),i=this.peerNetwork;typeof i?.recordCoordinator=="function"&&i.recordCoordinator(o,t)}}};var Sp=new Map;function jr(r,e){if(Sp.has(r))throw new Error(`Block type ${r} (${e}) already registered (${Sp.get(r)})`);return Sp.set(r,e),r}function Vl(r,[e,t,s,n]){Array.isArray(n)?r[e].splice(t,s,...structuredClone(n)):r[e]=structuredClone(n)}function F8(r,e){for(let t of e)Vl(r,t)}function Pn(r){if(!r)return[];let e=Object.keys(r.inserts??{}),t=Object.keys(r.updates??{}),s=r.deletes??[];return[...new Set([...e,...t,...s])]}function Ip(){return{inserts:{},updates:{},deletes:[]}}function Wl(r,e){return{...e in r.inserts?{insert:r.inserts[e]}:{},...e in r.updates?{updates:r.updates[e]}:{},...e in r.deletes?{delete:!0}:{}}}function _p(r,e){return{inserts:r.insert?{[e]:r.insert}:{},updates:r.updates?{[e]:r.updates}:{},deletes:r.delete?[e]:[]}}function Na(r,e){if(e.insert&&(r=e.insert),r&&e.updates&&F8(r,e.updates),!e.delete)return r}function Ap(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 zt(r,e){return e??r}var U8=jr("TL","TreeLeaf"),K8=jr("TB","TreeBranch"),H8=zt("entries"),z8=zt("partitions"),q8=zt("nodes");var V8=zt("entries"),W8=zt("priorId"),j8=zt("nextId"),Y8=jr("CHD","ChainDataBlock"),X8=zt("headId"),Z8=zt("tailId"),Q8=jr("CHH","ChainHeaderBlock");var Dp={};ve(Dp,{base58btc:()=>Yr,base58flickr:()=>iI});var FN=new Uint8Array(0);function $y(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 Gy(r){return new TextEncoder().encode(r)}function Vy(r){return new TextDecoder().decode(r)}function eI(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var n=0;n<r.length;n++){var o=r.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,w=p.length;y!==w&&p[y]===0;)y++,m++;for(var b=(w-y)*u+1>>>0,x=new Uint8Array(b);y!==w;){for(var E=p[y],P=0,T=b-1;(E!==0||P<g)&&T!==-1;T--,P++)E+=256*x[T]>>>0,x[T]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");g=P,y++}for(var D=b-g;D!==b&&x[D]===0;)D++;for(var v=c.repeat(m);D<b;++D)v+=r.charAt(x[D]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var w=(p.length-m)*l+1>>>0,b=new Uint8Array(w);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var E=0,P=w-1;(x!==0||E<y)&&P!==-1;P--,E++)x+=a*b[P]>>>0,b[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=E,m++}if(p[m]!==" "){for(var T=w-y;T!==w&&b[T]===0;)T++;for(var D=new Uint8Array(g+(w-T)),v=g;T!==w;)D[v++]=b[T++];return D}}}function f(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var tI=eI,rI=tI,jy=rI;var Cp=class{name;prefix;baseEncode;constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Tp=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,s){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=s}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 Yy(this,e)}},Pp=class{decoders;constructor(e){this.decoders=e}or(e){return Yy(this,e)}decode(e){let t=e[0],s=this.decoders[t];if(s!=null)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Yy(r,e){return new Pp({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var kp=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new Cp(e,t,s),this.decoder=new Tp(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Jo({name:r,prefix:e,encode:t,decode:s}){return new kp(r,e,t,s)}function Ys({name:r,prefix:e,alphabet:t}){let{encode:s,decode:n}=jy(t,r);return Jo({prefix:e,name:r,encode:s,decode:o=>ar(n(o))})}function sI(r,e,t,s){let n=r.length;for(;r[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,c=0;for(let l=0;l<n;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${s} 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 nI(r,e,t){let s=e[e.length-1]==="=",n=(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[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),s)for(;(o.length*t&7)!==0;)o+="=";return o}function oI(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ne({name:r,prefix:e,bitsPerChar:t,alphabet:s}){let n=oI(s);return Jo({prefix:e,name:r,encode(o){return nI(o,s,t)},decode(o){return sI(o,n,t,r)}})}var Yr=Ys({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),iI=Ys({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Mp={};ve(Mp,{base32:()=>ei,base32hex:()=>uI,base32hexpad:()=>dI,base32hexpadupper:()=>fI,base32hexupper:()=>hI,base32pad:()=>cI,base32padupper:()=>lI,base32upper:()=>aI,base32z:()=>pI});var ei=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),aI=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cI=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lI=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),uI=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),hI=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dI=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fI=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pI=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Op={};ve(Op,{base36:()=>Ba,base36upper:()=>mI});var Ba=Ys({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),mI=Ys({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gI=Qy,Xy=128,yI=127,bI=~yI,wI=Math.pow(2,31);function Qy(r,e,t){e=e||[],t=t||0;for(var s=t;r>=wI;)e[t++]=r&255|Xy,r/=128;for(;r&bI;)e[t++]=r&255|Xy,r>>>=7;return e[t]=r|0,Qy.bytes=t-s+1,e}var xI=Lp,vI=128,Zy=127;function Lp(r,s){var t=0,s=s||0,n=0,o=s,i,a=r.length;do{if(o>=a)throw Lp.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=n<28?(i&Zy)<<n:(i&Zy)*Math.pow(2,n),n+=7}while(i>=vI);return Lp.bytes=o-s,t}var EI=Math.pow(2,7),SI=Math.pow(2,14),II=Math.pow(2,21),_I=Math.pow(2,28),AI=Math.pow(2,35),CI=Math.pow(2,42),TI=Math.pow(2,49),PI=Math.pow(2,56),kI=Math.pow(2,63),DI=function(r){return r<EI?1:r<SI?2:r<II?3:r<_I?4:r<AI?5:r<CI?6:r<TI?7:r<PI?8:r<kI?9:10},MI={encode:gI,decode:xI,encodingLength:DI},OI=MI,Fa=OI;function Ua(r,e=0){return[Fa.decode(r,e),Fa.decode.bytes]}function ti(r,e,t=0){return Fa.encode(r,e,t),e}function ri(r){return Fa.encodingLength(r)}function ni(r,e){let t=e.byteLength,s=ri(r),n=s+ri(t),o=new Uint8Array(n+t);return ti(r,o,0),ti(t,o,s),o.set(e,n),new si(r,t,e,o)}function Jy(r){let e=ar(r),[t,s]=Ua(e),[n,o]=Ua(e.subarray(s)),i=e.subarray(s+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new si(t,n,i,e)}function e5(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&$y(r.bytes,t.bytes)}}var si=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}};function t5(r,e){let{bytes:t,version:s}=r;switch(s){case 0:return RI(t,Rp(r),e??Yr.encoder);default:return NI(t,Rp(r),e??ei.encoder)}}var r5=new WeakMap;function Rp(r){let e=r5.get(r);if(e==null){let t=new Map;return r5.set(r,t),t}return e}var Yl=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=n,this["/"]=n}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!==Ha)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==BI)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,s=ni(e,t);return r.createV1(this.code,s)}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 s=t;return s!=null&&e.code===s.code&&e.version===s.version&&e5(e.multihash,s.multihash)}toString(e){return t5(this,e)}toJSON(){return{"/":t5(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:s,code:n,multihash:o,bytes:i}=t;return new r(s,n,o,i??s5(s,n,o.bytes))}else if(t[FI]===!0){let{version:s,multihash:n,code:o}=t,i=Jy(n);return r.create(s,o,i)}else return null}static create(e,t,s){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(s.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ha)throw new Error(`Version 0 CID must use dag-pb (code: ${Ha}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=s5(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ha,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,s]=r.decodeFirst(e);if(s.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),s=t.size-t.multihashSize,n=ar(e.subarray(s,s+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new si(t.multihashCode,t.digestSize,o,n);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,s=()=>{let[h,d]=Ua(e.subarray(t));return t+=d,h},n=s(),o=Ha;if(n===18?(n=0,t=0):o=s(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=s(),c=s(),l=t+c,u=l-i;return{version:n,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[s,n]=LI(e,t),o=r.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Rp(o).set(s,e),o}};function LI(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 ei.prefix:{let t=e??ei;return[ei.prefix,t.decode(r)]}case Ba.prefix:{let t=e??Ba;return[Ba.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 RI(r,e,t){let{prefix:s}=t;if(s!==Yr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(s);if(n==null){let o=t.encode(r).slice(1);return e.set(s,o),o}else return n}function NI(r,e,t){let{prefix:s}=t,n=e.get(s);if(n==null){let o=t.encode(r);return e.set(s,o),o}else return n}var Ha=112,BI=18;function s5(r,e,t){let s=ri(r),n=s+ri(e),o=new Uint8Array(n+t.byteLength);return ti(r,o,0),ti(e,o,s),o.set(t,n),o}var FI=Symbol.for("@ipld/js-cid/CID");var Np={};ve(Np,{identity:()=>HI});var n5=0,UI="identity",o5=ar;function KI(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(n5,o5(r))}var HI={code:n5,name:UI,encode:o5,digest:KI};var a5=re("node:buffer");function i5(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function c5(r=0){return i5(a5.Buffer.allocUnsafe(r))}var Bp={};ve(Bp,{base10:()=>zI});var zI=Ys({prefix:"9",name:"base10",alphabet:"0123456789"});var Fp={};ve(Fp,{base16:()=>qI,base16upper:()=>$I});var qI=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$I=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Up={};ve(Up,{base2:()=>GI});var GI=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Kp={};ve(Kp,{base256emoji:()=>XI});var l5=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}"),VI=l5.reduce((r,e,t)=>(r[t]=e,r),[]),WI=l5.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);function jI(r){return r.reduce((e,t)=>(e+=VI[t],e),"")}function YI(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=WI[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var XI=Jo({prefix:"\u{1F680}",name:"base256emoji",encode:jI,decode:YI});var Hp={};ve(Hp,{base64:()=>ZI,base64pad:()=>QI,base64url:()=>JI,base64urlpad:()=>e_});var ZI=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),QI=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),JI=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),e_=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var zp={};ve(zp,{base8:()=>t_});var t_=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var qp={};ve(qp,{identity:()=>r_});var r_=Jo({prefix:"\0",name:"identity",encode:r=>Vy(r),decode:r=>Gy(r)});var fB=new TextEncoder,pB=new TextDecoder;var jp={};ve(jp,{sha256:()=>Wp,sha512:()=>i_});var Vp=we(re("crypto"),1);var o_=20;function Gp({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new $p(r,e,t,s,n)}var $p=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,o){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??o_,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 s=this.encode(e);return s instanceof Uint8Array?u5(s,this.code,t?.truncate):s.then(n=>u5(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function u5(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 Wp=Gp({name:"sha2-256",code:18,encode:r=>ar(Vp.default.createHash("sha256").update(r).digest())}),i_=Gp({name:"sha2-512",code:19,encode:r=>ar(Vp.default.createHash("sha512").update(r).digest())});var Yp={...qp,...Up,...zp,...Bp,...Fp,...Mp,...Op,...Dp,...Hp,...Kp},CB={...jp,...Np};function f5(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var d5=f5("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Xp=f5("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=c5(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),DB={utf8:d5,"utf-8":d5,hex:Yp.base16,latin1:Xp,ascii:Xp,binary:Xp,...Yp};var kn=class{static lockQueues=new Map;static async acquire(e){let t=this.lockQueues.get(e)??Promise.resolve(),s,n=new Promise(i=>{s=i});return this.lockQueues.set(e,n),await t,()=>{s(),this.lockQueues.get(e)===n&&this.lockQueues.delete(e)}}};var u_=jr("DIH","DiaryHeaderBlock");var h_=jr("TRE","TreeHeaderBlock"),d_=zt("rootId");var TF=zt("priorHash");Zp();Zp();var Dn=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 Qp(r,e){return r.reduce((t,s)=>{let n=e(s);return(t[n]??=[]).push(s),t},{})}ce();us();Se();var T5=we(s0(),1),N_="optimystic:db-p2p";function lr(r){return(0,T5.default)(`${N_}:${r}`)}var _e=lr("cluster-member"),vt;(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"})(vt||(vt={}));function n0(r){return new eu(r.storageRepo,r.peerNetwork,r.peerId,r.protocolPrefix,r.partitionDetector,r.fretService,r.validator)}var eu=class{storageRepo;peerNetwork;peerId;protocolPrefix;partitionDetector;fretService;validator;activeTransactions=new Map;cleanupQueue=[];pendingUpdates=new Map;constructor(e,t,s,n,o,i,a){this.storageRepo=e,this.peerNetwork=t,this.peerId=s,this.protocolPrefix=n,this.partitionDetector=o,this.fretService=i,this.validator=a,setInterval(()=>this.queueExpiredTransactions(),6e4),setInterval(()=>this.processCleanupQueue(),1e3)}async update(e){let t=this.pendingUpdates.get(e.messageHash);t&&(_e("cluster-member:concurrent-update-wait",{messageHash:e.messageHash}),await t);let s=this.processUpdate(e);this.pendingUpdates.set(e.messageHash,s);try{return await s}finally{setTimeout(()=>{this.pendingUpdates.delete(e.messageHash)},100)}}async processUpdate(e){let t=this.peerId.toString(),s=e.commits[t]?"commit":e.promises[t]?"promise":"initial";if(_e("cluster-member:incoming",{messageHash:e.messageHash,phase:s,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 n=this.activeTransactions.get(e.messageHash),o=n?.record||e;n&&_e("cluster-member:merge-start",{messageHash:e.messageHash,existingPromises:Object.keys(n.record.promises??{}),existingCommits:Object.keys(n.record.commits??{}),incomingPromises:Object.keys(e.promises??{}),incomingCommits:Object.keys(e.commits??{})}),n&&(o=await this.mergeRecords(n.record,e),_e("cluster-member:merge-complete",{messageHash:e.messageHash,mergedPromises:Object.keys(o.promises??{}),mergedCommits:Object.keys(o.commits??{})}));let i=await this.getTransactionPhase(o);_e("cluster-member:phase",{messageHash:e.messageHash,phase:i,promises:Object.keys(o.promises??{}),commits:Object.keys(o.commits??{})});let a=!0;switch(i){case vt.OurPromiseNeeded:_e("cluster-member:action-promise",{messageHash:e.messageHash}),o=await this.handlePromiseNeeded(o),_e("cluster-member:action-promise-complete",{messageHash:e.messageHash,promises:Object.keys(o.promises??{})});break;case vt.OurCommitNeeded:_e("cluster-member:action-commit",{messageHash:e.messageHash}),o=await this.handleCommitNeeded(o),_e("cluster-member:action-commit-complete",{messageHash:e.messageHash,commits:Object.keys(o.commits??{})}),a=!1;break;case vt.Consensus:_e("cluster-member:action-consensus",{messageHash:e.messageHash}),await this.handleConsensus(o),a=!1;break;case vt.Rejected:_e("cluster-member:action-rejected",{messageHash:e.messageHash}),await this.handleRejection(o),a=!1;break;case vt.Propagating:_e("cluster-member:phase-propagating",{messageHash:e.messageHash}),a=!1;break;case vt.Promising:_e("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}),_e("cluster-member:state-persist",{messageHash:e.messageHash,storedPromises:Object.keys(o.promises??{}),storedCommits:Object.keys(o.commits??{})})}else _e("cluster-member:state-clear",{messageHash:e.messageHash}),this.clearTransaction(e.messageHash);return _e("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(_e("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){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(e.messageHash+JSON.stringify(e.message)),s=await Qe.digest(t);return K(s.digest,"base64url")}async validateSignatures(e){let t=await this.computePromiseHash(e);for(let[n,o]of Object.entries(e.promises))if(!await this.verifySignature(n,t,o))throw new Error(`Invalid promise signature from ${n}`);let s=await this.computeCommitHash(e);for(let[n,o]of Object.entries(e.commits))if(!await this.verifySignature(n,s,o))throw new Error(`Invalid commit signature from ${n}`)}async computePromiseHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)),s=await Qe.digest(t);return K(s.digest,"base64url")}async computeCommitHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)+JSON.stringify(e.promises)),s=await Qe.digest(t);return K(s.digest,"base64url")}async verifySignature(e,t,s){return!0}async getTransactionPhase(e){let t=Object.keys(e.peers).length,s=Object.keys(e.promises).length,n=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 vt.Rejected;if(!e.promises[o]&&!this.hasConflict(e))return vt.OurPromiseNeeded;if(s<t)return vt.Promising;if(s===t&&!e.commits[o])return vt.OurCommitNeeded;let c=Object.values(e.commits).filter(l=>l.type==="approve");return this.hasMajority(c.length,t)?vt.Consensus:vt.Propagating}hasMajority(e,t){return e>t/2}async handlePromiseNeeded(e){let t=await this.validatePendOperations(e),s=t.valid?{type:"approve",signature:"approved"}:{type:"reject",signature:"rejected",rejectReason:t.reason};return t.valid||_e("cluster-member:validation-rejected",{messageHash:e.messageHash,reason:t.reason}),{...e,promises:{...e.promises,[this.peerId.toString()]:s}}}async validatePendOperations(e){if(!this.validator)return{valid:!0};for(let t of e.message.operations)if("pend"in t){let s=t.pend;if(s.transaction&&s.operationsHash){let n=await this.validator.validate(s.transaction,s.operationsHash);if(!n.valid)return{valid:!1,reason:n.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){let t=this.activeTransactions.get(e.messageHash);if(!this.hasLocalCommit(t?.record??e))for(let s of e.message.operations)"get"in s?await this.storageRepo.get(s.get):"pend"in s?await this.storageRepo.pend(s.pend):"commit"in s?await this.storageRepo.commit(s.commit):"cancel"in s&&await this.storageRepo.cancel(s.cancel.actionRef)}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(),s=2e3;for(let[n,o]of Array.from(this.activeTransactions.entries()))if(n!==e.messageHash){if(t-o.lastUpdate>s){_e("cluster-member:stale-cleanup",{messageHash:n,age:t-o.lastUpdate}),this.clearTransaction(n);continue}if(this.operationsConflict(o.record.message.operations,e.message.operations)){if(this.resolveRace(o.record,e)==="keep-existing")return _e("cluster-member:race-keep-existing",{existing:n,incoming:e.messageHash}),!0;_e("cluster-member:race-accept-incoming",{existing:n,incoming:e.messageHash}),this.clearTransaction(n);continue}}return!1}resolveRace(e,t){let s=Object.keys(e.promises).length,n=Object.keys(t.promises).length;return s>n?"keep-existing":n>s?"accept-incoming":e.messageHash>t.messageHash?"keep-existing":"accept-incoming"}operationsConflict(e,t){let s=this.getActionId(e),n=this.getActionId(t);if(s&&n&&s===n)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 _e("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 s of e)"get"in s?s.get.blockIds.forEach(n=>t.add(n)):"pend"in s?Pn(s.pend.transforms).forEach(n=>t.add(n)):"commit"in s?s.commit.blockIds.forEach(n=>t.add(n)):"cancel"in s&&s.cancel.actionRef.blockIds.forEach(n=>t.add(n));return Array.from(t)}async propagateIfNeeded(e){let t=[];for(let[s,n]of Object.entries(e.peers))if(s!==this.peerId.toString())try{let o=Tn.create($(s),this.peerNetwork,this.protocolPrefix);t.push(o.update(e))}catch(o){console.error(`Failed to propagate to peer ${s}:`,o)}await Promise.allSettled(t)}async handleExpiration(e){let t=this.activeTransactions.get(e);if(t&&!t.record.promises[this.peerId.toString()]){let s={type:"reject",signature:"rejected",rejectReason:"Transaction expired"},n={...t.record,promises:{...t.record.promises,[this.peerId.toString()]:s}};this.activeTransactions.set(e,{...t,record:n}),await this.propagateIfNeeded(n)}}async resolveWithPeers(e){_e("cluster-member:resolve-skipped",{messageHash:e,reason:"coordinator-handles-retry"})}queueExpiredTransactions(){let e=Date.now();for(let[t,s]of Array.from(this.activeTransactions.entries()))s.record.message.expiration&&s.record.message.expiration<e&&this.cleanupQueue.push(t)}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 s=await this.getTransactionPhase(t.record);s!==vt.Consensus&&s!==vt.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){_e("cluster-member:clear-miss",{messageHash:e});return}t.promiseTimeout&&clearTimeout(t.promiseTimeout),t.resolutionTimeout&&clearTimeout(t.resolutionTimeout),this.activeTransactions.delete(e),_e("cluster-member:clear-done",{messageHash:e,remaining:Array.from(this.activeTransactions.keys())})}};function o0(r={}){return e=>new tu(e,r)}var tu=class{protocol;maxInboundStreams;maxOutboundStreams;log;cluster;components;running;k;configuredClusterSize;allowDownsize;sizeTolerance;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}[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){let{stream:t,connection:s}=e,n=s.remotePeer,o=async function*(i){for await(let a of i){let c=new TextDecoder().decode(a.subarray()),l=JSON.parse(c),u;if(l.operation==="update"){let d=l.record?.message?.commit?.tailId??l.record?.message?.pend?Object.keys(l.record.message.pend.transforms)[0]:void 0;u=await this.cluster.update(l.record)}else throw new Error(`Unknown operation: ${l.operation}`);if(l.operation==="update"){let d=u;this.log("cluster-service:pre-serialize",{messageHash:d?.messageHash,responseType:typeof u,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 h=JSON.stringify(u);if(l.operation==="update"){let d=JSON.parse(h);this.log("cluster-service:post-serialize",{messageHash:d?.messageHash,promiseKeys:Object.keys(d?.promises??{}),commitKeys:Object.keys(d?.commits??{})})}yield new TextEncoder().encode(h)}};Promise.resolve().then(async()=>{await st(t,i=>Gt(i),o.bind(this),i=>sr(i),t)}).catch(i=>{this.log.error("error handling cluster protocol message from %p - %e",n,i)})}};ce();var i0=class r extends cs{protocolPrefix;constructor(e,t,s){super(e,t),this.protocolPrefix=s}static create(e,t,s){return new r(e,t,s)}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,s=0){let n={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((h,d)=>setTimeout(()=>d(new Error("RepoClient timeout")),i))]),c,l=(this.protocolPrefix??"/db-p2p")+"/repo/1.0.0";if(c=await a(()=>super.processMessage(n,l,{signal:t?.signal})),c?.redirect?.peers?.length){if(s>=2)throw new Error("Redirect loop detected in RepoClient (max hops reached)");let u=this.peerId.toString(),h=c.redirect.peers.find(p=>p.id!==u)??c.redirect.peers[0],d=$(h.id);if(h.id===u)throw new Error("Redirect loop detected in RepoClient (same peer)");return this.recordCoordinatorForOpsIfSupported(e,d),await r.create(d,this.peerNetwork,this.protocolPrefix).processRepoMessage(e,t,s+1)}return c}extractKeyFromOperations(e){let t=e[0];if("get"in t){let s=t.get.blockIds[0];return s?new TextEncoder().encode(s):void 0}if("pend"in t){let s=Object.keys(t.pend.transforms)[0];return s?new TextEncoder().encode(s):void 0}if("commit"in t)return new TextEncoder().encode(t.commit.tailId)}recordCoordinatorForOpsIfSupported(e,t){let s=this.extractKeyFromOperations(e),n=this.peerNetwork;s!=null&&typeof n?.recordCoordinator=="function"&&n.recordCoordinator(s,t)}};ce();Vt();us();var Q=lr("cluster"),za=class{keyNetwork;createClusterClient;cfg;localCluster;fretService;transactions=new Map;retryInitialIntervalMs=2e3;retryBackoffFactor=2;retryMaxIntervalMs=3e4;retryMaxAttempts=5;constructor(e,t,s,n,o){this.keyNetwork=e,this.createClusterClient=t,this.cfg=s,this.localCluster=n,this.fretService=o}async createMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),s=await Qe.digest(t);return me.encode(s.digest)}async getClusterForBlock(e){let t=new TextEncoder().encode(e);try{let s=await this.keyNetwork.findCluster(t),n=Object.keys(s??{});return Q("cluster-tx:cluster-members",{blockId:e,peerIds:n}),s}catch(s){return Q("WARN findCluster failed for %s: %o",e,s),{}}}makeRecord(e,t,s){let n=Object.keys(e??{}).length,o={messageHash:t,peers:e,message:s,coordinatingBlockIds:s.coordinatingBlockIds,promises:{},commits:{},suggestedClusterSize:n||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,s){let n=await this.getClusterForBlock(e),o=await this.createMessageHash(t),i=this.makeRecord(n,o,t);Q("cluster-tx:start",{messageHash:o,blockId:e,peerCount:Object.keys(n??{}).length,allowDownsize:this.cfg.allowClusterDownsize,configuredSize:this.cfg.clusterSize,suggestedSize:i.suggestedClusterSize,minRequiredSize:i.minRequiredSize});let a=this.executeTransaction(n,i),c=new Dn(a),l={messageHash:o,record:i,pending:c,lastUpdate:Date.now()};this.transactions.set(o,l),Q("cluster-tx:transaction-store",{messageHash:o,transactionKeys:Array.from(this.transactions.keys())});try{return await c.result()}finally{let u=this.transactions.get(o),h=u?.retry?{attempt:u.retry.attempt,pending:Array.from(u.retry.pendingPeers??[])}:void 0;Q("cluster-tx:complete",{messageHash:o,finalPromises:u?Object.keys(u.record.promises??{}):void 0,finalCommits:u?Object.keys(u.record.commits??{}):void 0,retry:h}),u?.retry||setTimeout(()=>{this.transactions.delete(o),Q("cluster-tx:transaction-remove",{messageHash:o,remaining:Array.from(this.transactions.keys())})},100)}}async executeTransaction(e,t){let s=Object.keys(e).length;if(s<this.cfg.minAbsoluteClusterSize){if(!await this.validateSmallCluster(s,e))throw Q("cluster-tx:reject-too-small",{peerCount:s,minRequired:this.cfg.minAbsoluteClusterSize}),new Error(`Cluster size ${s} below minimum ${this.cfg.minAbsoluteClusterSize} and not validated`);Q("cluster-tx:small-cluster-validated",{peerCount:s})}if(!this.cfg.allowClusterDownsize&&s<this.cfg.clusterSize)throw Q("cluster-tx:reject-downsize",{peerCount:s,required:this.cfg.clusterSize}),new Error(`Cluster size ${s} below configured minimum ${this.cfg.clusterSize}`);let n=await this.collectPromises(e,t),o=Math.ceil(s*this.cfg.superMajorityThreshold),i=n.record.promises,a=Object.values(i).filter(u=>u.type==="approve").length,c=Object.values(i).filter(u=>u.type==="reject").length,l=s-o;if(c>l){let u=Object.entries(i).filter(([h,d])=>d.type==="reject").map(([h,d])=>`${h}: ${d.rejectReason??"unknown"}`).join("; ");throw Q("cluster-tx:rejected-by-validators",{messageHash:t.messageHash,peerCount:s,rejections:c,maxAllowed:l,reasons:u}),this.updateTransactionRecord(n.record,"rejected-by-validators"),new Error(`Transaction rejected by validators (${c}/${s} rejected): ${u}`)}if(s>1&&a<o)throw Q("cluster-tx:supermajority-failed",{messageHash:t.messageHash,peerCount:s,approvals:a,rejections:c,superMajority:o,threshold:this.cfg.superMajorityThreshold}),this.updateTransactionRecord(n.record,"supermajority-failed"),new Error(`Failed to get super-majority: ${a}/${s} approvals (needed ${o}, ${c} rejections)`);return await this.commitTransaction(n.record)}async getClusterSize(e){let t=await this.getClusterForBlock(e);return Object.keys(t??{}).length}async validateSmallCluster(e,t){if(this.fretService)try{let s=this.fretService.getNetworkSizeEstimate();if(s.confidence>.5){let n=Math.floor(Math.log10(s.size_estimate+1)),o=Math.floor(Math.log10(e+1));if(Math.abs(n-o)<=1)return Q("cluster-tx:small-cluster-validated-by-fret",{localSize:e,fretEstimate:s.size_estimate,confidence:s.confidence,sources:s.sources}),!0}}catch{}return Q("cluster-tx:small-cluster-accepted-without-validation",{localSize:e,reason:"no-confident-network-size-estimate"}),!0}async collectPromises(e,t){let s=Object.keys(e),n=[],o=s.map(l=>{let u=this.localCluster&&l===this.localCluster.peerId.toString();Q("cluster-tx:promise-request",{messageHash:t.messageHash,peerId:l,isLocal:u});let h=u?this.localCluster.update(t):this.createClusterClient($(l)).update(t);return new Dn(h)}),i=await Promise.all(o.map((l,u)=>l.result().then(h=>{let d=s[u];return Q("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:d,success:!0,returnedPromises:Object.keys(h.promises??{}),returnedCommits:Object.keys(h.commits??{})}),n.push({peerId:d,success:!0}),h}).catch(h=>{let d=s[u];return Q("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:d,success:!1,error:h}),n.push({peerId:d,success:!1,error:h instanceof Error?h.message:String(h)}),null}))),a=n.filter(l=>l.success).map(l=>l.peerId),c=n.filter(l=>!l.success);Q("cluster-tx:promise-summary",{messageHash:t.messageHash,successes:a,failures:c}),Q("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)){Q("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(Q("cluster-tx:promise-merge-result",{messageHash:t.messageHash,peerPromises:u}),typeof t.suggestedClusterSize=="number"&&typeof l.suggestedClusterSize=="number"){let h=l.suggestedClusterSize,d=Object.keys(e).length,f=Math.ceil(Math.max(1,h*this.cfg.clusterSizeTolerance));Math.abs(d-h)>f&&Q("cluster-tx:size-variance",{expected:h,actual:d,tolerance:this.cfg.clusterSizeTolerance})}t.promises={...t.promises,...l.promises},Q("cluster-tx:promise-merge-after",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})})}return Q("cluster-tx:promise-merge",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})}),Q("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),s=[],n={...e},o=t.map(f=>{let p=this.localCluster&&f===this.localCluster.peerId.toString();Q("cluster-tx:commit-request",{messageHash:e.messageHash,peerId:f,isLocal:p});let m=p?this.localCluster.update(n):this.createClusterClient($(f)).update(n);return new Dn(m)}),i=await Promise.all(o.map((f,p)=>f.result().then(m=>{let g=t[p];return Q("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!0}),s.push({peerId:g,success:!0}),m}).catch(m=>{let g=t[p];return Q("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!1,error:m}),s.push({peerId:g,success:!1,error:m instanceof Error?m.message:String(m)}),null}))),a=s.filter(f=>f.success).map(f=>f.peerId),c=s.filter(f=>!f.success);Q("cluster-tx:commit-summary",{messageHash:e.messageHash,successes:a,failures:c}),Q("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))Q("cluster-tx:commit-merge-input",{messageHash:e.messageHash,resultFrom:Object.keys(f.commits??{}),recordBefore:Object.keys(e.commits??{})}),Q("cluster-tx:commit-merge-result",{messageHash:e.messageHash,peerCommits:Object.keys(f.commits??{})}),e.commits={...e.commits,...f.commits},Q("cluster-tx:commit-merge-after",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})});Q("cluster-tx:commit-merge",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})}),Q("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,h=Object.keys(e.commits).length;h>=u&&Q("cluster-tx:commit-majority-reached",{messageHash:e.messageHash,commitCount:h,simpleMajority:u,peerCount:l,threshold:this.cfg.simpleMajorityThreshold});let d=c.map(f=>f.peerId);return d.length>0?this.scheduleCommitRetry(e.messageHash,e,d):this.clearRetry(e.messageHash),e}updateTransactionRecord(e,t){let s=this.transactions.get(e.messageHash);if(!s){Q("cluster-tx:transaction-update-miss",{messageHash:e.messageHash,stage:t});return}s.record={...e},s.lastUpdate=Date.now(),Q("cluster-tx:transaction-update",{messageHash:e.messageHash,stage:t,promises:Object.keys(e.promises??{}),commits:Object.keys(e.commits??{})})}scheduleCommitRetry(e,t,s){let n=this.transactions.get(e);if(!n)return;let o=n.retry,i=(o?.attempt??0)+1;if(i>this.retryMaxAttempts){Q("cluster-tx:retry-abort",{messageHash:e,missingPeers:s});return}if(s.length===0){this.clearRetry(e);return}let a=new Set(s),c=o?Math.min(o.intervalMs*this.retryBackoffFactor,this.retryMaxIntervalMs):this.retryInitialIntervalMs;o?.timer&&clearTimeout(o.timer);let l=setTimeout(()=>{this.retryCommits(e)},c);n.retry={pendingPeers:a,attempt:i,intervalMs:c,timer:l},Q("cluster-tx:retry-scheduled",{messageHash:e,attempt:i,missingPeers:s,delayMs:c})}async retryCommits(e){let t=this.transactions.get(e);if(!t?.retry)return;let{pendingPeers:s,attempt:n}=t.retry;if(s.size===0){this.clearRetry(e);return}let o=Array.from(s),i=t.record;Q("cluster-tx:retry-start",{messageHash:e,attempt:n,peerIds:o});let a=await Promise.all(o.map(async u=>{let h=this.localCluster&&u===this.localCluster.peerId.toString(),d={...i,commits:i.commits};try{let f=h?await this.localCluster.update(d):await this.createClusterClient($(u)).update(d);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)s.delete(u);if(Q("cluster-tx:retry-complete",{messageHash:e,attempt:n,successes:c,failures:l}),s.size===0){Q("cluster-tx:retry-finished",{messageHash:e}),this.clearRetry(e);return}this.transactions.has(e)&&this.scheduleCommitRetry(e,t.record,Array.from(s))}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),Q("cluster-tx:transaction-remove",{messageHash:e,remaining:Array.from(this.transactions.keys())})},100))}};function a0(r,e,t,s){return n=>new ru(r,e,n.storageRepo,t,n.localCluster,n.localPeerId,s)}var ru=class{keyNetwork;createClusterClient;storageRepo;coordinator;DEFAULT_TIMEOUT=3e4;constructor(e,t,s,n,o,i,a){this.keyNetwork=e,this.createClusterClient=t,this.storageRepo=s;let c={clusterSize:n?.clusterSize??10,superMajorityThreshold:n?.superMajorityThreshold??.75,simpleMajorityThreshold:n?.simpleMajorityThreshold??.51,minAbsoluteClusterSize:n?.minAbsoluteClusterSize??3,allowClusterDownsize:n?.allowClusterDownsize??!0,clusterSizeTolerance:n?.clusterSizeTolerance??.5,partitionDetectionWindow:n?.partitionDetectionWindow??6e4},l=o&&i?{update:o.update.bind(o),peerId:i}:void 0;this.coordinator=new za(e,t,c,l,a)}async get(e,t){return await this.storageRepo.get(e,t)}async pend(e,t){let s=Object.keys(e.transforms),n=t?.coordinatingBlockIds??s;if(await this.coordinator.getClusterSize(n[0])<=1)return await this.storageRepo.pend(e,t);let i={operations:[{pend:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT,coordinatingBlockIds:n};try{return await this.coordinator.executeClusterTransaction(n[0],i,t),await this.storageRepo.pend(e,t)}catch(a){throw console.error("Failed to complete pend operation:",a),a}}async cancel(e,t){let s=e.blockIds,n={operations:[{cancel:{actionRef:e}}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let o=s.map(i=>this.coordinator.executeClusterTransaction(i,n,t));await Promise.all(o),await this.storageRepo.cancel(e,t)}catch(o){throw console.error("Failed to complete cancel operation:",o),o}}async commit(e,t){let s=e.blockIds;if(await this.coordinator.getClusterSize(s[0])<=1)return await this.storageRepo.commit(e,t);let o={operations:[{commit:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{return await this.coordinator.executeClusterTransaction(s[0],o,t),await this.storageRepo.commit(e,t)}catch(i){throw console.error("Failed to complete commit operation:",i),i}}};function P5(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 On(r,e){let t=P5(r),s=P5(e);return t!=null&&s!=null&&t===s}us();function su(r){return{redirect:{peers:r,reason:"not_in_cluster"}}}function c0(r={}){return e=>new nu(e,r)}var nu=class{protocol;maxInboundStreams;maxOutboundStreams;log;repo;components;running;k;constructor(e,t={}){this.components=e;let s=t.protocol??(t.protocolPrefix??"/db-p2p")+"/repo/1.0.0";this.protocol=s,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}[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){let{stream:t,connection:s}=e,n=s.remotePeer,o=async function*(i){for await(let a of i){let c=new TextDecoder().decode(a.subarray()),l=JSON.parse(c),u=l.operations[0],h;if("get"in u){let f=(await Qe.digest(new TextEncoder().encode(u.get.blockIds[0]))).digest,p=this.components.libp2p?.services?.networkManager;if(p?.getCluster){let m=await p.getCluster(f);l.cluster=m.map(b=>b.toString?.()??String(b));let g=this.components.libp2p.peerId,y=m.some(b=>On(b,g));if(!(m.length<this.k)&&!y){let b=m.filter(x=>!On(x,g));console.debug("repo-service:redirect",{peerId:g.toString(),reason:"not-cluster-member",operation:"get",blockId:u.get.blockIds[0],cluster:m.map(x=>x.toString?.()??String(x))}),h=su(b.map(x=>({id:x.toString(),addrs:[]})))}else h=await this.repo.get(u.get,{expiration:l.expiration})}else h=await this.repo.get(u.get,{expiration:l.expiration})}else if("pend"in u){let d=Object.keys(u.pend.transforms)[0],p=(await Qe.digest(new TextEncoder().encode(d))).digest,m=this.components.libp2p?.services?.networkManager;if(m?.getCluster){let g=await m.getCluster(p);l.cluster=g.map(x=>x.toString?.()??String(x));let y=this.components.libp2p.peerId,w=g.some(x=>On(x,y));if(!(g.length<this.k)&&!w){let x=g.filter(E=>!On(E,y));console.debug("repo-service:redirect",{peerId:y.toString(),reason:"not-cluster-member",operation:"pend",blockId:d,cluster:g.map(E=>E.toString?.()??String(E))}),h=su(x.map(E=>({id:E.toString(),addrs:[]})))}else h=await this.repo.pend(u.pend,{expiration:l.expiration})}else h=await this.repo.pend(u.pend,{expiration:l.expiration})}else if("cancel"in u)h=await this.repo.cancel(u.cancel.actionRef,{expiration:l.expiration});else if("commit"in u){let f=(await Qe.digest(new TextEncoder().encode(u.commit.tailId))).digest,p=this.components.libp2p?.services?.networkManager;if(p?.getCluster){let m=await p.getCluster(f);l.cluster=m.map(b=>b.toString?.()??String(b));let g=this.components.libp2p.peerId,y=m.some(b=>On(b,g));if(!(m.length<this.k)&&!y){let b=m.filter(x=>!On(x,g));console.debug("repo-service:redirect",{peerId:g.toString(),reason:"not-cluster-member",operation:"commit",tailId:u.commit.tailId,cluster:m.map(x=>x.toString?.()??String(x))}),h=su(b.map(x=>({id:x.toString(),addrs:[]})))}else h=await this.repo.commit(u.commit,{expiration:l.expiration})}else h=await this.repo.commit(u.commit,{expiration:l.expiration})}yield new TextEncoder().encode(JSON.stringify(h))}};Promise.resolve().then(async()=>{await st(t,i=>Gt(i),o.bind(this),i=>sr(i),t)}).catch(i=>{this.log.error("error handling repo protocol message from %p - %e",n,i)})}};function k5(r){if(r.length<=1)return r;r.sort((t,s)=>t[0]-s[0]);let e=[r[0]];for(let t of r.slice(1)){let s=e[e.length-1];s[1]!==void 0&&(t[0]<=s[1]?t[1]===void 0?s[1]=void 0:s[1]=Math.max(s[1],t[1]):e.push(t))}return e}var ci=class{blockId;storage;restoreCallback;constructor(e,t,s){this.blockId=e,this.storage=t,this.restoreCallback=s}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 s=e??t.latest?.rev;if(s===void 0)throw new Error(`No revision specified and no latest revision exists for block ${this.blockId}`);return await this.ensureRevision(t,s),await this.materializeBlock(t,s)}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 s=await this.storage.getMetadata(this.blockId);s||(s={latest:void 0,ranges:[[0]]},await this.storage.saveMetadata(this.blockId,s)),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 s=`BlockStorage.ensureRevision:${this.blockId}`,n=await kn.acquire(s);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=k5(o.ranges),await this.storage.saveMetadata(this.blockId,o)}finally{n()}}async materializeBlock(e,t){let s,n,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){s=a,n=i;break}else o.push(i)}if(!s||!n)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}`);s=Na(s,c)}if(!s)throw new Error(`Block ${this.blockId} has been deleted`);return o.length?(await this.storage.saveMaterializedBlock(this.blockId,o[0].actionId,s),{block:s,actionRev:o[0]}):{block:s,actionRev:n}}async restoreBlock(e){if(this.restoreCallback)return await this.restoreCallback(this.blockId,e)}async saveRestored(e){let t=Object.entries(e.revisions).map(([s,n])=>({rev:Number(s),data:n}));for(let{rev:s,data:{action:n,block:o}}of t)await Promise.all([this.storage.saveRevision(this.blockId,s,n.actionId),this.storage.saveTransaction(this.blockId,n.actionId,n.transform),o?this.storage.saveMaterializedBlock(this.blockId,n.actionId,o):Promise.resolve()])}inRanges(e,t){return t.some(s=>e>=s[0]&&(s[1]===void 0||e<s[1]))}};var ys=re("fs"),kr=we(re("path"),1);var ou=lr("storage:file"),qa=class{basePath;constructor(e){this.basePath=e}async getMetadata(e){return this.readIfExists(this.getMetadataPath(e))}async saveMetadata(e,t){await this.ensureAndWriteFile(this.getMetadataPath(e),JSON.stringify(t))}async getRevision(e,t){return this.readIfExists(this.getRevisionPath(e,t))}async saveRevision(e,t,s){await this.ensureAndWriteFile(this.getRevisionPath(e,t),s)}async getPendingTransaction(e,t){return this.readIfExists(this.getPendingActionPath(e,t))}async savePendingTransaction(e,t,s){await this.ensureAndWriteFile(this.getPendingActionPath(e,t),JSON.stringify(s))}async deletePendingTransaction(e,t){let s=this.getPendingActionPath(e,t);await ys.promises.unlink(s).catch(n=>{n?.code!=="ENOENT"&&ou("deletePendingTransaction unlink failed for %s/%s - %o",e,t,n)})}async*listPendingTransactions(e){let t=kr.join(this.getBlockPath(e),"pend"),s=await ys.promises.readdir(t).catch(n=>(ou("listPendingTransactions readdir failed for %s - %o",e,n),[]));for(let n of s){if(!n.endsWith(".json"))continue;let o=n.slice(0,-5);/^[\w\d]+-[\w\d]+-[\w\d]+-[\w\d]+-[\w\d]+$/.test(o)&&(yield o)}}async getTransaction(e,t){return this.readIfExists(this.getActionPath(e,t))}async*listRevisions(e,t,s){for(let n=t;t<=s?n<=s:n>=s;t<=s?++n:--n){let o=await this.getRevision(e,n);o&&(yield{actionId:o,rev:n})}}async saveTransaction(e,t,s){await this.ensureAndWriteFile(this.getActionPath(e,t),JSON.stringify(s))}async getMaterializedBlock(e,t){return this.readIfExists(this.getMaterializedPath(e,t))}async saveMaterializedBlock(e,t,s){s?await this.ensureAndWriteFile(this.getMaterializedPath(e,t),JSON.stringify(s)):await ys.promises.unlink(this.getMaterializedPath(e,t)).catch(n=>{n?.code!=="ENOENT"&&ou("saveMaterializedBlock unlink failed for %s/%s - %o",e,t,n)})}async promotePendingTransaction(e,t){let s=this.getPendingActionPath(e,t),n=this.getActionPath(e,t);return await ys.promises.mkdir(kr.dirname(n),{recursive:!0}),ys.promises.rename(s,n).catch(o=>{throw o.code==="ENOENT"?new Error(`Pending action ${t} not found for block ${e}`):(ou("promotePendingTransaction rename failed for %s/%s - %o",e,t,o),o)})}getBlockPath(e){return kr.join(this.basePath,e)}getMetadataPath(e){return kr.join(this.getBlockPath(e),"meta.json")}getRevisionPath(e,t){return kr.join(this.getBlockPath(e),"revs",`${t}.json`)}getPendingActionPath(e,t){return kr.join(this.getBlockPath(e),"pend",`${t}.json`)}getActionPath(e,t){return kr.join(this.getBlockPath(e),"actions",`${t}.json`)}getMaterializedPath(e,t){return kr.join(this.getBlockPath(e),"blocks",`${t}.json`)}async readIfExists(e){return ys.promises.readFile(e,"utf-8").then(t=>JSON.parse(t)).catch(t=>{if(t.code!=="ENOENT")throw t})}async ensureAndWriteFile(e,t){await ys.promises.mkdir(kr.dirname(e),{recursive:!0}),await ys.promises.writeFile(e,t)}};var $a=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,s){this.revisions.set(this.getRevisionKey(e,t),s)}async*listRevisions(e,t,s){let n=t<=s,o=n?t:s,i=n?s: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})}n||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,s){this.pendingActions.set(this.getActionKey(e,t),s)}async deletePendingTransaction(e,t){this.pendingActions.delete(this.getActionKey(e,t))}async*listPendingTransactions(e){let t=`${e}:`;for(let[s]of Array.from(this.pendingActions.entries()))s.startsWith(t)&&(yield s.substring(t.length))}async getTransaction(e,t){return this.actions.get(this.getActionKey(e,t))}async saveTransaction(e,t,s){this.actions.set(this.getActionKey(e,t),s)}async getMaterializedBlock(e,t){return this.materializedBlocks.get(this.getActionKey(e,t))}async saveMaterializedBlock(e,t,s){let n=this.getActionKey(e,t);s?this.materializedBlocks.set(n,s):this.materializedBlocks.delete(n)}async promotePendingTransaction(e,t){let s=this.getActionKey(e,t),n=this.pendingActions.get(s);n&&(this.actions.set(s,n),this.pendingActions.delete(s))}};var Ga=class{createBlockStorage;validatePend;constructor(e,t){this.createBlockStorage=e,this.validatePend=t?.validatePend}async get({blockIds:e,context:t},s){let n=Array.from(new Set(e)),o=await Promise.all(n.map(async i=>{let a=this.createBlockStorage(i);if(t){let u=await a.getLatest(),h=u?t.committed.filter(d=>d.rev>u.rev):t.committed;for(let{actionId:d,rev:f}of h.sort((p,m)=>p.rev-m.rev))await a.getPendingTransaction(d)&&await this.internalCommit(i,d,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 h=Na(c.block,u);return[i,{block:h,state:{latest:await a.getLatest(),pendings:[t.actionId]}}]}let l=await na(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 s=Pn(e.transforms),n=[],o=[];for(let i of s){let a=this.createBlockStorage(i),c=Wl(e.transforms,i),l=await na(a.listPendingTransactions());if(n.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 h=await na(a.listRevisions(e.rev??0,u.rev));for(let d of h){let f=await a.getTransaction(d.actionId);if(!f)throw new Error(`Missing action ${d.actionId} for block ${i}`);o.push({actionId:d.actionId,rev:d.rev,transforms:_p(f,i)})}}}}if(o.length)return{success:!1,missing:o};if(n.length>0){if(e.policy==="f")return{success:!1,pending:n};if(e.policy==="r")return{success:!1,pending:await Promise.all(n.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(s.map(i=>{let a=this.createBlockStorage(i),c=Wl(e.transforms,i);return a.savePendingTransaction(e.actionId,c)})),{success:!0,pending:n,blockIds:s}}async cancel(e,t){await Promise.all(e.blockIds.map(s=>this.createBlockStorage(s).deletePendingTransaction(e.actionId)))}async commit(e,t){let s=Array.from(new Set(e.blockIds)).sort(),n=[];try{for(let c of s){let l=`StorageRepo.commit:${c}`,u=await kn.acquire(l);n.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 h=[];for await(let d of l.listRevisions(e.rev,u.rev)){let f=await l.getTransaction(d.actionId);if(!f)throw new Error(`Missing action ${d.actionId} for block ${c}`);h.push({actionId:d.actionId,rev:d.rev,transform:f})}i.push({blockId:c,transforms:h})}}if(i.length)return{success:!1,missing:B_(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{n.reverse().forEach(o=>o())}return{success:!0}}async internalCommit(e,t,s,n){let o=await n.getPendingTransaction(t);if(!o)throw new Error(`Consistency Error: Pending action ${t} disappeared for block ${e} within critical section.`);let i=await n.getLatest(),a=i?(await n.getBlock(i.rev))?.block:void 0,c=Na(a,o);c&&await n.saveMaterializedBlock(t,c),await n.saveRevision(s,t),await n.promotePendingTransaction(t),await n.setLatest({actionId:t,rev:s})}};function B_(r){let e=r.flatMap(({blockId:s,transforms:n})=>n.map(o=>({blockId:s,transform:o}))),t=Qp(e,({transform:s})=>s.actionId);return Object.entries(t).map(([s,n])=>n.reduce((o,{blockId:i,transform:a})=>(Ap(o.transforms,i,a.transform),o),{actionId:s,rev:n[0].transform.rev,transforms:Ip()}))}var Xr=class{entries;constructor(e){this.entries=e}},Va=class{partitions;nodes;constructor(e,t){this.partitions=e,this.nodes=t}};var bs=class r{node;index;constructor(e,t){this.node=e,this.index=t}clone(){return new r(this.node,this.index)}},li=class r{branches;leafNode;leafIndex;on;version;constructor(e,t,s,n,o){this.branches=e,this.leafNode=t,this.leafIndex=s,this.on=n,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 ur=64,iu=class{keyFromEntry;compare;_root;_version=0;constructor(e=s=>s,t=(s,n)=>s<n?-1:s>n?1:0){this.keyFromEntry=e,this.compare=t,this._root=new Xr([])}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(),s=e.last?this.findLast(e):e.isAscending?this.last():this.first(),n=this.keyFromEntry(s.leafNode.entries[s.leafIndex]),o=e.isAscending?this.internalAscending(t):this.internalDescending(t),i=e.isAscending?1:-1;for(let a of o){if(!a.on||!s.on||this.compareKeys(this.keyFromEntry(a.leafNode.entries[a.leafIndex]),n)*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 s=this.internalUpdate(e,t);return s[0].on&&(s[0].version=++this._version),s}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 s=this.keyFromEntry(e),n=this.find(s);if(n.on){let o=this.updateAt(n,t(n.leafNode.entries[n.leafIndex]));return o[0].on&&(o[0].version=++this._version),o}else return this.internalInsertAt(n,Object.freeze(e)),n.on=!0,n.version=++this._version,[n,!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,s=e?e.path.clone():this.first();if(e?.ascending??!0)for(;s.on;)t+=s.leafNode.entries.length-s.leafIndex,s.leafIndex=s.leafNode.entries.length-1,this.internalNext(s);else for(;s.on;)t+=s.leafIndex+1,s.leafIndex=0,this.internalPrior(s);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 s=this.compare(e,t);if(s!==0&&s===this.compare(t,e))throw new Error("Inconsistent comparison function for given values");return s}*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 Xr){let s=e,[n,o]=this.indexOfEntry(s.entries,t);return new li([],s,o,n,this._version)}else{let s=e,n=this.indexOfKey(s.partitions,t),o=this.getPath(s.nodes[n],t);return o.branches.unshift(new bs(s,n)),o}}indexOfEntry(e,t){let s=0,n=e.length-1,o=0,i=-1;for(;s<=n;){if(o=s+n>>>1,i=this.compareKeys(t,this.keyFromEntry(e[o])),i===0)return[!0,o];i<0?n=o-1:s=o+1}return[!1,s]}indexOfKey(e,t){let s=0,n=e.length-1,o=0,i=-1;for(;s<=n;){if(o=s+n>>>1,i=this.compareKeys(t,e[o]),i===0)return o+1;i<0?n=o-1:s=o+1}return s}internalNext(e){if(e.on)if(e.leafIndex>=e.leafNode.entries.length-1){let t=0,s=!1,n=e.branches.length-1;for(;t<=n&&!s;){let o=e.branches[n-t];o.index===o.node.partitions.length?++t:s=!0}if(!s)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,s=!1,n=e.branches.length-1;for(;t<=n&&!s;)e.branches[n-t].index===0?++t:s=!0;if(!s)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 s=this.keyFromEntry(e.leafNode.entries[e.leafIndex]),n=this.keyFromEntry(t);if(this.compareKeys(s,n)!==0){let o=this.internalInsert(t);return o.on&&(this.internalDelete(this.find(s)),o=this.find(n)),[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 s=e.branches.at(-1);this.updatePartition(s.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 s=this.leafInsert(e,t),n=e.branches.length-1;for(;s&&n>=0;)s=this.branchInsert(e,n,s),--n;if(s){let o=new Va([s.key],[this._root,s.right]);this._root=o,e.branches.unshift(new bs(o,s.indexDelta))}}moveToFirst(e,t){if(e instanceof Xr){let s=e;t.leafNode=s,t.leafIndex=0,t.on=s.entries.length>0}else t.branches.push(new bs(e,0)),this.moveToFirst(e.nodes[0],t)}moveToLast(e,t){if(e instanceof Xr){let s=e,n=s.entries.length;t.leafNode=s,t.on=n>0,t.leafIndex=n>0?n-1:0}else{let s=e,n=new bs(s,s.partitions.length);t.branches.push(n),this.moveToLast(s.nodes[n.index],t)}}getFirst(e){if(e instanceof Xr){let t=e;return new li([],t,0,t.entries.length>0,this._version)}else{let t=e,s=this.getFirst(t.nodes[0]);return s.branches.unshift(new bs(t,0)),s}}getLast(e){if(e instanceof Xr){let t=e,s=t.entries.length;return new li([],t,s>0?s-1:0,s>0,this._version)}else{let t=e,s=t.nodes.length-1,n=this.getLast(t.nodes[s]);return n.branches.unshift(new bs(t,s)),n}}leafInsert(e,t){let{leafNode:s,leafIndex:n}=e;if(s.entries.length<ur){s.entries.splice(n,0,t);return}let o=s.entries.length+1>>>1,i=s.entries.splice(o),a=new Xr(i),c=n<o?0:1;return c?(e.leafNode=a,e.leafIndex-=s.entries.length,a.entries.splice(e.leafIndex,0,t)):s.entries.splice(n,0,t),new au(this.keyFromEntry(i[0]),a,c)}branchInsert(e,t,s){let n=e.branches[t],{index:o,node:i}=n;if(n.index+=s.indexDelta,i.partitions.splice(o,0,s.key),i.nodes.splice(o+1,0,s.right),i.nodes.length<=ur)return;let a=i.nodes.length>>>1,c=i.partitions.splice(a),l=i.partitions.pop(),u=i.nodes.splice(a),h=new Va(c,u),d=n.index<a?0:1;return d&&(n.index-=a,n.node=h),new au(l,h,d)}rebalanceLeaf(e){if(e.leafNode.entries.length>=ur>>>1)return;let t=e.leafNode,s=e.branches.at(-1),n=e.branches.length-1,o=s.index,i=s.node,a=i.nodes[o+1];if(a&&a.entries.length>ur>>>1){let l=a.entries.shift();t.entries.push(l),this.updatePartition(o+1,e,n,this.keyFromEntry(a.entries[0]));return}let c=i.nodes[o-1];if(c&&c.entries.length>ur>>>1){let l=c.entries.pop();t.entries.unshift(l),this.updatePartition(o,e,n,this.keyFromEntry(l)),e.leafIndex+=1;return}if(a&&a.entries.length+t.entries.length<=ur)return t.entries.push(...a.entries),i.partitions.splice(o,1),i.nodes.splice(o+1,1),o===0&&this.updatePartition(o,e,n,this.keyFromEntry(t.entries[0])),this.rebalanceBranch(e,n);if(c&&c.entries.length+t.entries.length<=ur)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,n)}rebalanceBranch(e,t){let s=e.branches[t],n=s.node;if(t===0&&n.partitions.length===0)return e.branches[t+1]?.node??e.leafNode;if(t===0||n.nodes.length>=ur<<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>ur>>>1){n.partitions.push(a.partitions[i]);let u=c.nodes.shift();n.nodes.push(u);let h=c.partitions.shift();this.updatePartition(i+1,e,t-1,h);return}let l=a.nodes[i-1];if(l&&l.nodes.length>ur>>>1){n.partitions.unshift(a.partitions[i-1]);let u=l.nodes.pop();n.nodes.unshift(u);let h=l.partitions.pop();s.index+=1,this.updatePartition(i,e,t-1,h);return}if(c&&c.nodes.length+n.nodes.length<=ur){let u=a.partitions.splice(i,1)[0];return n.partitions.push(u),n.partitions.push(...c.partitions),n.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+n.nodes.length<=ur){s.node=l,s.index+=l.nodes.length;let u=a.partitions.splice(i-1,1)[0];return l.partitions.push(u),l.partitions.push(...n.partitions),l.nodes.push(...n.nodes),a.nodes.splice(i,1),this.rebalanceBranch(e,t-1)}}updatePartition(e,t,s,n){let o=t.branches[s];e>0?o.node.partitions[e-1]=n:s!==0&&this.updatePartition(t.branches[s-1].index,t,s-1,n)}validatePath(e){if(!this.isValid(e))throw new Error("Path is invalid due to mutation of the tree")}},au=class{key;right;indexDelta;constructor(e,t,s){this.key=e,this.right=t,this.indexDelta=s}};function Wa(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function cu(r){return`${Wa(r.coord)}|${r.id}`}var lu=class{byKey;byId;constructor(){this.byKey=new iu(e=>cu(e)),this.byId=new Map}insert(e){let t=cu(e);this.byKey.insert(e),this.byId.set(e.id,t)}upsert(e,t){let s=Date.now(),n=this.byId.get(e);if(n){let i=this.byKey.find(n);i.on&&this.byKey.deleteAt(i),this.byId.delete(e)}let o={id:e,coord:t,relevance:0,lastAccess:s,state:"disconnected",accessCount:0,successCount:0,failureCount:0,avgLatencyMs:0};return this.insert(o),o}update(e,t){let s=this.byId.get(e);if(!s)return;let n=this.byKey.find(s),o=this.byKey.at(n);if(!o)return;let i={...o,...t};this.byKey.updateAt(n,i),cu(o)!==cu(i)&&(this.byKey.deleteAt(n),this.insert(i))}getById(e){let t=this.byId.get(e);if(!t)return;let s=this.byKey.find(t);return s.on?this.byKey.at(s):void 0}remove(e){let t=this.byId.get(e);if(!t)return;let s=this.byKey.find(t);s.on&&this.byKey.deleteAt(s),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 s=new Set;for(let n of this.neighborsRight(e,t))s.add(n);for(let n of this.neighborsLeft(e,t))s.add(n);return s}ceilPath(e){let t=`${e}|\0`,s=this.byKey.find(t);return s.on||(s=this.byKey.next(s)),s}floorPath(e){let t=`${e}|\uFFFF`,s=this.byKey.find(t);return s.on||(s=this.byKey.prior(s)),s}successorOfCoord(e){let t=Wa(e),s=this.ceilPath(t);if(s.on)return this.byKey.at(s);let n=this.byKey.first();return n.on?this.byKey.at(n):void 0}predecessorOfCoord(e){let t=Wa(e),s=this.floorPath(t);if(s.on)return this.byKey.at(s);let n=this.byKey.last();return n.on?this.byKey.at(n):void 0}neighborsRight(e,t){let s=[],n=Wa(e),o=this.ceilPath(n);o=o.on?o:this.byKey.first();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.first(),!o.on));)s.push(this.byKey.at(o).id),o=this.byKey.next(o),i++;return Array.from(new Set(s))}neighborsLeft(e,t){let s=[],n=Wa(e),o=this.floorPath(n);o=o.on?o:this.byKey.last();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.last(),!o.on));)s.push(this.byKey.at(o).id),o=this.byKey.prior(o),i++;return Array.from(new Set(s))}};us();Se();ge();async function Be(r){let e=r.toMultihash().bytes;return await Qe.encode(e)}async function Xt(r){return await Qe.encode(r)}function D5(r){return K(r,"base64url")}function M5(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 l0="/optimystic/default/fret/1.0.0/neighbors",u0="/optimystic/default/fret/1.0.0/neighbors/announce",h0="/optimystic/default/fret/1.0.0/maybeAct",d0="/optimystic/default/fret/1.0.0/leave",f0="/optimystic/default/fret/1.0.0/ping";async function hr(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)}async function Zr(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 s=new TextDecoder().decode(r.subarray(e,t));return JSON.parse(s)}ce();var O5=we(s0(),1),F_="optimystic:fret";function Zs(r){return(0,O5.default)(`${F_}:${r}`)}var p0=Zs("rpc:neighbors");function L5(r,e,t,s={PROTOCOL_NEIGHBORS:l0,PROTOCOL_NEIGHBORS_ANNOUNCE:u0}){r.handle(s.PROTOCOL_NEIGHBORS,async({stream:n})=>{try{let o=await e();await n.sink((async function*(){yield await hr(o)})());try{n.close?.()}catch{}}catch(o){console.error("neighbors handler error:",o)}}),t&&r.handle(s.PROTOCOL_NEIGHBORS_ANNOUNCE,async({stream:n})=>{try{let o=await N5(n),i=await Zr(o);t(i.from,i),await n.sink((async function*(){yield await hr({ok:!0})})());try{n.close?.()}catch{}}catch(o){console.error("neighbors announce handler error:",o)}})}async function R5(r,e,t=l0){let s=$(e),n=r.getConnections?.(s)??[];if(!Array.isArray(n)||n.length===0||typeof n[0]?.newStream!="function")return{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""};let o;try{o=await n[0].newStream([t]);let i=await N5(o);return await Zr(i)}catch(i){return p0("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 m0(r,e,t,s=u0){let n=$(e),o=r.getConnections?.(n)??[];if(!Array.isArray(o)||o.length===0||typeof o[0]?.newStream!="function")return;let i;try{i=await o[0].newStream([s]),await i.sink((async function*(){yield await hr(t)})())}catch(a){p0("announceNeighbors failed to %s - %o",e,a)}finally{if(i)try{await i.close()}catch{}}}function U_(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")try{return e.subarray(0)}catch(t){p0("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 N5(r){let e=[];for await(let o of r.source)e.push(U_(o));let t=0;for(let o of e)t+=o.length;let s=new Uint8Array(t),n=0;for(let o of e)s.set(o,n),n+=o.length;return s}ce();function B5(r,e,t=h0){r.handle(t,async({stream:s})=>{try{let n=await U5(s),o=await Zr(n),i=await e(o);await s.sink((async function*(){yield await hr(i)})())}catch(n){console.error("maybeAct handler error:",n)}})}async function F5(r,e,t,s=h0){let n=$(e),o=r.getConnections?.(n)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([s]):i=await r.dialProtocol(n,[s]),await i.sink((async function*(){yield await hr(t)})());let a=await U5(i);return await Zr(a)}finally{if(i)try{await i.close()}catch{}}}function K_(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 U5(r){let e=[];for await(let o of r.source)e.push(K_(o));let t=0;for(let o of e)t+=o.length;let s=new Uint8Array(t),n=0;for(let o of e)s.set(o,n),n+=o.length;return s}ce();function K5(r,e,t=d0){r.handle(t,async({stream:s})=>{try{let n=await z_(s),o=await Zr(n);await e(o),await s.sink((async function*(){yield await hr({ok:!0})})())}catch(n){console.error("leave handler error:",n)}})}async function H5(r,e,t,s=d0){let n=$(e),o=r.getConnections?.(n)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([s]):i=await r.dialProtocol(n,[s]),await i.sink((async function*(){yield await hr(t)})())}finally{if(i)try{await i.close()}catch{}}}function H_(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 z_(r){let e=[];for await(let o of r.source)e.push(H_(o));let t=0;for(let o of e)t+=o.length;let s=new Uint8Array(t),n=0;for(let o of e)s.set(o,n),n+=o.length;return s}ce();var g0=Zs("rpc:ping");function z5(r,e=f0,t){r.handle(e,async({stream:s})=>{let n={ok:!0,ts:Date.now()};if(t)try{let o=await t();o.size_estimate!==void 0&&(n.size_estimate=o.size_estimate,n.confidence=o.confidence)}catch(o){g0("getSizeEstimate failed - %o",o)}await s.sink((async function*(){yield await hr(n)})())})}async function ja(r,e,t=f0){let s=Date.now(),n=$(e),o;try{try{let l=r.getConnections?.(n)??[];if(Array.isArray(l)&&l.length>0&&typeof l[0]?.newStream=="function")o=await l[0].newStream([t]);else{let u=await r.dialProtocol(n,[t]);o=u.stream??u}}catch{let u=await r.dialProtocol(n,[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){g0("sendPing chunk handling failed - %o",u)}let a=Math.max(0,Date.now()-s);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 Zr(i);return{ok:!!l.ok,rttMs:a,size_estimate:l.size_estimate,confidence:l.confidence}}catch(l){return g0("sendPing decode failed - %o",l),{ok:!1,rttMs:a}}}finally{if(o)try{await o.close()}catch{}}}ge();function q_(r){let e=0n;for(let t=0;t<r.length;t++)e=e<<8n|BigInt(r[t]);return e}function $_(r){if(r.length===0)return 0n;let e=[...r].sort((s,n)=>s<n?-1:s>n?1:0),t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2n:e[t]}function uu(r,e){let t=r.list(),s=t.length;if(s===0)return{n:0,confidence:0};if(s===1)return{n:1,confidence:.2};let n=1n<<256n,o=t.map(g=>q_(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]+n-o[o.length-1]);let a=$_(i),c=a>0n?a:n/BigInt(Math.max(1,s)),l=n/c,u=Math.max(1,Math.min(Number(l),1e9)),h=i[0],d=i[0];for(let g of i)g<h&&(h=g),g>d&&(d=g);let f=Math.min(1,s/Math.max(1,e*2)),p=d===0n?0:Number(h)/Number(d),m=Math.max(.05,Math.min(1,.5*f+.5*p));return{n:u,confidence:m}}var ui=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 s=(e-this.tokens)/this.refillPerSec;return Math.ceil(s*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)}};ce();Se();var pt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ws=class extends Error{static name="ValidationError";name="ValidationError"},Ya=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},hu=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};Vt();zr();Kt();ge();Se();wr();Kr();ge();Se();var Fe=re("node:net");jd();cl();Ro();Yd();Kr();ge();Se();function b0(r){return e=>K(e,r)}function w0(r){return e=>L(e,r)}function hi(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ln(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function q5(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=L(e[0],"base32"),s=parseInt(e[1],10);if(s<1||s>65536)throw new Error("Port number is not in range(1, 65536)");let n=Ln(s);return Ye([t,n],t.length+n.length)}function $5(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=or.decode(`b${e[0]}`),s=parseInt(e[1],10);if(s<1||s>65536)throw new Error("Port number is not in range(1, 65536)");let n=Ln(s);return Ye([t,n],t.length+n.length)}function x0(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),s=K(e,"base32"),n=hi(t);return`${s}:${n}`}var v0=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,s)=>{let n=parseInt(t,10);if(isNaN(n)||n<0||n>255)throw new pt("Invalid byte value in IP address");e[s]=n}),e},G5=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),s;for(s=0;s<t.length;s++){let o=(0,Fe.isIPv4)(t[s]),i;o&&(i=v0(t[s]),t[s]=K(i.subarray(0,2),"base16")),i!=null&&++s<8&&t.splice(s,0,K(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(s=0;s<t.length&&t[s]!=="";s++);let o=[s,1];for(s=9-t.length;s>0;s--)o.push("0");t.splice.apply(t,o)}let n=new Uint8Array(e+16);for(s=0;s<t.length;s++){t[s]===""&&(t[s]="0");let o=parseInt(t[s],16);if(isNaN(o)||o<0||o>65535)throw new pt("Invalid byte value in IP address");n[e++]=o>>8&255,n[e++]=o&255}return n},V5=function(r){if(r.byteLength!==4)throw new pt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},W5=function(r){if(r.byteLength!==16)throw new pt("IPv6 address was incorrect length");let e=[];for(let s=0;s<r.byteLength;s+=2){let n=r[s],o=r[s+1],i=`${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let s=new URL(`http://[${t}]`);return s.hostname.substring(1,s.hostname.length-1)}catch{throw new pt(`Invalid IPv6 address "${t}"`)}};function j5(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new pt(`Invalid IPv6 address "${r}"`)}}var y0=Object.values(ua).map(r=>r.decoder),G_=(function(){let r=y0[0].or(y0[1]);return y0.slice(2).forEach(e=>r=r.or(e)),r})();function Y5(r){return G_.decode(r)}function X5(r){return e=>r.encoder.encode(e)}function V_(r){if(parseInt(r).toString()!==r)throw new ws("Value must be an integer")}function W_(r){if(r<0)throw new ws("Value must be a positive integer, or zero")}function j_(r){return e=>{if(e>r)throw new ws(`Value must be smaller than or equal to ${r}`)}}function Y_(...r){return e=>{for(let t of r)t(e)}}var Xa=Y_(V_,W_,j_(65535));var ct=-1,E0=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 hu(`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(s=>{this.protocolsByName.delete(s)}))}},Rt=new E0,uA=[{code:4,name:"ip4",size:32,valueToBytes:v0,bytesToValue:V5,validate:r=>{if(!(0,Fe.isIPv4)(r))throw new ws(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ln,bytesToValue:hi,validate:Xa},{code:273,name:"udp",size:16,valueToBytes:Ln,bytesToValue:hi,validate:Xa},{code:33,name:"dccp",size:16,valueToBytes:Ln,bytesToValue:hi,validate:Xa},{code:41,name:"ip6",size:128,valueToBytes:G5,bytesToValue:W5,stringToValue:j5,validate:r=>{if(!(0,Fe.isIPv6)(r))throw new ws(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ct},{code:43,name:"ipcidr",size:8,bytesToValue:b0("base10"),valueToBytes:w0("base10")},{code:53,name:"dns",size:ct,resolvable:!0},{code:54,name:"dns4",size:ct,resolvable:!0},{code:55,name:"dns6",size:ct,resolvable:!0},{code:56,name:"dnsaddr",size:ct,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Ln,bytesToValue:hi,validate:Xa},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ct,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ct,bytesToValue:b0("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?w0("base58btc")(r):De.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:x0,valueToBytes:q5},{code:445,name:"onion3",size:296,bytesToValue:x0,valueToBytes:$5},{code:446,name:"garlic64",size:ct},{code:447,name:"garlic32",size:ct},{code:448,name:"tls"},{code:449,name:"sni",size:ct},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ct,bytesToValue:X5(Ud),valueToBytes:Y5},{code:480,name:"http"},{code:481,name:"http-path",size:ct,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:ct}];uA.forEach(r=>{Rt.addProtocol(r)});function Z5(r){let e=[],t=0;for(;t<r.length;){let s=as(r,t),n=Rt.getProtocol(s),o=Le(s),i=hA(n,r,t+o),a=0;i>0&&n.size===ct&&(a=Le(i));let c=o+a+i,l={code:s,name:n.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,h=r.subarray(u,u+i);l.value=n.bytesToValue?.(h)??K(h)}e.push(l),t+=c}return e}function Q5(r){let e=0,t=[];for(let s of r){if(s.bytes==null){let n=Rt.getProtocol(s.code),o=Le(s.code),i,a=0,c=0;s.value!=null&&(i=n.valueToBytes?.(s.value)??L(s.value),a=i.byteLength,n.size===ct&&(c=Le(a)));let l=new Uint8Array(o+c+a),u=0;ko(s.code,l,u),u+=o,i!=null&&(n.size===ct&&(ko(a,l,u),u+=c),l.set(i,u)),s.bytes=l}t.push(s.bytes),e+=s.bytes.byteLength}return Ye(t,e)}function J5(r){if(r.charAt(0)!=="/")throw new pt('String multiaddr must start with "/"');let e=[],t="protocol",s="",n="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?n+=r.charAt(o):s+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=Rt.getProtocol(n);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),s="",n="",t="protocol";continue}else if(a)throw new pt(`Component ${n} 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(s==="")throw new pt(`Component ${n} was missing value`);l.value=c.stringToValue?.(s)??s}e.push(l),s="",n="",t="protocol"}}}if(n!==""&&s!=="")throw new pt("Incomplete multiaddr");return e}function e4(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Rt.getProtocol(e.code);if(t==null)throw new pt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function hA(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:as(e,t)}var dA=Symbol.for("nodejs.util.inspect.custom"),M0=Symbol.for("@multiformats/multiaddr"),fA=[53,54,55,56],D0=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function pA(r){if(r==null&&(r="/"),Js(r))return r.getComponents();if(r instanceof Uint8Array)return Z5(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),J5(r);if(Array.isArray(r))return r;throw new pt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var mu=class r{[M0]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=pA(e),t.validate!==!1&&mA(this)}get bytes(){return this.#r==null&&(this.#r=Q5(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=e4(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,s,n,o="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(o=`%${l??""}`),fA.includes(a)&&(t="tcp",n=443,s=`${l??""}${o}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",n=parseInt(l??"")),(a===4||a===41)&&(t="tcp",s=`${l??""}${o}`,e=a===41?6:4);if(e==null||t==null||s==null||n==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:s,transport:t,port:n}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let s=Rt.getProtocol(e);return{code:e,size:s.size??0,name:s.name,resolvable:!!s.resolvable,path:!!s.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 s=Rt.getProtocol(e),n=[e];return t!=null&&n.push(s.valueToBytes?.(t)??L(t)),n})}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(),s=this.toString(),n=s.lastIndexOf(t);if(n<0)throw new Ya(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(s.slice(0,n),{validate:!1})}decapsulateCode(e){let t;for(let s=this.#e.length-1;s>-1;s--)if(this.#e[s].code===e){t=s;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:s,value:n})=>{s===421&&e.push([s,n]),s===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let s=t[1];return s[0]==="Q"||s[0]==="1"?K(me.decode(`z${s}`),"base58btc"):K(De.parse(s).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(Rt.getProtocol(e.code).path)return e.value??null;return null}equals(e){return ae(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let s=t4.get(t.name);if(s==null)throw new D0(`no available resolver for ${t.name}`);return(await s(this,e)).map(o=>G(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)}[dA](){return`Multiaddr(${this.toString()})`}};function mA(r){r.getComponents().forEach(e=>{let t=Rt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}var gu=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,s=e();return s===void 0&&(this.index=t),s}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,s){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return s()})}readNumber(e,t,s,n){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*n)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let d=Number.parseInt(h,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!s&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let s=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(s===void 0)return;e[t]=s}return e})}readIPv6Addr(){let e=t=>{for(let s=0;s<t.length/2;s++){let n=s*2;if(s<t.length-3){let i=this.readSeparator(":",s,()=>this.readIPv4Addr());if(i!==void 0)return t[n]=i[0],t[n+1]=i[1],t[n+2]=i[2],t[n+3]=i[3],[n+4,!0]}let o=this.readSeparator(":",s,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[n,!1];t[n]=o>>8,t[n+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[s,n]=e(t);if(s===16)return t;if(n||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(s+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var r4=45,gA=15,gi=new gu;function s4(r){if(!(r.length>gA))return gi.new(r).parseWith(()=>gi.readIPv4Addr())}function n4(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>r4))return gi.new(r).parseWith(()=>gi.readIPv6Addr())}function Qa(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>r4)return;let t=gi.new(r).parseWith(()=>gi.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 o4(r,e,t){let s=0;for(let n of r)if(!(s<e)){if(s>t)break;if(n!==255)return!1;s++}return!0}function i4(r,e,t,s){let n=0;for(let o of r)if(!(n<t)){if(n>s)break;if(o!==e[n])return!1;n++}return!0}function O0(r){switch(r.length){case Un:return r.join(".");case Kn:{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 a4(r){let e=0;for(let[t,s]of r.entries()){if(s===255){e+=8;continue}for(;(s&128)!=0;)e++,s=s<<1;if((s&128)!=0)return-1;for(let n=t+1;n<r.length;n++)if(r[n]!=0)return-1;break}return e}function c4(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Un=4,Kn=16,Uz=parseInt("0xFFFF",16),yA=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Ja(r,e){e.length===Kn&&r.length===Un&&o4(e,0,11)&&(e=e.slice(12)),e.length===Un&&r.length===Kn&&i4(r,yA,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let s=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=r[n]&e[n];return s}function l4(r,e){if(typeof e=="string"&&(e=Qa(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 L0(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let s=Un,n=s4(e);if(n==null&&(s=Kn,n=n4(e),n==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>s*8)throw new Error("Failed to parse given CIDR: "+r);let i=R0(o,8*s);return{network:Ja(n,i),mask:i}}function R0(r,e){if(e!==8*Un&&e!==8*Kn)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,s=new Uint8Array(t);for(let n=0;n<t;n++){if(r>=8){s[n]=255,r-=8;continue}s[n]=255-(255>>r),r=0}return s}var Hn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=L0(e));else{let s=Qa(e);if(s==null)throw new Error("Failed to parse network");t=String(t);let n=parseInt(t,10);if(Number.isNaN(n)||String(n).length!==t.length||n<0||n>s.length*8){let o=Qa(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=R0(n,8*s.length);this.network=Ja(s,this.mask)}}contains(e){return l4({network:this.network,mask:this.mask},e)}toString(){let e=a4(this.mask),t=e!==-1?String(e):c4(this.mask);return O0(this.network)+"/"+t}};function u4(r,e){return new Hn(r).contains(e)}ge();Se();function N0(r){let e,t;if(r.getComponents().forEach(s=>{(s.name==="ip4"||s.name==="ip6")&&(t=s.value),s.name==="ipcidr"&&(e=s.value)}),e==null||t==null)throw new Error("Invalid multiaddr");return new Hn(t,e)}function h4(r,e){return Rt.getProtocol(r).bytesToValue?.(e)??K(e,"base16")}var t4=new Map;function Js(r){return!!r?.[M0]}function G(r){return new mu(r)}function yi(r){let e=Rt.getProtocol(r);return{code:e.code,size:e.size??0,name:e.name,resolvable:!!e.resolvable,path:!!e.path}}function yu(r,e){let t=Math.max(r.length,e.length),s=new Uint8Array(t);for(let n=0;n<t;n++){let o=r[r.length-1-n]??0,i=e[e.length-1-n]??0;s[t-1-n]=o^i}return s}function B0(r,e){let t=Math.max(r.length,e.length);for(let s=0;s<t;s++){let n=r[s]??0,o=e[s]??0;if(n<o)return!0;if(n>o)return!1}return!1}function d4(r){for(let e=0;e<r.length;e++)if(r[e]!==0)return e;return Number.POSITIVE_INFINITY}function bA(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 f4(r,e,t,s){return B0(e,s)?!0:B0(s,e)?!1:r<t}function bu(r,e,t,s,n,o=1){let i,a=[];for(let u of t){let h=r.getById(u);if(!h)continue;let d=yu(h.coord,e),f=s(u),p=(f?1:0)+.25*n(u);a.push({id:u,dist:d,connected:f,score:p}),(!i||f4(u,d,i.id,i.dist))&&(i={id:u,dist:d})}if(!i)return;let c=d4(i.dist),l;for(let u of a){if(!u.connected)continue;if(d4(u.dist)<=c+o){if(!l){l={id:u.id,dist:u.dist,score:u.score};continue}f4(u.id,u.dist,l.id,l.dist)?l={id:u.id,dist:u.dist,score:u.score}:bA(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 p4(r=12,e=.08,t=.03,s=.6,n=.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:s,sMin:n,sMax:o,eps:i}}function wu(r,e){let t=yu(r,e),s=0;for(let o=0;o<t.length;o++){let i=t[o]??0;if(i===0){s+=8;continue}let a=7-Math.floor(Math.log2(i));s+=a;break}return 1-Math.min(256,s)/256}function m4(r,e){let t=r/Math.max(1e-9,e);return Math.exp(-.5*t*t)}function F0(r,e){for(let t=0;t<r.centers.length;t++){let s=m4(Math.abs(e-r.centers[t]),r.sigma);r.occupancy[t]=(1-r.alpha)*r.occupancy[t]+r.alpha*s}}function U0(r,e){let t=0,s=0;for(let i=0;i<r.centers.length;i++){let a=m4(Math.abs(e-r.centers[i]),r.sigma);t+=r.occupancy[i]*a,s+=1*a}let n=(s+r.eps)/(t+r.eps),o=Math.pow(n,r.beta);return Math.max(r.sMin,Math.min(r.sMax,o))}function wA(r,e){let t=Math.max(0,e-r.lastAccess),n=Math.log(2)/Math.max(1,6e4);return Math.exp(-n*t)}function xA(r){return Math.log1p(r.accessCount)/5}function vA(r){let e=r.successCount+r.failureCount,t=e>0?r.successCount/e:.5,s=r.avgLatencyMs>0?Math.min(1,r.avgLatencyMs/1e3):.5,n=.5*t+.5*(1-s);return Math.max(0,n)}function K0(r,e){return .4*wA(r,e)+.2*xA(r)+.4*vA(r)}function H0(r,e){return{...r,...e}}function g4(r,e,t,s=Date.now()){F0(t,e);let n=K0(r,s),o=U0(t,e),i=n*o;return H0(r,{lastAccess:s,relevance:i,accessCount:r.accessCount+1})}function y4(r,e,t,s,n=Date.now()){F0(s,t);let o=.2,i=r.avgLatencyMs>0?(1-o)*r.avgLatencyMs+o*e:e,a=K0({...r,avgLatencyMs:i,successCount:r.successCount+1},n),c=U0(s,t),l=a*c;return H0(r,{lastAccess:n,relevance:l,successCount:r.successCount+1,avgLatencyMs:i})}function b4(r,e,t,s=Date.now()){F0(t,e);let n=K0({...r,failureCount:r.failureCount+1},s)*.7,o=U0(t,e),i=n*o;return H0(r,{lastAccess:s,relevance:i,failureCount:r.failureCount+1})}var Dr=Zs("service:fret"),bi=class{mode="passive";store=new lu;cfg;node;stabilizing=!1;inflightAct=0;bucketNeighbors;bucketMaybeAct;bucketDiscovery;announcedIds=new Map;postBootstrapAnnounced=!1;sparsity=p4();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=M5(this.cfg.networkName),this.bucketDiscovery=new ui(this.cfg.profile==="core"?50:10,this.cfg.profile==="core"?25:3),this.bucketNeighbors=new ui(this.cfg.profile==="core"?20:8,this.cfg.profile==="core"?10:4),this.bucketMaybeAct=new ui(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 Be(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 s=this.store.protectedIdsAround(t,Math.max(2,this.cfg.m)),n=this.store.list();n.sort((o,i)=>o.relevance-i.relevance);for(let o of n){if(this.store.size()<=e)break;s.has(o.id)||this.store.remove(o.id)}}async applyTouch(e,t){let s=this.store.getById(e)??this.store.upsert(e,t),n=wu(await this.selfCoord(),t),o=g4(s,n,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,accessCount:o.accessCount})}async applySuccess(e,t,s){let n=this.store.getById(e)??this.store.upsert(e,t),o=wu(await this.selfCoord(),t),i=y4(n,s,o,this.sparsity);this.store.update(e,{lastAccess:i.lastAccess,relevance:i.relevance,successCount:i.successCount,avgLatencyMs:i.avgLatencyMs})}async applyFailure(e,t){let s=this.store.getById(e)??this.store.upsert(e,t),n=wu(await this.selfCoord(),t),o=b4(s,n,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){Dr("postBootstrap announce failed - %o",t)}}}),this.node.addEventListener("peer:connect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let s=this.store.getById(t)?.coord??await Be($(t));this.store.setState(t,"connected"),await this.applyTouch(t,s)}catch(t){Dr("peer:connect handler failed - %o",t)}}),this.node.addEventListener("peer:disconnect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let s=this.store.getById(t)?.coord??await Be($(t));this.store.setState(t,"disconnected"),await this.applyFailure(t,s)}catch(t){Dr("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(){L5(this.node,async()=>this.handleNeighborsRequest(),(e,t)=>{this.mergeAnnounceSnapshot(e,t)},this.protocols),B5(this.node,async e=>this.handleMaybeAct(e),this.protocols.PROTOCOL_MAYBE_ACT),K5(this.node,async e=>this.handleLeave(e.from),this.protocols.PROTOCOL_LEAVE),z5(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(s){return console.error("routeAct failed:",s),await this.nearAnchorOnly(e)}finally{this.inflightAct--}}isConnected(e){try{return this.node.getConnections($(e)).length>0}catch{return!1}}hasAddresses(e){try{let t=this.node.getMultiaddrsForPeer?.($(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 Be(this.node.peerId),s=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(t,"right",this.cfg.m),...this.getNeighbors(t,"left",this.cfg.m)])).filter(i=>i!==s).slice(0,e),o=await this.snapshot();for(let i of n)if(this.isConnected(i)||this.hasAddresses(i))try{await m0(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 Be(this.node.peerId),t=this.node.peerId.toString(),s=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(n=>n!==t);for(let n of s)if(this.isConnected(n)||this.hasAddresses(n))try{await ja(this.node,n,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(o){Dr("preconnectNeighbors ping failed for %s - %o",n,o)}}catch(e){Dr("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(),s=this.node.peerId.toString(),n=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!==s).slice(0,n);for(let i of o)if(this.isConnected(i)||this.hasAddresses(i))try{await ja(this.node,i,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(a){Dr("active preconnect ping failed for %s - %o",i,a)}}catch(t){Dr("active preconnect tick failed - %o",t)}setTimeout(e,1e3)};e()}async sendLeaveToNeighbors(){try{let e=await Be(this.node.peerId),t=this.node.peerId.toString(),s=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),n={v:1,from:this.node.peerId.toString(),timestamp:Date.now()};for(let o of s)try{await H5(this.node,o,n,this.protocols.PROTOCOL_LEAVE)}catch(i){Dr("sendLeave failed for %s - %o",o,i)}}catch(e){Dr("sendLeaveToNeighbors outer failed - %o",e)}}async handleLeave(e){try{let t=null,s=this.store.getById(e);if(s)t=s.coord;else try{t=await Be($(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 n=Array.from(new Set([...this.store.neighborsRight(t,this.cfg.m),...this.store.neighborsLeft(t,this.cfg.m)])),o=this.expandCohort(n,t,Math.max(2,Math.ceil(this.cfg.m/2))),i=new Set(n),a=o.filter(l=>!i.has(l)),c=a.slice(0,Math.min(a.length,6));for(let l of c)try{if(await ja(this.node,l,this.protocols.PROTOCOL_PING),!this.isConnected(l)){let u=await this.snapshot();await m0(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 s=$(e),n=await Be(s),o=[];this.store.getById(e)||o.push(e),this.store.upsert(e,n),await this.applyTouch(e,n),t.metadata&&this.store.update(e,{metadata:t.metadata});for(let i of[...t.successors??[],...t.predecessors??[]])try{let a=await Be($(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=L(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){Dr("mergeAnnounceSnapshot sample upsert failed for %s - %o",i.id,a)}this.enforceCapacity(),this.emitDiscovered(o)}catch(s){console.warn("mergeAnnounceSnapshot failed for",e,s)}}async seedFromPeerStore(){try{let e=this.node.peerStore?.getPeers?.()??[],t=[];for(let s of e)try{let n=await Be(s.id),o=s.id.toString();this.store.getById(o)||t.push(o),this.store.upsert(o,n)}catch(n){console.warn("failed to add peer from peerStore",s?.id?.toString?.(),n)}try{let s=await Be(this.node.peerId),n=this.node.peerId.toString();this.store.getById(n)||t.push(n),this.store.upsert(n,s)}catch(s){console.error("failed to add self to store",s)}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 s=t;if(t.startsWith("/"))try{let a=G(t).getPeerId();a&&(s=a)}catch{}let n=$(s),o=await Be(n);this.store.getById(s)||e.push(s),this.store.upsert(s,o),await this.applyTouch(s,o)}catch(s){console.warn("seedFromBootstraps failed for",t,s)}this.enforceCapacity(),this.emitDiscovered(e)}async stabilizeOnce(){let e=await Be(this.node.peerId),t=this.node.peerId.toString(),n=this.getNeighbors(e,"both",Math.max(2,this.cfg.m)).filter(o=>o!==t&&(this.isConnected(o)||this.hasAddresses(o)));await this.probeNeighborsLatency(n.slice(0,4)),await this.mergeNeighborSnapshots(n.slice(0,4))}async probeNeighborsLatency(e){for(let t of e)try{let s=await ja(this.node,t,this.protocols.PROTOCOL_PING);if(this.diag.pingsSent++,s.ok){let n=this.store.getById(t)?.coord??await Be($(t));await this.applySuccess(t,n,s.rttMs),this.diag.pingsOk++}else{let n=this.store.getById(t)?.coord??await Be($(t));await this.applyFailure(t,n),this.diag.pingsFail++}}catch{try{let n=this.store.getById(t)?.coord??await Be($(t));await this.applyFailure(t,n),this.diag.pingsFail++}catch{}}}async mergeNeighborSnapshots(e){let t=[];for(let s of e)try{let n=await R5(this.node,s,this.protocols.PROTOCOL_NEIGHBORS);this.diag.snapshotsFetched++;let o=this.cfg.profile==="core"?16:8,i=this.cfg.profile==="core"?16:8,a=(n.successors??[]).slice(0,o),c=(n.predecessors??[]).slice(0,i);for(let u of[...a,...c])try{let h=await Be($(u));this.store.getById(u)||t.push(u),this.store.upsert(u,h),await this.applyTouch(u,h)}catch(h){console.warn("failed to merge neighbor",u,h)}let l=this.cfg.profile==="core"?8:6;for(let u of(n.sample??[]).slice(0,l))try{let h=L(u.coord,"base64url");this.store.getById(u.id)||t.push(u.id),this.store.upsert(u.id,h),await this.applyTouch(u.id,h)}catch(h){Dr("mergeNeighborSnapshots sample upsert failed for %s - %o",u.id,h)}}catch(n){console.warn("fetchNeighbors failed for",s,n)}this.enforceCapacity(),this.emitDiscovered(t)}async snapshot(){let e=await Be(this.node.peerId),{n:t,confidence:s}=uu(this.store,this.cfg.m),n=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,n),u=c.slice(0,o),h=Array.from(new Set([...l.slice(0,4),...u.slice(0,4)])).slice(0,i),d=await Promise.all(h.map(async f=>{let p=this.store.getById(f);return p?{id:f,coord:D5(p.coord),relevance:p.relevance}:{id:f,coord:"",relevance:0}}));return{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:l,predecessors:u,sample:d,size_estimate:t,confidence:s,sig:"",metadata:this.metadata}}neighborDistance(e,t,s){let n=new Set,o=Math.max(1,s),a=this.assembleCohort(t,o,n).findIndex(c=>c===e);return a>=0?a:Number.POSITIVE_INFINITY}getNeighbors(e,t,s){let n=[];return(t==="right"||t==="both")&&n.push(...this.store.neighborsRight(e,s)),(t==="left"||t==="both")&&n.push(...this.store.neighborsLeft(e,s)),Array.from(new Set(n)).slice(0,s)}nextSuccessor(e,t){let s=t.findIndex(n=>n.id===e.id);return t[(s+1)%t.length]}nextPredecessor(e,t){let s=t.findIndex(n=>n.id===e.id);return t[(s-1+t.length)%t.length]}assembleCohort(e,t,s){let n=[],o=s??new Set,i=this.store.neighborsRight(e,t*2),a=this.store.neighborsLeft(e,t*2),c=0,l=0;for(;n.length<t&&(c<i.length||l<a.length);)if(n.length%2===0){let u=i[c++];u&&!o.has(u)&&n.push(u)}else{let u=a[l++];u&&!o.has(u)&&n.push(u)}return Array.from(new Set(n)).slice(0,t)}expandCohort(e,t,s,n){let o=new Set(e),i=this.assembleCohort(t,e.length+s,n);for(let a of i)o.add(a);return Array.from(o)}async nearAnchorOnly(e){let t=L(e.key,"base64url"),s=await Xt(t),n=this.getNeighbors(s,"right",this.cfg.m),o=this.getNeighbors(s,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...n.slice(0,3),...o.slice(0,3)]),cohort_hint:Array.from(new Set([...n.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(),s=this.cfg.profile==="core"?10*6e4:30*6e4,n=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=$(i);n.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:c,multiaddrs:[]}})),this.announcedIds.set(i,t+s),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 s=c=>.5,n=new Uint8Array(32),o=bu(this.store,n,t,c=>this.isConnected(c),s),i=t.filter(c=>c!==o),a=bu(this.store,n,i,c=>this.isConnected(c),s);return[o,a].filter(c=>!!c)}async routeAct(e){let t=L(e.key,"base64url"),s=await Xt(t),n=this.node.peerId.toString();if(this.neighborDistance(n,s,2)>1&&e.ttl>0){let h=new Set([...e.breadcrumbs??[],n]),d=this.assembleCohort(s,Math.max(4,this.cfg.m)).filter(m=>!h.has(m)),f=m=>.5,p=bu(this.store,s,d,m=>this.isConnected(m),f);if(p){let m={...e,ttl:e.ttl-1,breadcrumbs:[...e.breadcrumbs??[],n]};try{return await F5(this.node,p,m,this.protocols.PROTOCOL_MAYBE_ACT)}catch(g){console.warn("forward maybeAct failed to",p,g)}}}let{n:i,confidence:a}=uu(this.store,this.cfg.m),c=this.getNeighbors(s,"right",this.cfg.m),l=this.getNeighbors(s,"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,s="external"){let n=Date.now();this.networkObservations.push({estimate:e,confidence:t,timestamp:n,source:s});let o=n-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=uu(this.store,this.cfg.m),t=Date.now(),s=[{estimate:e.n,confidence:e.confidence,timestamp:t,source:"fret"},...this.networkObservations];if(s.length===0)return{size_estimate:0,confidence:0,sources:0};let n=0,o=0,i=0;for(let l of s){let u=t-l.timestamp,h=Math.exp(-u/(this.observationWindowMs/3)),d=h*l.confidence;o+=l.estimate*d,i+=l.confidence*h,n+=d}if(n===0)return{size_estimate:0,confidence:0,sources:0};let a=Math.round(o/n),c=i/s.length;return{size_estimate:a,confidence:Math.min(1,c),sources:s.length}}getNetworkChurn(){if(this.networkObservations.length<2)return 0;let e=Date.now(),t=this.observationWindowMs/2,s=e-t,n=this.networkObservations.filter(l=>l.timestamp>s),o=this.networkObservations.filter(l=>l.timestamp<=s);if(n.length===0||o.length===0)return 0;let i=n.reduce((l,u)=>l+u.estimate,0)/n.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,s=this.networkObservations.filter(c=>c.timestamp<t);if(s.length<3)return!1;let n=s.slice(-5).reduce((c,l)=>c+l.estimate,0)/Math.min(5,s.length);if(e.size_estimate/n<.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}))}};ce();var EA=Zs("service:discovery");function z0(r,e){let t=r;for(let s of e.list())try{let n=$(s.id);t.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:n,multiaddrs:[]}}))}catch(n){EA("seedDiscovery failed for %s - %o",s.id,n)}}var xu=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 bi(this.nodeRef,this.cfg)}return this.inner}async start(){if(this.ensure(),!this.nodeRef)throw new Error("Libp2pFretService.start: libp2p node not injected");z0(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,s){return this.ensure().getNeighbors(e,t,s)}assembleCohortForKey(e,t){return this.ensure().assembleCohort(e,t)}getDiagnostics(){return this.ensure().getDiagnostics?.()}neighborDistance(e,t,s){return this.ensure().neighborDistance(e,t,s)}getNeighbors(e,t,s){return this.ensure().getNeighbors(e,t,s)}assembleCohort(e,t,s){return this.ensure().assembleCohort(e,t,s)}expandCohort(e,t,s,n){return this.ensure().expandCohort(e,t,s,n)}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 q0(r){return e=>new xu(e,r)}ce();var w4="/db-p2p/sync/",x4="1.0.0",ec=(r="")=>`${r}${w4}${x4}`;var tc=class extends cs{protocol;constructor(e,t,s=""){super(e,t),this.protocol=ec(s)}async requestBlock(e){return await this.processMessage(e,this.protocol)}getProtocol(){return this.protocol}};var rc=class{fretAdapter;peerNetwork;protocolPrefix;metrics={totalRequests:0,successByRing:new Map,failureByRing:new Map,averageDurationMs:0};constructor(e,t,s){this.fretAdapter=e,this.peerNetwork=t,this.protocolPrefix=s}log=lr("storage:restoration");async restore(e,t){let s=Date.now();this.metrics.totalRequests++;let n=await this.getMyRingPeers(e),o=this.getMyRingDepth();for(let a of n){let c=await this.queryPeer(a,e,t);if(c)return this.recordSuccess(o,e,Date.now()-s),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 h=await this.queryPeer(u,e,t);if(h)return this.recordSuccess(a,e,Date.now()-s),h}}let i=Date.now()-s;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),s=await Xt(t);return this.fretAdapter.getFret().assembleCohort(s,10)}getMyRingDepth(){return this.fretAdapter.getMyArachnodeInfo()?.ringDepth??8}filterByPartition(e,t,s){if(s===0)return e;let n=this.extractBlockPrefix(t,s);return e.filter(o=>{let i=this.fretAdapter.getArachnodeInfo(o);return!i||!i.partition?!1:i.partition.prefixValue===n})}extractBlockPrefix(e,t){let s=new TextEncoder().encode(e),n=new Uint8Array(32);for(let i=0;i<Math.min(s.length,n.length);i++)n[i]=s[i];let o=0;for(let i=0;i<t;i++){let a=Math.floor(i/8),c=7-i%8,l=n[a]>>c&1;o=o<<1|l}return o}async queryPeer(e,t,s){try{let n=$(e),i=await new tc(n,this.peerNetwork,this.protocolPrefix).requestBlock({blockId:t,rev:s});return i.success?i.archive:void 0}catch(n){this.log("queryPeer failed for %s - %o",e,n);return}}recordSuccess(e,t,s){let n=this.metrics.successByRing.get(e)??0;this.metrics.successByRing.set(e,n+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+s)/o,console.log(`[Ring ${e}] Successfully restored block ${t} in ${s}ms`)}getMetrics(){return{...this.metrics}}};var sc=class{fretAdapter;storageMonitor;config;constructor(e,t,s){this.fretAdapter=e,this.storageMonitor=t,this.config=s}async determineRing(){let e=await this.storageMonitor.getCapacity();if(e.available<this.config.minCapacity)return-1;let n=1e3*(100*1024),o=e.available/n,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 s=await Be({toString:()=>t}),n=e,o=this.extractPrefix(s,n);return{prefixBits:n,prefixValue:o}}async createArachnodeInfo(e){let t=await this.storageMonitor.getCapacity(),s=await this.determineRing(),n=s>=0?await this.calculatePartition(s,e):void 0;return{ringDepth:Math.max(0,s),partition:n,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 s=await this.determineRing();if(s>0)return{shouldMove:!0,direction:"in",newRingDepth:s-1}}return{shouldMove:!1}}extractPrefix(e,t){let s=0;for(let n=0;n<t;n++){let o=Math.floor(n/8),i=7-n%8,a=e[o]>>i&1;s=s<<1|a}return s}};var nc=class{storage;config;constructor(e,t={}){this.storage=e,this.config=t}async getCapacity(){let t=this.config.totalBytes??10737418240,s=this.config.usedBytes,n=this.config.availableBytes;if(s!==void 0||n!==void 0||this.config.totalBytes!==void 0){let a=s??Math.max(0,t-(n??t)),c=n??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 oc=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(s=>s.metadata?.[r.ARACHNODE_KEY]?.ringDepth===e).map(s=>s.id)}getKnownRings(){let e=this.fret.listPeers(),t=new Set;for(let s of e){let n=s.metadata?.[r.ARACHNODE_KEY];n?.ringDepth!==void 0&&t.add(n.ringDepth)}return Array.from(t).sort((s,n)=>s-n)}getRingStats(){let e=this.fret.listPeers(),t=new Map;for(let s of e){let n=s.metadata?.[r.ARACHNODE_KEY];if(n){let o=t.get(n.ringDepth)??{count:0,totalCapacity:0};t.set(n.ringDepth,{count:o.count+1,totalCapacity:o.totalCapacity+n.capacity.available})}}return Array.from(t.entries()).map(([s,n])=>({ringDepth:s,peerCount:n.count,avgCapacity:n.totalCapacity/n.count})).sort((s,n)=>s.ringDepth-n.ringDepth)}getFret(){return this.fret}};ge();Se();var vu=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=ec(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 s=await this.buildArchive(t.blockId,t.rev,t.includePending,t.maxRevisions),n=s?{success:!0,archive:s,responderId:e.id}:{success:!1,error:"Block not found in local storage"};await this.sendResponse(e,n),this.log("[Ring Zulu] %s sync request for block %s",n.success?"Fulfilled":"Failed",t.blockId)}catch(t){this.log.error("Error handling sync request:",t);try{let s={success:!1,error:t instanceof Error?t.message:"Unknown error"};await this.sendResponse(e,s)}catch(s){this.log.error("Failed to send error response:",s)}}finally{try{await e.close()}catch{}}}async readRequest(e){let t=[];if(await st(e.source,Gt,async n=>{for await(let o of n)t.push(o.subarray())}),t.length===0)throw new Error("No request received");let s=K(t[0],"utf8");return JSON.parse(s)}async sendResponse(e,t){let s=JSON.stringify(t),n=L(s,"utf8");await st([n],sr,e.sink)}async buildArchive(e,t,s,n){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}}},$0=(r={})=>e=>new vu(e,r);Se();ce();var ic=class r{libp2p;clusterSize;selfCoordinationConfig;networkHighWaterMark=1;lastConnectedTime=Date.now();constructor(e,t=16,s){this.libp2p=e,this.clusterSize=t,this.selfCoordinationConfig={gracePeriodMs:s?.gracePeriodMs??3e4,shrinkageThreshold:s?.shrinkageThreshold??.5,allowSelfCoordination:s?.allowSelfCoordination??!0},this.setupConnectionTracking()}coordinatorCache=new Map;static MAX_CACHE_ENTRIES=1e3;log=lr("libp2p-key-network");toCacheKey(e){return K(e,"base64url")}setupConnectionTracking(){this.libp2p.addEventListener("connection:open",()=>{this.updateNetworkObservations()})}updateNetworkObservations(){(this.libp2p.getConnections?.()??[]).length>0&&(this.lastConnectedTime=Date.now());try{let s=this.getFret().getNetworkSizeEstimate();s.size_estimate>this.networkHighWaterMark&&(this.networkHighWaterMark=s.size_estimate,this.log("network-hwm-updated mark=%d confidence=%f",this.networkHighWaterMark,s.confidence))}catch{let s=(this.libp2p.getConnections?.().length??0)+1;s>this.networkHighWaterMark&&(this.networkHighWaterMark=s,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 s=t.getNetworkSizeEstimate(),n=1-s.size_estimate/this.networkHighWaterMark;if(n>this.selfCoordinationConfig.shrinkageThreshold)return this.log("self-coord-blocked: suspicious-shrinkage current=%d hwm=%d shrinkage=%f",s.size_estimate,this.networkHighWaterMark,n),{allow:!1,reason:"suspicious-shrinkage"}}catch{let t=this.libp2p.getConnections?.()??[];if(this.networkHighWaterMark>1&&t.length===0){let s=Date.now()-this.lastConnectedTime;if(s<this.selfCoordinationConfig.gracePeriodMs)return this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",s),{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,s=1800*1e3){let n=this.toCacheKey(e),o=Date.now();for(let[i,a]of this.coordinatorCache)a.expires<=o&&this.coordinatorCache.delete(i);for(this.coordinatorCache.set(n,{id:t,expires:o+s});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),s=this.coordinatorCache.get(t);if(s&&s.expires>Date.now())return s.id;s&&this.coordinatorCache.delete(t)}connect(e,t,s){let n=this.libp2p.getConnections?.(e)??[];if(Array.isArray(n)&&n.length>0&&typeof n[0]?.newStream=="function")return n[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 s=this.getFret(),n=await Xt(e),o=s.getNeighbors(n,"both",t);return Array.from(new Set(o)).slice(0,t)}async findCoordinator(e,t){let s=new Set((t?.excludedPeers??[]).map(l=>l.toString())),n=this.toCacheKey(e).substring(0,12);this.log("findCoordinator:start key=%s excluded=%o",n,Array.from(s).map(l=>l.substring(0,12)));let o=this.getCachedCoordinator(e);if(o!=null&&!s.has(o.toString()))return this.log("findCoordinator:cached-hit key=%s coordinator=%s",n,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),h=new Set(u.map(f=>f.toString()));this.log("findCoordinator:connected-peers key=%s count=%d peers=%o attempt=%d",n,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",n,f.map(g=>g.substring(0,12)));let p=f.filter(g=>h.has(g)||g===this.libp2p.peerId.toString());this.log("findCoordinator:fret-connected key=%s count=%d peers=%o",n,p.length,p.map(g=>g.substring(0,12)));let m=p.find(g=>!s.has(g));if(m){let g=$(m);return this.recordCoordinator(e,g),this.log("findCoordinator:fret-selected key=%s coordinator=%s",n,m.substring(0,12)),g}}catch(f){this.log("findCoordinator getNeighborIdsForKey failed - %o",f)}let d=u.find(f=>!s.has(f.toString()));if(d)return this.recordCoordinator(e,d),this.log("findCoordinator:connected-fallback key=%s coordinator=%s",n,d.toString().substring(0,12)),d;if(u.length===0&&l<i-1){this.log("findCoordinator:no-connections-retry key=%s attempt=%d delay=%dms",n,l,a),await new Promise(f=>setTimeout(f,a));continue}}let c=this.libp2p.peerId;if(!s.has(c.toString())){let l=this.shouldAllowSelfCoordination();if(!l.allow)throw this.log("findCoordinator:self-coord-blocked key=%s reason=%s",n,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",n,c.toString().substring(0,12),l.reason):this.log("findCoordinator:self-selected key=%s coordinator=%s reason=%s",n,c.toString().substring(0,12),l.reason),c}throw this.log("findCoordinator:all-excluded key=%s self=%s",n,c.toString().substring(0,12)),new Error("No coordinator available for key (all candidates excluded)")}getConnectedAddrsByPeer(){let e=this.libp2p.getConnections(),t={};for(let s of e){let n=s.remotePeer.toString(),o=s.remoteAddr?.toString?.();o&&(t[n]??=[]).push(o)}return t}parseMultiaddrs(e){let t=[];for(let s of e)try{t.push(G(s))}catch(n){console.warn("invalid multiaddr from connection",s,n)}return t}async findCluster(e){let t=this.getFret(),s=await Xt(e),n=t.assembleCohort(s,this.clusterSize),o=this.toCacheKey(e).substring(0,12),i=Array.from(new Set([...n,this.libp2p.peerId.toString()])),a=this.getConnectedAddrsByPeer(),c=Object.keys(a);this.log("findCluster key=%s fretCohort=%d connected=%d cohortPeers=%o",o,n.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(),publicKey:this.libp2p.peerId.publicKey?.raw??new Uint8Array};continue}let h=a[u]??[],d=this.parseMultiaddrs(h);l[u]={multiaddrs: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}};ft();ce();X();function wi(r){if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:E4}=Object.prototype,{propertyIsEnumerable:SA}=Object,xi=(r,e,t)=>{Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})},IA=void 0,v4={concatArrays:!1,ignoreUndefined:!1},Eu=r=>{let e=[];for(let t in r)E4.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let s of t)SA.call(r,s)&&e.push(s)}return e};function vi(r){return Array.isArray(r)?_A(r):wi(r)?AA(r):r}function _A(r){let e=r.slice(0,0);return Eu(r).forEach(t=>{xi(e,t,vi(r[t]))}),e}function AA(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return Eu(r).forEach(t=>{xi(e,t,vi(r[t]))}),e}var S4=(r,e,t,s)=>(t.forEach(n=>{typeof e[n]>"u"&&s.ignoreUndefined||(n in r&&r[n]!==Object.getPrototypeOf(r)?xi(r,n,G0(r[n],e[n],s)):xi(r,n,vi(e[n])))}),r),CA=(r,e,t)=>{let s=r.slice(0,0),n=0;return[r,e].forEach(o=>{let i=[];for(let a=0;a<o.length;a++)E4.call(o,a)&&(i.push(String(a)),o===r?xi(s,n++,o[a]):xi(s,n++,vi(o[a])));s=S4(s,o,Eu(o).filter(a=>!i.includes(a)),t)}),s};function G0(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?CA(r,e,t):!wi(e)||!wi(r)?vi(e):S4(r,e,Eu(e),t)}function Su(...r){let e=G0(vi(v4),this!==IA&&this||{},v4),t={_:{}};for(let s of r)if(s!==void 0){if(!wi(s))throw new TypeError("`"+s+"` is not an Option Object");t=G0(t,{_:s},e)}return t._}var We=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var _4=re("dns/promises");function Iu(r){let e=[Et.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}Se();var V0=60;function _u(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:Et[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Et[e.type],TTL:e.TTL??e.ttl??V0,data:e.data instanceof Uint8Array?K(e.data):e.data}))}}var TA=async(r,e={})=>{let t=new _4.Resolver,s=()=>{t.cancel()},n=Iu(e.types);try{e.signal?.addEventListener("abort",s);let o=await Promise.all(n.map(async i=>{if(i===Et.A)return Au(r,i,await t.resolve4(r));if(i===Et.CNAME)return Au(r,i,await t.resolveCname(r));if(i===Et.TXT)return Au(r,i,await t.resolveTxt(r));if(i===Et.AAAA)return Au(r,i,await t.resolve6(r));throw new TypeError("Unsupported DNS record type")}));return _u({Question:n.map(i=>({name:r,type:i})),Answer:o.flat()})}finally{e.signal?.removeEventListener("abort",s)}};function A4(){return[TA]}function I4(r,e,t){return{name:r,type:e,data:t}}function Au(r,e,t){return Array.isArray(t)||(t=[t]),t.map(s=>Array.isArray(s)?s.map(n=>I4(r,e,n)):I4(r,e,s)).flat()}var P4=we(T4(),1);var W0=class{lru;constructor(e){this.lru=(0,P4.default)(e)}get(e,t){let s=!0,n=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){s=!1;break}n.push(...i)}if(s)return _u({answers:n})}getAnswers(e,t){let s=`${e.toLowerCase()}-${t}`,n=this.lru.get(s);if(n!=null){let o=n.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Et[a.type]}));return o.length===0&&this.lru.remove(s),o}return[]}add(e,t){let s=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(s)??[];n.push({expires:Date.now()+(t.TTL??V0)*1e3,value:t}),this.lru.set(s,n)}remove(e,t){let s=`${e.toLowerCase()}-${t}`;this.lru.remove(s)}clear(){this.lru.clear()}};function k4(r){return new W0(r)}var PA=1e3,Cu=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=k4(e.cacheSize??PA),Object.entries(e.resolvers??{}).forEach(([t,s])=>{Array.isArray(s)||(s=[s]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=s}),this.resolvers["."]==null&&(this.resolvers["."]=A4())}async query(e,t={}){let s=Iu(t.types),n=t.cached!==!1?this.cache.get(e,s):void 0;if(n!=null)return t.onProgress?.(new We("dns:cache",n)),n;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:s});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new We("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${s} failed`)}};var Et;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Et||(Et={}));function D4(r={}){return new Cu(r)}var j0=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let s=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(s==null)return[e];let o=await this.getDNS(t).query(`_dnsaddr.${s}`,{signal:t?.signal,types:[Et.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(G(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=D4()),this.dns)}},zn=new j0;var kA={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:zn}},transportManager:{faultTolerance:_n.FATAL_ALL}};async function M4(r){let e=Su(kA,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new V("Private network is enforced, but no protector was provided");return e}ft();X();Ro();Vt();cl();var R4=we(re("node:tty"),1),Mu=we(re("node:util"),1);function DA(r,e){if(typeof r=="string")return MA(r);if(typeof r=="number")return RA(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var Tu=DA;function MA(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:s="ms"}=e.groups,n=parseFloat(t),o=s.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return n*315576e5;case"months":case"month":case"mo":return n*26298e5;case"weeks":case"week":case"w":return n*6048e5;case"days":case"day":case"d":return n*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return n*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return n*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return n*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function OA(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 LA(r){let e=Math.abs(r);return e>=315576e5?qn(r,e,315576e5,"year"):e>=26298e5?qn(r,e,26298e5,"month"):e>=6048e5?qn(r,e,6048e5,"week"):e>=864e5?qn(r,e,864e5,"day"):e>=36e5?qn(r,e,36e5,"hour"):e>=6e4?qn(r,e,6e4,"minute"):e>=1e3?qn(r,e,1e3,"second"):`${r} ms`}function RA(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?LA(r):OA(r)}function qn(r,e,t,s){let n=e>=t*1.5;return`${Math.round(r/t)} ${s}${n?"s":""}`}var ku=we(re("node:process"),1),L4=we(re("node:os"),1),Y0=we(re("node:tty"),1);function fr(r,e=globalThis.Deno?globalThis.Deno.args:ku.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",s=e.indexOf(t+r),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}var{env:Te}=ku.default,Pu;fr("no-color")||fr("no-colors")||fr("color=false")||fr("color=never")?Pu=0:(fr("color")||fr("colors")||fr("color=true")||fr("color=always"))&&(Pu=1);function NA(){if(!("FORCE_COLOR"in Te))return;if(Te.FORCE_COLOR==="true")return 1;if(Te.FORCE_COLOR==="false")return 0;if(Te.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(Te.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function BA(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function FA(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let s=NA();s!==void 0&&(Pu=s);let n=t?Pu:s;if(n===0)return 0;if(t){if(fr("color=16m")||fr("color=full")||fr("color=truecolor"))return 3;if(fr("color=256"))return 2}if("TF_BUILD"in Te&&"AGENT_NAME"in Te)return 1;if(r&&!e&&n===void 0)return 0;let o=n||0;if(Te.TERM==="dumb")return o;if(ku.default.platform==="win32"){let i=L4.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in Te)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in Te)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in Te)||Te.CI_NAME==="codeship"?1:o;if("TEAMCITY_VERSION"in Te)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Te.TEAMCITY_VERSION)?1:0;if(Te.COLORTERM==="truecolor"||Te.TERM==="xterm-kitty"||Te.TERM==="xterm-ghostty"||Te.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Te){let i=Number.parseInt((Te.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Te.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Te.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Te.TERM)||"COLORTERM"in Te?1:o}function O4(r,e={}){let t=FA(r,{streamIsTTY:r&&r.isTTY,...e});return BA(t)}var UA={stdout:O4({isTTY:Y0.default.isatty(1)}),stderr:O4({isTTY:Y0.default.isatty(2)})},Du=UA;function X0(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=i,t.humanize=Tu,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let h=0;for(let d=0;d<u.length;d++)h=(h<<5)-h+u.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(u){let h,d=null,f,p;function m(...g){if(!m.enabled)return;let y=m,w=Number(new Date),b=w-(h||w);y.diff=b,y.prev=h,y.curr=w,h=w,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,(P,T)=>{if(P==="%%")return"%";x++;let D=t.formatters[T];if(typeof D=="function"){let v=g[x];P=D.call(y,v),g.splice(x,1),x--}return P}),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=s,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(u)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function s(u,h){let d=t(this.namespace+(typeof h>"u"?":":h)+u);return d.log=this.log,d}function n(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let h,d=(typeof u=="string"?u:"").split(/[\s,]+/),f=d.length;for(h=0;h<f;h++)d[h]&&(u=d[h].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(h=>"-"+h)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let h,d;for(h=0,d=t.skips.length;h<d;h++)if(t.skips[h].test(u))return!1;for(h=0,d=t.names.length;h<d;h++)if(t.names[h].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 N4=[6,2,3,4,5,1];Du.stderr!==!1&&(Du.stderr??Du).level>=2&&(N4=[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 Ei=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,o)=>o.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function KA(){return"colors"in Ei?!!Ei.colors:R4.default.isatty(process.stderr.fd)}function HA(r){let{namespace:e,useColors:t}=this;if(t===!0){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),o=` ${n};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
4
+ `+o),r.push(n+"m+"+Su.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=HA()+e+" "+r[0]}function HA(){return ht.inspectOpts.hideDate?"":new Date().toISOString()+" "}function zA(...r){return process.stderr.write(Eu.formatWithOptions(ht.inspectOpts,...r)+`
5
+ `)}function qA(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function $A(){return process.env.DEBUG}function GA(r){r.inspectOpts={};let e=Object.keys(ht.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=ht.inspectOpts[e[t]]}Su.exports=N0()(ht);var{formatters:yb}=Su.exports;yb.o=function(r){return this.inspectOpts.colors=this.useColors,Eu.inspect(r,this.inspectOpts).split(`
6
+ `).map(e=>e.trim()).join(" ")};yb.O=function(r){return this.inspectOpts.colors=this.useColors,Eu.inspect(r,this.inspectOpts)}});var K0=We(($H,U0)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?U0.exports=hb():U0.exports=bb()});var w4=We((QG,b4)=>{b4.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),s=Object.create(null);function n(o,i){t[o]=i,e++,e>=r&&(e=0,s=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||s[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),s[o]!==void 0&&(s[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=s[o])!==void 0)return n(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:n(o,i)},clear:function(){t=Object.create(null),s=Object.create(null)}}}});var tw=We(Lc=>{(function(){var r,e,t,s,n,o,i,a;a=function(c){var l,u,h,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,d=c&255,[l,u,h,d].join(".")},i=function(c){var l,u,h,d,f,p;for(l=[],h=d=0;d<=3&&c.length!==0;h=++d){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),f=p[0],u=p[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)},s=t("0"),o=t("a"),n=t("A"),e=function(c){var l,u,h,d,f;for(d=0,l=10,u="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,u="7")),f=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)d=d*l+(t(c[h])-s)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")d=d*l+(10+t(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")d=d*l+(10+t(c[h])-n)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");h++}if(h===f)throw new Error("empty octet");return[d,h]},r=(function(){function c(l,u){var h,d,f,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw h=m,new Error("Invalid mask: "+u)}for(d=f=32;f>=0;d=--f)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;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 h=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,h,d;for(d=i(this.first),h=i(this.last),u=0;d<=h;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),Lc.ip2long=i,Lc.long2ip=a,Lc.Netmask=r}).call(Lc)});var kw=We((vQ,Pw)=>{function Er(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Pw.exports=Er;Er.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Er.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Er.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var s=this;return this._timer=setTimeout(function(){s._attempts++,s._operationTimeoutCb&&(s._timeout=setTimeout(function(){s._operationTimeoutCb(s._attempts)},s._operationTimeout),s._options.unref&&s._timeout.unref()),s._fn(s._attempts)},t),this._options.unref&&this._timer.unref(),!0};Er.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Er.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Er.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Er.prototype.start=Er.prototype.try;Er.prototype.errors=function(){return this._errors};Er.prototype.attempts=function(){return this._attempts};Er.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,s=0;s<this._errors.length;s++){var n=this._errors[s],o=n.message,i=(r[o]||0)+1;r[o]=i,i>=t&&(e=n,t=i)}return e}});var Dw=We(Io=>{var I7=kw();Io.operation=function(r){var e=Io.timeouts(r);return new I7(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Io.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var s=[],n=0;n<e.retries;n++)s.push(this.createTimeout(n,e));return r&&r.forever&&!s.length&&s.push(this.createTimeout(n,e)),s.sort(function(o,i){return o-i}),s};Io.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,s=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return s=Math.min(s,e.maxTimeout),s};Io.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var s in r)typeof r[s]=="function"&&t.push(s)}for(var n=0;n<t.length;n++){var o=t[n],i=r[o];r[o]=function(c){var l=Io.operation(e),u=Array.prototype.slice.call(arguments,1),h=u.pop();u.push(function(d){l.retry(d)||(d&&(arguments[0]=l.mainError()),h.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,i),r[o].options=e}}});var Ow=We((SQ,Mw)=>{Mw.exports=Dw()});var Km=We(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.TAG_LENGTH=as.DATA_CHUNK_LENGTH=as.NONCE_LENGTH=as.KEY_LENGTH=void 0;as.KEY_LENGTH=32;as.NONCE_LENGTH=12;as.DATA_CHUNK_LENGTH=65536;as.TAG_LENGTH=16});var ix=We(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});_d.ChaCha20Poly1305=void 0;var Ge=Km(),Hm=class{constructor(e){this.ctx=e;let t=e.cpKey.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,Ge.KEY_LENGTH);let s=e.cpNonce.value;this.wasmNonceArr=new Uint8Array(e.memory.buffer,s,Ge.NONCE_LENGTH);let n=e.cpAssociatedData.value;this.wasmAdArr=new Uint8Array(e.memory.buffer,n,Ge.KEY_LENGTH);let o=e.cpInput.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,o,Ge.DATA_CHUNK_LENGTH);let i=e.chacha20Output.value;this.wasmChacha20OutputArr=new Uint8Array(e.memory.buffer,i,Ge.DATA_CHUNK_LENGTH);let a=e.poly1305Output.value;this.wasmPoly1305OutputArr=new Uint8Array(e.memory.buffer,a,Ge.TAG_LENGTH);let c=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,c,64)}seal(e,t,s,n,o){this.init(e,t,n);let i=s.length+Ge.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=n?.length??0;return this.sealUpdate(s,c,a),a.set(this.wasmPoly1305OutputArr,s.length),a}open(e,t,s,n,o){this.init(e,t,n);let i=s.subarray(0,s.length-Ge.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=n?.length??0;this.openUpdate(i,c,a);let l=s.subarray(s.length-Ge.TAG_LENGTH,s.length);return this.isSameTag(l)?a:null}init(e,t,s=new Uint8Array(0)){if(e.length!=Ge.KEY_LENGTH)throw Error(`Invalid chacha20poly1305 key length ${e.length}, expect ${Ge.KEY_LENGTH}`);if(s.length>Ge.KEY_LENGTH)throw Error(`Invalid ad length ${s.length}, expect <= ${Ge.KEY_LENGTH}`);if(t.length!==Ge.NONCE_LENGTH)throw Error(`Invalid nonce length ${t.length}, expect ${Ge.NONCE_LENGTH}`);this.wasmKeyArr.set(e),this.wasmNonceArr.set(t),this.wasmAdArr.set(s)}openUpdate(e,t,s){this.commonUpdate(e,this.ctx.openUpdate,t,s)}sealUpdate(e,t,s){this.commonUpdate(e,this.ctx.sealUpdate,t,s)}commonUpdate(e,t,s,n){let o=e.length;if(e.length<=Ge.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),t(!0,!0,o,o,s),n.set(o===Ge.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,o));return}for(let i=0;i<o;i+=Ge.DATA_CHUNK_LENGTH){let a=Math.min(o,i+Ge.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(i,a));let c=i===0,l=i+Ge.DATA_CHUNK_LENGTH>=o;t(c,l,a-i,o,s),n.set(a-i===Ge.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,a-i),i)}}isSameTag(e){let t=!0;for(let s=0;s<Ge.TAG_LENGTH;s++)if(this.wasmPoly1305OutputArr[s]!==e[s]){t=!1;break}return t}};_d.ChaCha20Poly1305=Hm});var ax=We(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});Ad.Poly1305=void 0;var Ls=Km(),zm=class{constructor(e){this.ctx=e;let t=e.poly1305Key.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,Ls.KEY_LENGTH);let s=e.poly1305Input.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,s,Ls.DATA_CHUNK_LENGTH);let n=e.poly1305Output.value;this.wasmOutputArr=new Uint8Array(e.memory.buffer,n,Ls.TAG_LENGTH);let o=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,o,64)}init(e){if(e.length!=Ls.KEY_LENGTH)throw Error(`Invalid poly1305 key length ${e.length}, expect ${Ls.KEY_LENGTH}`);this.wasmKeyArr.set(e),this.ctx.poly1305Init()}update(e){if(e.length<=Ls.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),this.ctx.poly1305Update(e.length);return}for(let t=0;t<e.length;t+=Ls.DATA_CHUNK_LENGTH){let s=Math.min(e.length,t+Ls.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(t,s)),this.ctx.poly1305Update(s-t)}}digest(){this.ctx.poly1305Digest();let e=new Uint8Array(Ls.TAG_LENGTH);return e.set(this.wasmOutputArr),e}};Ad.Poly1305=zm});var cx=We(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});Td.wasmCode=void 0;Td.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 qm=We(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});Cd.newInstance=void 0;var tP=cx(),rP=new WebAssembly.Module(tP.wasmCode),sP={env:{abort:function(r,e,t,s){throw Error(`abort: ${r}:${e}:${t}:${s}`)}}};function nP(){return new WebAssembly.Instance(rP,sP).exports}Cd.newInstance=nP});var hx=We(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});Pd.chacha20StreamXOR=void 0;var oP=qm(),cs=oP.newInstance(),iP=cs.chacha20Input.value,aP=cs.chacha20Output.value,cP=cs.chacha20Key.value,lP=cs.chacha20Counter.value,{CHACHA20_INPUT_LENGTH:Gi,KEY_LENGTH:$m,CHACHA20_COUNTER_LENGTH:ux}=cs,uP=new Uint8Array(cs.memory.buffer,iP,Gi),lx=new Uint8Array(cs.memory.buffer,aP,Gi),hP=new Uint8Array(cs.memory.buffer,cP,$m),dP=new Uint8Array(cs.memory.buffer,lP,ux);function fP(r,e,t){if(r.length!=$m)throw new Error("ChaCha: key size must be 32 bytes, expected "+$m+" got "+r.length);if(e.length!=ux)throw new Error("ChaCha nonce with counter must be 16 bytes");hP.set(r),dP.set(e);let s=new Uint8Array(t.length),n=Math.floor(t.length/Gi);for(let o=0;o<=n;o++){let i=o*Gi,a=Math.min((o+1)*Gi,t.length);uP.set(n===0?t:t.subarray(i,a));let c=a-i,l=cs.chacha20StreamXORUpdate(c);s.set(l===Gi?lx:lx.subarray(0,l),i)}return s}Pd.chacha20StreamXOR=fP});var dx=We(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.newInstance=ls.chacha20StreamXOR=ls.Poly1305=ls.ChaCha20Poly1305=void 0;var pP=ix();Object.defineProperty(ls,"ChaCha20Poly1305",{enumerable:!0,get:function(){return pP.ChaCha20Poly1305}});var mP=ax();Object.defineProperty(ls,"Poly1305",{enumerable:!0,get:function(){return mP.Poly1305}});var gP=hx();Object.defineProperty(ls,"chacha20StreamXOR",{enumerable:!0,get:function(){return gP.chacha20StreamXOR}});var yP=qm();Object.defineProperty(ls,"newInstance",{enumerable:!0,get:function(){return yP.newInstance}})});var wx=We((_re,bx)=>{function CP(){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)}bx.exports=CP});var IE=We((fae,SE)=>{"use strict";function Fe(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))}Fe.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var s=this.size();if(!(t>=s||t<-s))return t<0&&(t+=s),t=this._head+t&this._capacityMask,this._list[t]}};Fe.prototype.get=function(e){return this.peekAt(e)};Fe.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};Fe.prototype.peekFront=function(){return this.peek()};Fe.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(Fe.prototype,"length",{get:function(){return this.size()}});Fe.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Fe.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)};Fe.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}};Fe.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)};Fe.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var s=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),s}};Fe.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var s=this.size(),n=this._list.length;if(!(t>=s||t<-s)){t<0&&(t+=s),t=this._head+t&this._capacityMask;var o=this._list[t],i;if(e<s/2){for(i=e;i>0;i--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(i=s-1-e;i>0;i--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return o}}};Fe.prototype.remove=function(e,t){var s=e,n,o=t;if(s===(s|0)&&this._head!==this._tail){var i=this.size(),a=this._list.length;if(!(s>=i||s<-i||t<1)){if(s<0&&(s+=i),t===1||!t)return n=new Array(1),n[0]=this.removeOne(s),n;if(s===0&&s+t>=i)return n=this.toArray(),this.clear(),n;s+t>i&&(t=i-s);var c;for(n=new Array(t),c=0;c<t;c++)n[c]=this._list[this._head+s+c&this._capacityMask];if(s=this._head+s&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[s=s+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[s=s+1+a&this._capacityMask]=void 0;return n}if(s<i/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[s=s-1+a&this._capacityMask]);for(s=this._head-1+a&this._capacityMask;o>0;)this._list[s=s-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=s)}else{for(this._tail=s,s=s+t+a&this._capacityMask,c=i-(t+e);c>0;c--)this.push(this._list[s++]);for(s=this._tail;o>0;)this._list[s=s+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};Fe.prototype.splice=function(e,t){var s=e;if(s===(s|0)){var n=this.size();if(s<0&&(s+=n),!(s>n))if(arguments.length>2){var o,i,a,c=arguments.length,l=this._list.length,u=2;if(!n||s<n/2){for(i=new Array(s),o=0;o<s;o++)i[o]=this._list[this._head+o&this._capacityMask];for(t===0?(a=[],s>0&&(this._head=this._head+s+l&this._capacityMask)):(a=this.remove(s,t),this._head=this._head+s+l&this._capacityMask);c>u;)this.unshift(arguments[--c]);for(o=s;o>0;o--)this.unshift(i[o-1])}else{i=new Array(n-(s+t));var h=i.length;for(o=0;o<h;o++)i[o]=this._list[this._head+s+t+o&this._capacityMask];for(t===0?(a=[],s!=n&&(this._tail=this._head+s+l&this._capacityMask)):(a=this.remove(s,t),this._tail=this._tail-h+l&this._capacityMask);u<c;)this.push(arguments[u++]);for(o=0;o<h;o++)this.push(i[o])}return a}else return this.remove(s,t)}};Fe.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};Fe.prototype.isEmpty=function(){return this._head===this._tail};Fe.prototype.toArray=function(){return this._copyArray(!1)};Fe.prototype._fromArray=function(e){var t=e.length,s=this._nextPowerOf2(t);this._list=new Array(s),this._capacityMask=s-1,this._tail=t;for(var n=0;n<t;n++)this._list[n]=e[n]};Fe.prototype._copyArray=function(e,t){var s=this._list,n=s.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<n;c++)i[a++]=s[c];for(c=0;c<this._tail;c++)i[a++]=s[c]}else for(c=this._head;c<this._tail;c++)i[a++]=s[c];return i};Fe.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};Fe.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};Fe.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),s=1<<t+1;return Math.max(s,4)};SE.exports=Fe});var XD={};_e(XD,{ArachnodeFretAdapter:()=>vc,BlockStorage:()=>Ei,ClusterClient:()=>Hn,ClusterCoordinator:()=>nc,ClusterMember:()=>Iu,ClusterService:()=>_u,CoordinatorRepo:()=>Au,FileRawStorage:()=>oc,Libp2pKeyPeerNetwork:()=>Ec,MemoryRawStorage:()=>ic,NetworkManagerService:()=>j1,ProtocolClient:()=>gs,RepoClient:()=>q0,RepoService:()=>Cu,RestorationCoordinator:()=>bc,RingSelector:()=>wc,SYNC_PROTOCOL_PREFIX:()=>u4,SYNC_PROTOCOL_VERSION:()=>h4,StorageMonitor:()=>xc,StorageRepo:()=>ac,SyncClient:()=>yc,SyncService:()=>Gu,asyncIteratorToArray:()=>va,buildKnownPeers:()=>WD,buildSyncProtocol:()=>gc,clusterMember:()=>H0,clusterService:()=>z0,computeResponsibility:()=>VD,coordinatorRepo:()=>$0,createLibp2pNode:()=>GD,first:()=>af,getNetworkManager:()=>YD,lessThanLex:()=>mS,networkManagerService:()=>a3,reduce:()=>FS,repoService:()=>G0,sortPeersByDistance:()=>gS,syncService:()=>T2,xorDistanceBytes:()=>pS});function me(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var bl=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}},qo=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new bl(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 bl(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 X1=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function gt(r={}){return SS(t=>{let s=t.shift();if(s==null)return{done:!0};if(s.error!=null)throw s.error;return{done:s.done===!0,value:s.value}},r)}function SS(r,e){e=e??{};let t=e.onEnd,s=new qo,n,o,i,a=me(),c=async()=>{try{return s.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{o=b=>{o=null,s.push(b);try{g(r(s))}catch(w){y(w)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=me()})}},l=g=>o!=null?o(g):(s.push(g),n),u=g=>(s=new qo,o!=null?o({error:g}):(s.push({error:g}),n)),h=g=>{if(i)return n;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})},d=g=>i?n:(i=!0,g!=null?u(g):l({done:!0})),f=()=>(s=new qo,d(),{done:!0}),p=g=>(d(g),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:f,throw:p,push:h,end:d,get readableLength(){return s.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),s.isEmpty())return;let b,w;y!=null&&(b=new Promise((x,E)=>{w=()=>{E(new X1)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,b])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},t==null)return n;let m=n;return n={[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:h,end(g){return m.end(g),t!=null&&(t(g),t=void 0),n},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},n}var wl=class extends Error{type;code;constructor(e,t,s){super(e??"The operation was aborted"),this.type="aborted",this.name=s??"AbortError",this.code=t??"ABORT_ERR"}};async function Me(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new wl(t?.errorMessage,t?.errorCode,t?.errorName));let s,n=new wl(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n)},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var Z1=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=me(),this.haveNext=me()}[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=me(),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=me(),await Me(this.readNext.promise,t?.signal,t)}};function xl(){return new Z1}function IS(r){return r[Symbol.asyncIterator]!=null}async function _S(r,e,t){try{await Promise.all(r.map(async s=>{for await(let n of s)await e.push(n,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(s){await e.end(s,{signal:t}).catch(()=>{})}}async function*AS(r){let e=new AbortController,t=xl();_S(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*TS(r){for(let e of r)yield*e}function CS(...r){let e=[];for(let t of r)IS(t)||e.push(t);return e.length===r.length?TS(e):AS(r)}var En=CS;function Qe(r,...e){if(r==null)throw new Error("Empty pipeline");if(Q1(r)){let s=r;r=()=>s.source}else if(d3(r)||h3(r)){let s=r;r=()=>s}let t=[r,...e];if(t.length>1&&Q1(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let s=1;s<t.length-1;s++)Q1(t[s])&&(t[s]=kS(t[s]));return PS(...t)}var PS=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},h3=r=>r?.[Symbol.asyncIterator]!=null,d3=r=>r?.[Symbol.iterator]!=null,Q1=r=>r==null?!1:r.sink!=null&&r.source!=null,kS=r=>e=>{let t=r.sink(e);if(t?.then!=null){let s=gt({objectMode:!0});t.then(()=>{s.end()},i=>{s.end(i)});let n,o=r.source;if(h3(o))n=async function*(){yield*o,s.end()};else if(d3(o))n=function*(){yield*o,s.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return En(s,n())}return r.source};Ar();at();rt();var El=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Go=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Sl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},xa=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Il(r){return r[Symbol.asyncIterator]!=null}function g3(r,e){if(r.byteLength>e)throw new Go("Message length too long")}var Al=r=>{let e=Ue(r),t=tt(e);return hr(r,t),Al.bytes=e,t};Al.bytes=0;function dr(r,e){e=e??{};let t=e.lengthEncoder??Al,s=e?.maxDataLength??4194304;function*n(o){g3(o,s);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Il(r)?(async function*(){for await(let o of r)yield*n(o)})():(function*(){for(let o of r)yield*n(o)})()}dr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Al,s=e?.maxDataLength??4194304;return g3(r,s),new W(t(r.byteLength),r)};Ar();at();var Sn;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Sn||(Sn={}));var of=r=>{let e=ms(r);return of.bytes=Ue(e),e};of.bytes=0;function Zt(r,e){let t=new W,s=Sn.LENGTH,n=-1,o=e?.lengthDecoder??of,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(s===Sn.LENGTH)try{if(n=o(t),n<0)throw new El("Invalid message length");if(n>a)throw new Go("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(n),s=Sn.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Sl("Message length length too long");break}throw l}if(s===Sn.DATA){if(t.byteLength<n)break;let l=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(l),yield l,s=Sn.LENGTH}}}return Il(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new xa("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new xa("Unexpected end of input")})()}Zt.fromReader=(r,e)=>{let t=1,s=(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 Zt(s,{...e??{},onLength:o=>{t=o}})};async function af(r,e=()=>{throw new Error("No items found")},t){let s=new AbortController,n=typeof t=="number"?setTimeout(()=>s.abort(),t):void 0;try{for await(let o of r(s.signal))return o;return e()}finally{n!==void 0&&clearTimeout(n),s.abort()}}async function va(r){let e=[];for await(let t of r)e.push(t);return e}function FS(r,e,t){let s=t,n=0;for(let o of r)s=e(s,o,n),++n;return s}var gs=class{peerId;peerNetwork;constructor(e,t){this.peerId=e,this.peerNetwork=t}async processMessage(e,t,s){let n=await this.peerNetwork.connect(this.peerId,t,{signal:s?.signal});try{let o=Qe(n.source,Zt,async function*(a){for await(let c of a){let l=new TextDecoder().decode(c.subarray());yield JSON.parse(l)}}),i=gt();return Qe(i,dr,n.sink),i.push(new TextEncoder().encode(JSON.stringify(e))),i.end(),await af(()=>o,()=>{throw new Error("No response received")})}finally{n.close()}}};ce();var Hn=class r extends gs{protocolPrefix;constructor(e,t,s){super(e,t),this.protocolPrefix=s}static create(e,t,s){return new r(e,t,s)}async update(e,t=0){let s={operation:"update",record:e},n=(this.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",o;try{o=await this.processMessage(s,n)}catch(i){if(n!=="/db-p2p/cluster/1.0.0")o=await this.processMessage(s,"/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=G(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 s=e?.message,n;if(s?.commit?.tailId)n=s.commit.tailId;else if(s?.pend?.transforms){let o=Object.keys(s.pend.transforms);o.length>0&&(n=o[0])}if(n){let o=new TextEncoder().encode(n),i=this.peerNetwork;typeof i?.recordCoordinator=="function"&&i.recordCoordinator(o,t)}}};var i0=new Map;function es(r,e){if(i0.has(r))throw new Error(`Block type ${r} (${e}) already registered (${i0.get(r)})`);return i0.set(r,e),r}function gu(r,[e,t,s,n]){Array.isArray(n)?r[e].splice(t,s,...structuredClone(n)):r[e]=structuredClone(n)}function j8(r,e){for(let t of e)gu(r,t)}function zn(r){if(!r)return[];let e=Object.keys(r.inserts??{}),t=Object.keys(r.updates??{}),s=r.deletes??[];return[...new Set([...e,...t,...s])]}function a0(){return{inserts:{},updates:{},deletes:[]}}function yu(r,e){return{...e in r.inserts?{insert:r.inserts[e]}:{},...e in r.updates?{updates:r.updates[e]}:{},...e in r.deletes?{delete:!0}:{}}}function c0(r,e){return{inserts:r.insert?{[e]:r.insert}:{},updates:r.updates?{[e]:r.updates}:{},deletes:r.delete?[e]:[]}}function Qa(r,e){if(e.insert&&(r=e.insert),r&&e.updates&&j8(r,e.updates),!e.delete)return r}function l0(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 Wt(r,e){return e??r}var Y8=es("TL","TreeLeaf"),X8=es("TB","TreeBranch"),Z8=Wt("entries"),Q8=Wt("partitions"),J8=Wt("nodes");var r_=Wt("entries"),s_=Wt("priorId"),n_=Wt("nextId"),o_=es("CHD","ChainDataBlock"),i_=Wt("headId"),a_=Wt("tailId"),c_=es("CHH","ChainHeaderBlock");var p0={};_e(p0,{base58btc:()=>ts,base58flickr:()=>g_});var tF=new Uint8Array(0);function L5(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 N5(r){return new TextEncoder().encode(r)}function B5(r){return new TextDecoder().decode(r)}function u_(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var n=0;n<r.length;n++){var o=r.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,b=p.length;y!==b&&p[y]===0;)y++,m++;for(var w=(b-y)*u+1>>>0,x=new Uint8Array(w);y!==b;){for(var E=p[y],P=0,C=w-1;(E!==0||P<g)&&C!==-1;C--,P++)E+=256*x[C]>>>0,x[C]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");g=P,y++}for(var D=w-g;D!==w&&x[D]===0;)D++;for(var v=c.repeat(m);D<w;++D)v+=r.charAt(x[D]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var b=(p.length-m)*l+1>>>0,w=new Uint8Array(b);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var E=0,P=b-1;(x!==0||E<y)&&P!==-1;P--,E++)x+=a*w[P]>>>0,w[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=E,m++}if(p[m]!==" "){for(var C=b-y;C!==b&&w[C]===0;)C++;for(var D=new Uint8Array(g+(b-C)),v=g;C!==b;)D[v++]=w[C++];return D}}}function f(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var h_=u_,d_=h_,U5=d_;var u0=class{name;prefix;baseEncode;constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}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,s){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=s}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 K5(this,e)}},d0=class{decoders;constructor(e){this.decoders=e}or(e){return K5(this,e)}decode(e){let t=e[0],s=this.decoders[t];if(s!=null)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function K5(r,e){return new d0({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var f0=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new u0(e,t,s),this.decoder=new h0(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function fi({name:r,prefix:e,encode:t,decode:s}){return new f0(r,e,t,s)}function nn({name:r,prefix:e,alphabet:t}){let{encode:s,decode:n}=U5(t,r);return fi({prefix:e,name:r,encode:s,decode:o=>mr(n(o))})}function f_(r,e,t,s){let n=r.length;for(;r[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,c=0;for(let l=0;l<n;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${s} 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 p_(r,e,t){let s=e[e.length-1]==="=",n=(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[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),s)for(;(o.length*t&7)!==0;)o+="=";return o}function m_(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:s}){let n=m_(s);return fi({prefix:e,name:r,encode(o){return p_(o,s,t)},decode(o){return f_(o,n,t,r)}})}var ts=nn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),g_=nn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var m0={};_e(m0,{base32:()=>pi,base32hex:()=>x_,base32hexpad:()=>E_,base32hexpadupper:()=>S_,base32hexupper:()=>v_,base32pad:()=>b_,base32padupper:()=>w_,base32upper:()=>y_,base32z:()=>I_});var pi=ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),y_=ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),b_=ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),w_=ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),x_=ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),v_=ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),E_=ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),S_=ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),I_=ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var g0={};_e(g0,{base36:()=>Ja,base36upper:()=>__});var Ja=nn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),__=nn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var A_=q5,H5=128,T_=127,C_=~T_,P_=Math.pow(2,31);function q5(r,e,t){e=e||[],t=t||0;for(var s=t;r>=P_;)e[t++]=r&255|H5,r/=128;for(;r&C_;)e[t++]=r&255|H5,r>>>=7;return e[t]=r|0,q5.bytes=t-s+1,e}var k_=y0,D_=128,z5=127;function y0(r,s){var t=0,s=s||0,n=0,o=s,i,a=r.length;do{if(o>=a)throw y0.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=n<28?(i&z5)<<n:(i&z5)*Math.pow(2,n),n+=7}while(i>=D_);return y0.bytes=o-s,t}var M_=Math.pow(2,7),O_=Math.pow(2,14),R_=Math.pow(2,21),L_=Math.pow(2,28),N_=Math.pow(2,35),B_=Math.pow(2,42),F_=Math.pow(2,49),U_=Math.pow(2,56),K_=Math.pow(2,63),H_=function(r){return r<M_?1:r<O_?2:r<R_?3:r<L_?4:r<N_?5:r<B_?6:r<F_?7:r<U_?8:r<K_?9:10},z_={encode:A_,decode:k_,encodingLength:H_},q_=z_,ec=q_;function tc(r,e=0){return[ec.decode(r,e),ec.decode.bytes]}function mi(r,e,t=0){return ec.encode(r,e,t),e}function gi(r){return ec.encodingLength(r)}function bi(r,e){let t=e.byteLength,s=gi(r),n=s+gi(t),o=new Uint8Array(n+t);return mi(r,o,0),mi(t,o,s),o.set(e,n),new yi(r,t,e,o)}function $5(r){let e=mr(r),[t,s]=tc(e),[n,o]=tc(e.subarray(s)),i=e.subarray(s+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new yi(t,n,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&&L5(r.bytes,t.bytes)}}var yi=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}};function V5(r,e){let{bytes:t,version:s}=r;switch(s){case 0:return G_(t,b0(r),e??ts.encoder);default:return V_(t,b0(r),e??pi.encoder)}}var W5=new WeakMap;function b0(r){let e=W5.get(r);if(e==null){let t=new Map;return W5.set(r,t),t}return e}var wu=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=n,this["/"]=n}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!==sc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==W_)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,s=bi(e,t);return r.createV1(this.code,s)}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 s=t;return s!=null&&e.code===s.code&&e.version===s.version&&G5(e.multihash,s.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:s,code:n,multihash:o,bytes:i}=t;return new r(s,n,o,i??j5(s,n,o.bytes))}else if(t[j_]===!0){let{version:s,multihash:n,code:o}=t,i=$5(n);return r.create(s,o,i)}else return null}static create(e,t,s){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(s.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==sc)throw new Error(`Version 0 CID must use dag-pb (code: ${sc}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=j5(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,sc,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,s]=r.decodeFirst(e);if(s.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),s=t.size-t.multihashSize,n=mr(e.subarray(s,s+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new yi(t.multihashCode,t.digestSize,o,n);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,s=()=>{let[h,d]=tc(e.subarray(t));return t+=d,h},n=s(),o=sc;if(n===18?(n=0,t=0):o=s(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=s(),c=s(),l=t+c,u=l-i;return{version:n,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[s,n]=$_(e,t),o=r.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return b0(o).set(s,e),o}};function $_(r,e){switch(r[0]){case"Q":{let t=e??ts;return[ts.prefix,t.decode(`${ts.prefix}${r}`)]}case ts.prefix:{let t=e??ts;return[ts.prefix,t.decode(r)]}case pi.prefix:{let t=e??pi;return[pi.prefix,t.decode(r)]}case Ja.prefix:{let t=e??Ja;return[Ja.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 G_(r,e,t){let{prefix:s}=t;if(s!==ts.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(s);if(n==null){let o=t.encode(r).slice(1);return e.set(s,o),o}else return n}function V_(r,e,t){let{prefix:s}=t,n=e.get(s);if(n==null){let o=t.encode(r);return e.set(s,o),o}else return n}var sc=112,W_=18;function j5(r,e,t){let s=gi(r),n=s+gi(e),o=new Uint8Array(n+t.byteLength);return mi(r,o,0),mi(e,o,s),o.set(t,n),o}var j_=Symbol.for("@ipld/js-cid/CID");var w0={};_e(w0,{identity:()=>Z_});var Y5=0,Y_="identity",X5=mr;function X_(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 bi(Y5,X5(r))}var Z_={code:Y5,name:Y_,encode:X5,digest:X_};var Q5=oe("node:buffer");function Z5(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function J5(r=0){return Z5(Q5.Buffer.allocUnsafe(r))}var x0={};_e(x0,{base10:()=>Q_});var Q_=nn({prefix:"9",name:"base10",alphabet:"0123456789"});var v0={};_e(v0,{base16:()=>J_,base16upper:()=>eA});var J_=ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),eA=ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var E0={};_e(E0,{base2:()=>tA});var tA=ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var S0={};_e(S0,{base256emoji:()=>iA});var eb=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}"),rA=eb.reduce((r,e,t)=>(r[t]=e,r),[]),sA=eb.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);function nA(r){return r.reduce((e,t)=>(e+=rA[t],e),"")}function oA(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=sA[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var iA=fi({prefix:"\u{1F680}",name:"base256emoji",encode:nA,decode:oA});var I0={};_e(I0,{base64:()=>aA,base64pad:()=>cA,base64url:()=>lA,base64urlpad:()=>uA});var aA=ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cA=ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),lA=ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),uA=ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var _0={};_e(_0,{base8:()=>hA});var hA=ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var A0={};_e(A0,{identity:()=>dA});var dA=fi({prefix:"\0",name:"identity",encode:r=>B5(r),decode:r=>N5(r)});var kF=new TextEncoder,DF=new TextDecoder;var D0={};_e(D0,{sha256:()=>k0,sha512:()=>gA});var P0=xe(oe("crypto"),1);var mA=20;function C0({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new T0(r,e,t,s,n)}var T0=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,o){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??mA,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 s=this.encode(e);return s instanceof Uint8Array?tb(s,this.code,t?.truncate):s.then(n=>tb(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function tb(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 bi(e,r)}var k0=C0({name:"sha2-256",code:18,encode:r=>mr(P0.default.createHash("sha256").update(r).digest())}),gA=C0({name:"sha2-512",code:19,encode:r=>mr(P0.default.createHash("sha512").update(r).digest())});var M0={...A0,...E0,..._0,...x0,...v0,...m0,...g0,...p0,...I0,...S0},$F={...D0,...w0};function nb(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var sb=nb("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),O0=nb("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=J5(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),jF={utf8:sb,"utf-8":sb,hex:M0.base16,latin1:O0,ascii:O0,binary:O0,...M0};var qn=class{static lockQueues=new Map;static async acquire(e){let t=this.lockQueues.get(e)??Promise.resolve(),s,n=new Promise(i=>{s=i});return this.lockQueues.set(e,n),await t,()=>{s(),this.lockQueues.get(e)===n&&this.lockQueues.delete(e)}}};var xA=es("DIH","DiaryHeaderBlock");var vA=es("TRE","TreeHeaderBlock"),EA=Wt("rootId");var GU=Wt("priorHash");R0();R0();var $n=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 L0(r,e){return r.reduce((t,s)=>{let n=e(s);return(t[n]??=[]).push(s),t},{})}ce();jr();Pe();var wb=xe(K0(),1),VA="optimystic:db-p2p";function yr(r){return(0,wb.default)(`${VA}:${r}`)}var De=yr("cluster-member"),It;(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"})(It||(It={}));function H0(r){return new Iu(r.storageRepo,r.peerNetwork,r.peerId,r.protocolPrefix,r.partitionDetector,r.fretService,r.validator)}var Iu=class{storageRepo;peerNetwork;peerId;protocolPrefix;partitionDetector;fretService;validator;activeTransactions=new Map;cleanupQueue=[];pendingUpdates=new Map;constructor(e,t,s,n,o,i,a){this.storageRepo=e,this.peerNetwork=t,this.peerId=s,this.protocolPrefix=n,this.partitionDetector=o,this.fretService=i,this.validator=a,setInterval(()=>this.queueExpiredTransactions(),6e4),setInterval(()=>this.processCleanupQueue(),1e3)}async update(e){let t=this.pendingUpdates.get(e.messageHash);t&&(De("cluster-member:concurrent-update-wait",{messageHash:e.messageHash}),await t);let s=this.processUpdate(e);this.pendingUpdates.set(e.messageHash,s);try{return await s}finally{setTimeout(()=>{this.pendingUpdates.delete(e.messageHash)},100)}}async processUpdate(e){let t=this.peerId.toString(),s=e.commits[t]?"commit":e.promises[t]?"promise":"initial";if(De("cluster-member:incoming",{messageHash:e.messageHash,phase:s,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 n=this.activeTransactions.get(e.messageHash),o=n?.record||e;n&&De("cluster-member:merge-start",{messageHash:e.messageHash,existingPromises:Object.keys(n.record.promises??{}),existingCommits:Object.keys(n.record.commits??{}),incomingPromises:Object.keys(e.promises??{}),incomingCommits:Object.keys(e.commits??{})}),n&&(o=await this.mergeRecords(n.record,e),De("cluster-member:merge-complete",{messageHash:e.messageHash,mergedPromises:Object.keys(o.promises??{}),mergedCommits:Object.keys(o.commits??{})}));let i=await this.getTransactionPhase(o);De("cluster-member:phase",{messageHash:e.messageHash,phase:i,promises:Object.keys(o.promises??{}),commits:Object.keys(o.commits??{})});let a=!0;switch(i){case It.OurPromiseNeeded:De("cluster-member:action-promise",{messageHash:e.messageHash}),o=await this.handlePromiseNeeded(o),De("cluster-member:action-promise-complete",{messageHash:e.messageHash,promises:Object.keys(o.promises??{})});break;case It.OurCommitNeeded:De("cluster-member:action-commit",{messageHash:e.messageHash}),o=await this.handleCommitNeeded(o),De("cluster-member:action-commit-complete",{messageHash:e.messageHash,commits:Object.keys(o.commits??{})}),a=!1;break;case It.Consensus:De("cluster-member:action-consensus",{messageHash:e.messageHash}),await this.handleConsensus(o),a=!1;break;case It.Rejected:De("cluster-member:action-rejected",{messageHash:e.messageHash}),await this.handleRejection(o),a=!1;break;case It.Propagating:De("cluster-member:phase-propagating",{messageHash:e.messageHash}),a=!1;break;case It.Promising:De("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}),De("cluster-member:state-persist",{messageHash:e.messageHash,storedPromises:Object.keys(o.promises??{}),storedCommits:Object.keys(o.commits??{})})}else De("cluster-member:state-clear",{messageHash:e.messageHash}),this.clearTransaction(e.messageHash);return De("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(De("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){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(e.messageHash+JSON.stringify(e.message)),s=await et.digest(t);return U(s.digest,"base64url")}async validateSignatures(e){let t=await this.computePromiseHash(e);for(let[n,o]of Object.entries(e.promises))if(!await this.verifySignature(n,t,o))throw new Error(`Invalid promise signature from ${n}`);let s=await this.computeCommitHash(e);for(let[n,o]of Object.entries(e.commits))if(!await this.verifySignature(n,s,o))throw new Error(`Invalid commit signature from ${n}`)}async computePromiseHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)),s=await et.digest(t);return U(s.digest,"base64url")}async computeCommitHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)+JSON.stringify(e.promises)),s=await et.digest(t);return U(s.digest,"base64url")}async verifySignature(e,t,s){return!0}async getTransactionPhase(e){let t=Object.keys(e.peers).length,s=Object.keys(e.promises).length,n=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 It.Rejected;if(!e.promises[o]&&!this.hasConflict(e))return It.OurPromiseNeeded;if(s<t)return It.Promising;if(s===t&&!e.commits[o])return It.OurCommitNeeded;let c=Object.values(e.commits).filter(l=>l.type==="approve");return this.hasMajority(c.length,t)?It.Consensus:It.Propagating}hasMajority(e,t){return e>t/2}async handlePromiseNeeded(e){let t=await this.validatePendOperations(e),s=t.valid?{type:"approve",signature:"approved"}:{type:"reject",signature:"rejected",rejectReason:t.reason};return t.valid||De("cluster-member:validation-rejected",{messageHash:e.messageHash,reason:t.reason}),{...e,promises:{...e.promises,[this.peerId.toString()]:s}}}async validatePendOperations(e){if(!this.validator)return{valid:!0};for(let t of e.message.operations)if("pend"in t){let s=t.pend;if(s.transaction&&s.operationsHash){let n=await this.validator.validate(s.transaction,s.operationsHash);if(!n.valid)return{valid:!1,reason:n.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){let t=this.activeTransactions.get(e.messageHash);if(!this.hasLocalCommit(t?.record??e))for(let s of e.message.operations)"get"in s?await this.storageRepo.get(s.get):"pend"in s?await this.storageRepo.pend(s.pend):"commit"in s?await this.storageRepo.commit(s.commit):"cancel"in s&&await this.storageRepo.cancel(s.cancel.actionRef)}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(),s=2e3;for(let[n,o]of Array.from(this.activeTransactions.entries()))if(n!==e.messageHash){if(t-o.lastUpdate>s){De("cluster-member:stale-cleanup",{messageHash:n,age:t-o.lastUpdate}),this.clearTransaction(n);continue}if(this.operationsConflict(o.record.message.operations,e.message.operations)){if(this.resolveRace(o.record,e)==="keep-existing")return De("cluster-member:race-keep-existing",{existing:n,incoming:e.messageHash}),!0;De("cluster-member:race-accept-incoming",{existing:n,incoming:e.messageHash}),this.clearTransaction(n);continue}}return!1}resolveRace(e,t){let s=Object.keys(e.promises).length,n=Object.keys(t.promises).length;return s>n?"keep-existing":n>s?"accept-incoming":e.messageHash>t.messageHash?"keep-existing":"accept-incoming"}operationsConflict(e,t){let s=this.getActionId(e),n=this.getActionId(t);if(s&&n&&s===n)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 De("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 s of e)"get"in s?s.get.blockIds.forEach(n=>t.add(n)):"pend"in s?zn(s.pend.transforms).forEach(n=>t.add(n)):"commit"in s?s.commit.blockIds.forEach(n=>t.add(n)):"cancel"in s&&s.cancel.actionRef.blockIds.forEach(n=>t.add(n));return Array.from(t)}async propagateIfNeeded(e){let t=[];for(let[s,n]of Object.entries(e.peers))if(s!==this.peerId.toString())try{let o=Hn.create(G(s),this.peerNetwork,this.protocolPrefix);t.push(o.update(e))}catch(o){console.error(`Failed to propagate to peer ${s}:`,o)}await Promise.allSettled(t)}async handleExpiration(e){let t=this.activeTransactions.get(e);if(t&&!t.record.promises[this.peerId.toString()]){let s={type:"reject",signature:"rejected",rejectReason:"Transaction expired"},n={...t.record,promises:{...t.record.promises,[this.peerId.toString()]:s}};this.activeTransactions.set(e,{...t,record:n}),await this.propagateIfNeeded(n)}}async resolveWithPeers(e){De("cluster-member:resolve-skipped",{messageHash:e,reason:"coordinator-handles-retry"})}queueExpiredTransactions(){let e=Date.now();for(let[t,s]of Array.from(this.activeTransactions.entries()))s.record.message.expiration&&s.record.message.expiration<e&&this.cleanupQueue.push(t)}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 s=await this.getTransactionPhase(t.record);s!==It.Consensus&&s!==It.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){De("cluster-member:clear-miss",{messageHash:e});return}t.promiseTimeout&&clearTimeout(t.promiseTimeout),t.resolutionTimeout&&clearTimeout(t.resolutionTimeout),this.activeTransactions.delete(e),De("cluster-member:clear-done",{messageHash:e,remaining:Array.from(this.activeTransactions.keys())})}};function z0(r={}){return e=>new _u(e,r)}var _u=class{protocol;maxInboundStreams;maxOutboundStreams;log;cluster;components;running;k;configuredClusterSize;allowDownsize;sizeTolerance;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}[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){let{stream:t,connection:s}=e,n=s.remotePeer,o=async function*(i){for await(let a of i){let c=new TextDecoder().decode(a.subarray()),l=JSON.parse(c),u;if(l.operation==="update"){let d=l.record?.message?.commit?.tailId??l.record?.message?.pend?Object.keys(l.record.message.pend.transforms)[0]:void 0;u=await this.cluster.update(l.record)}else throw new Error(`Unknown operation: ${l.operation}`);if(l.operation==="update"){let d=u;this.log("cluster-service:pre-serialize",{messageHash:d?.messageHash,responseType:typeof u,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 h=JSON.stringify(u);if(l.operation==="update"){let d=JSON.parse(h);this.log("cluster-service:post-serialize",{messageHash:d?.messageHash,promiseKeys:Object.keys(d?.promises??{}),commitKeys:Object.keys(d?.commits??{})})}yield new TextEncoder().encode(h)}};Promise.resolve().then(async()=>{await Qe(t,i=>Zt(i),o.bind(this),i=>dr(i),t)}).catch(i=>{this.log.error("error handling cluster protocol message from %p - %e",n,i)})}};ce();var q0=class r extends gs{protocolPrefix;constructor(e,t,s){super(e,t),this.protocolPrefix=s}static create(e,t,s){return new r(e,t,s)}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,s=0){let n={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((h,d)=>setTimeout(()=>d(new Error("RepoClient timeout")),i))]),c,l=(this.protocolPrefix??"/db-p2p")+"/repo/1.0.0";if(c=await a(()=>super.processMessage(n,l,{signal:t?.signal})),c?.redirect?.peers?.length){if(s>=2)throw new Error("Redirect loop detected in RepoClient (max hops reached)");let u=this.peerId.toString(),h=c.redirect.peers.find(p=>p.id!==u)??c.redirect.peers[0],d=G(h.id);if(h.id===u)throw new Error("Redirect loop detected in RepoClient (same peer)");return this.recordCoordinatorForOpsIfSupported(e,d),await r.create(d,this.peerNetwork,this.protocolPrefix).processRepoMessage(e,t,s+1)}return c}extractKeyFromOperations(e){let t=e[0];if("get"in t){let s=t.get.blockIds[0];return s?new TextEncoder().encode(s):void 0}if("pend"in t){let s=Object.keys(t.pend.transforms)[0];return s?new TextEncoder().encode(s):void 0}if("commit"in t)return new TextEncoder().encode(t.commit.tailId)}recordCoordinatorForOpsIfSupported(e,t){let s=this.extractKeyFromOperations(e),n=this.peerNetwork;s!=null&&typeof n?.recordCoordinator=="function"&&n.recordCoordinator(s,t)}};ce();Qt();jr();var J=yr("cluster"),nc=class{keyNetwork;createClusterClient;cfg;localCluster;fretService;transactions=new Map;retryInitialIntervalMs=2e3;retryBackoffFactor=2;retryMaxIntervalMs=3e4;retryMaxAttempts=5;constructor(e,t,s,n,o){this.keyNetwork=e,this.createClusterClient=t,this.cfg=s,this.localCluster=n,this.fretService=o}async createMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),s=await et.digest(t);return ye.encode(s.digest)}async getClusterForBlock(e){let t=new TextEncoder().encode(e);try{let s=await this.keyNetwork.findCluster(t),n=Object.keys(s??{});return J("cluster-tx:cluster-members",{blockId:e,peerIds:n}),s}catch(s){return J("WARN findCluster failed for %s: %o",e,s),{}}}makeRecord(e,t,s){let n=Object.keys(e??{}).length,o={messageHash:t,peers:e,message:s,coordinatingBlockIds:s.coordinatingBlockIds,promises:{},commits:{},suggestedClusterSize:n||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,s){let n=await this.getClusterForBlock(e),o=await this.createMessageHash(t),i=this.makeRecord(n,o,t);J("cluster-tx:start",{messageHash:o,blockId:e,peerCount:Object.keys(n??{}).length,allowDownsize:this.cfg.allowClusterDownsize,configuredSize:this.cfg.clusterSize,suggestedSize:i.suggestedClusterSize,minRequiredSize:i.minRequiredSize});let a=this.executeTransaction(n,i),c=new $n(a),l={messageHash:o,record:i,pending:c,lastUpdate:Date.now()};this.transactions.set(o,l),J("cluster-tx:transaction-store",{messageHash:o,transactionKeys:Array.from(this.transactions.keys())});try{return await c.result()}finally{let u=this.transactions.get(o),h=u?.retry?{attempt:u.retry.attempt,pending:Array.from(u.retry.pendingPeers??[])}:void 0;J("cluster-tx:complete",{messageHash:o,finalPromises:u?Object.keys(u.record.promises??{}):void 0,finalCommits:u?Object.keys(u.record.commits??{}):void 0,retry:h}),u?.retry||setTimeout(()=>{this.transactions.delete(o),J("cluster-tx:transaction-remove",{messageHash:o,remaining:Array.from(this.transactions.keys())})},100)}}async executeTransaction(e,t){let s=Object.keys(e).length;if(s<this.cfg.minAbsoluteClusterSize){if(!await this.validateSmallCluster(s,e))throw J("cluster-tx:reject-too-small",{peerCount:s,minRequired:this.cfg.minAbsoluteClusterSize}),new Error(`Cluster size ${s} below minimum ${this.cfg.minAbsoluteClusterSize} and not validated`);J("cluster-tx:small-cluster-validated",{peerCount:s})}if(!this.cfg.allowClusterDownsize&&s<this.cfg.clusterSize)throw J("cluster-tx:reject-downsize",{peerCount:s,required:this.cfg.clusterSize}),new Error(`Cluster size ${s} below configured minimum ${this.cfg.clusterSize}`);let n=await this.collectPromises(e,t),o=Math.ceil(s*this.cfg.superMajorityThreshold),i=n.record.promises,a=Object.values(i).filter(u=>u.type==="approve").length,c=Object.values(i).filter(u=>u.type==="reject").length,l=s-o;if(c>l){let u=Object.entries(i).filter(([h,d])=>d.type==="reject").map(([h,d])=>`${h}: ${d.rejectReason??"unknown"}`).join("; ");throw J("cluster-tx:rejected-by-validators",{messageHash:t.messageHash,peerCount:s,rejections:c,maxAllowed:l,reasons:u}),this.updateTransactionRecord(n.record,"rejected-by-validators"),new Error(`Transaction rejected by validators (${c}/${s} rejected): ${u}`)}if(s>1&&a<o)throw J("cluster-tx:supermajority-failed",{messageHash:t.messageHash,peerCount:s,approvals:a,rejections:c,superMajority:o,threshold:this.cfg.superMajorityThreshold}),this.updateTransactionRecord(n.record,"supermajority-failed"),new Error(`Failed to get super-majority: ${a}/${s} approvals (needed ${o}, ${c} rejections)`);return await this.commitTransaction(n.record)}async getClusterSize(e){let t=await this.getClusterForBlock(e);return Object.keys(t??{}).length}async validateSmallCluster(e,t){if(this.fretService)try{let s=this.fretService.getNetworkSizeEstimate();if(s.confidence>.5){let n=Math.floor(Math.log10(s.size_estimate+1)),o=Math.floor(Math.log10(e+1));if(Math.abs(n-o)<=1)return J("cluster-tx:small-cluster-validated-by-fret",{localSize:e,fretEstimate:s.size_estimate,confidence:s.confidence,sources:s.sources}),!0}}catch{}return J("cluster-tx:small-cluster-accepted-without-validation",{localSize:e,reason:"no-confident-network-size-estimate"}),!0}async collectPromises(e,t){let s=Object.keys(e),n=[],o=s.map(l=>{let u=this.localCluster&&l===this.localCluster.peerId.toString();J("cluster-tx:promise-request",{messageHash:t.messageHash,peerId:l,isLocal:u});let h=u?this.localCluster.update(t):this.createClusterClient(G(l)).update(t);return new $n(h)}),i=await Promise.all(o.map((l,u)=>l.result().then(h=>{let d=s[u];return J("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:d,success:!0,returnedPromises:Object.keys(h.promises??{}),returnedCommits:Object.keys(h.commits??{})}),n.push({peerId:d,success:!0}),h}).catch(h=>{let d=s[u];return J("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:d,success:!1,error:h}),n.push({peerId:d,success:!1,error:h instanceof Error?h.message:String(h)}),null}))),a=n.filter(l=>l.success).map(l=>l.peerId),c=n.filter(l=>!l.success);J("cluster-tx:promise-summary",{messageHash:t.messageHash,successes:a,failures:c}),J("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)){J("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(J("cluster-tx:promise-merge-result",{messageHash:t.messageHash,peerPromises:u}),typeof t.suggestedClusterSize=="number"&&typeof l.suggestedClusterSize=="number"){let h=l.suggestedClusterSize,d=Object.keys(e).length,f=Math.ceil(Math.max(1,h*this.cfg.clusterSizeTolerance));Math.abs(d-h)>f&&J("cluster-tx:size-variance",{expected:h,actual:d,tolerance:this.cfg.clusterSizeTolerance})}t.promises={...t.promises,...l.promises},J("cluster-tx:promise-merge-after",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})})}return J("cluster-tx:promise-merge",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})}),J("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),s=[],n={...e},o=t.map(f=>{let p=this.localCluster&&f===this.localCluster.peerId.toString();J("cluster-tx:commit-request",{messageHash:e.messageHash,peerId:f,isLocal:p});let m=p?this.localCluster.update(n):this.createClusterClient(G(f)).update(n);return new $n(m)}),i=await Promise.all(o.map((f,p)=>f.result().then(m=>{let g=t[p];return J("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!0}),s.push({peerId:g,success:!0}),m}).catch(m=>{let g=t[p];return J("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!1,error:m}),s.push({peerId:g,success:!1,error:m instanceof Error?m.message:String(m)}),null}))),a=s.filter(f=>f.success).map(f=>f.peerId),c=s.filter(f=>!f.success);J("cluster-tx:commit-summary",{messageHash:e.messageHash,successes:a,failures:c}),J("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))J("cluster-tx:commit-merge-input",{messageHash:e.messageHash,resultFrom:Object.keys(f.commits??{}),recordBefore:Object.keys(e.commits??{})}),J("cluster-tx:commit-merge-result",{messageHash:e.messageHash,peerCommits:Object.keys(f.commits??{})}),e.commits={...e.commits,...f.commits},J("cluster-tx:commit-merge-after",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})});J("cluster-tx:commit-merge",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})}),J("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,h=Object.keys(e.commits).length;h>=u&&J("cluster-tx:commit-majority-reached",{messageHash:e.messageHash,commitCount:h,simpleMajority:u,peerCount:l,threshold:this.cfg.simpleMajorityThreshold});let d=c.map(f=>f.peerId);return d.length>0?this.scheduleCommitRetry(e.messageHash,e,d):this.clearRetry(e.messageHash),e}updateTransactionRecord(e,t){let s=this.transactions.get(e.messageHash);if(!s){J("cluster-tx:transaction-update-miss",{messageHash:e.messageHash,stage:t});return}s.record={...e},s.lastUpdate=Date.now(),J("cluster-tx:transaction-update",{messageHash:e.messageHash,stage:t,promises:Object.keys(e.promises??{}),commits:Object.keys(e.commits??{})})}scheduleCommitRetry(e,t,s){let n=this.transactions.get(e);if(!n)return;let o=n.retry,i=(o?.attempt??0)+1;if(i>this.retryMaxAttempts){J("cluster-tx:retry-abort",{messageHash:e,missingPeers:s});return}if(s.length===0){this.clearRetry(e);return}let a=new Set(s),c=o?Math.min(o.intervalMs*this.retryBackoffFactor,this.retryMaxIntervalMs):this.retryInitialIntervalMs;o?.timer&&clearTimeout(o.timer);let l=setTimeout(()=>{this.retryCommits(e)},c);n.retry={pendingPeers:a,attempt:i,intervalMs:c,timer:l},J("cluster-tx:retry-scheduled",{messageHash:e,attempt:i,missingPeers:s,delayMs:c})}async retryCommits(e){let t=this.transactions.get(e);if(!t?.retry)return;let{pendingPeers:s,attempt:n}=t.retry;if(s.size===0){this.clearRetry(e);return}let o=Array.from(s),i=t.record;J("cluster-tx:retry-start",{messageHash:e,attempt:n,peerIds:o});let a=await Promise.all(o.map(async u=>{let h=this.localCluster&&u===this.localCluster.peerId.toString(),d={...i,commits:i.commits};try{let f=h?await this.localCluster.update(d):await this.createClusterClient(G(u)).update(d);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)s.delete(u);if(J("cluster-tx:retry-complete",{messageHash:e,attempt:n,successes:c,failures:l}),s.size===0){J("cluster-tx:retry-finished",{messageHash:e}),this.clearRetry(e);return}this.transactions.has(e)&&this.scheduleCommitRetry(e,t.record,Array.from(s))}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),J("cluster-tx:transaction-remove",{messageHash:e,remaining:Array.from(this.transactions.keys())})},100))}};function $0(r,e,t,s){return n=>new Au(r,e,n.storageRepo,t,n.localCluster,n.localPeerId,s)}var Au=class{keyNetwork;createClusterClient;storageRepo;coordinator;DEFAULT_TIMEOUT=3e4;constructor(e,t,s,n,o,i,a){this.keyNetwork=e,this.createClusterClient=t,this.storageRepo=s;let c={clusterSize:n?.clusterSize??10,superMajorityThreshold:n?.superMajorityThreshold??.75,simpleMajorityThreshold:n?.simpleMajorityThreshold??.51,minAbsoluteClusterSize:n?.minAbsoluteClusterSize??3,allowClusterDownsize:n?.allowClusterDownsize??!0,clusterSizeTolerance:n?.clusterSizeTolerance??.5,partitionDetectionWindow:n?.partitionDetectionWindow??6e4},l=o&&i?{update:o.update.bind(o),peerId:i}:void 0;this.coordinator=new nc(e,t,c,l,a)}async get(e,t){return await this.storageRepo.get(e,t)}async pend(e,t){let s=Object.keys(e.transforms),n=t?.coordinatingBlockIds??s;if(await this.coordinator.getClusterSize(n[0])<=1)return await this.storageRepo.pend(e,t);let i={operations:[{pend:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT,coordinatingBlockIds:n};try{return await this.coordinator.executeClusterTransaction(n[0],i,t),await this.storageRepo.pend(e,t)}catch(a){throw console.error("Failed to complete pend operation:",a),a}}async cancel(e,t){let s=e.blockIds,n={operations:[{cancel:{actionRef:e}}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let o=s.map(i=>this.coordinator.executeClusterTransaction(i,n,t));await Promise.all(o),await this.storageRepo.cancel(e,t)}catch(o){throw console.error("Failed to complete cancel operation:",o),o}}async commit(e,t){let s=e.blockIds;if(await this.coordinator.getClusterSize(s[0])<=1)return await this.storageRepo.commit(e,t);let o={operations:[{commit:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{return await this.coordinator.executeClusterTransaction(s[0],o,t),await this.storageRepo.commit(e,t)}catch(i){throw console.error("Failed to complete commit operation:",i),i}}};function xb(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 Vn(r,e){let t=xb(r),s=xb(e);return t!=null&&s!=null&&t===s}jr();function Tu(r){return{redirect:{peers:r,reason:"not_in_cluster"}}}function G0(r={}){return e=>new Cu(e,r)}var Cu=class{protocol;maxInboundStreams;maxOutboundStreams;log;repo;components;running;k;constructor(e,t={}){this.components=e;let s=t.protocol??(t.protocolPrefix??"/db-p2p")+"/repo/1.0.0";this.protocol=s,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}[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){let{stream:t,connection:s}=e,n=s.remotePeer,o=async function*(i){for await(let a of i){let c=new TextDecoder().decode(a.subarray()),l=JSON.parse(c),u=l.operations[0],h;if("get"in u){let f=(await et.digest(new TextEncoder().encode(u.get.blockIds[0]))).digest,p=this.components.libp2p?.services?.networkManager;if(p?.getCluster){let m=await p.getCluster(f);l.cluster=m.map(w=>w.toString?.()??String(w));let g=this.components.libp2p.peerId,y=m.some(w=>Vn(w,g));if(!(m.length<this.k)&&!y){let w=m.filter(x=>!Vn(x,g));console.debug("repo-service:redirect",{peerId:g.toString(),reason:"not-cluster-member",operation:"get",blockId:u.get.blockIds[0],cluster:m.map(x=>x.toString?.()??String(x))}),h=Tu(w.map(x=>({id:x.toString(),addrs:[]})))}else h=await this.repo.get(u.get,{expiration:l.expiration})}else h=await this.repo.get(u.get,{expiration:l.expiration})}else if("pend"in u){let d=Object.keys(u.pend.transforms)[0],p=(await et.digest(new TextEncoder().encode(d))).digest,m=this.components.libp2p?.services?.networkManager;if(m?.getCluster){let g=await m.getCluster(p);l.cluster=g.map(x=>x.toString?.()??String(x));let y=this.components.libp2p.peerId,b=g.some(x=>Vn(x,y));if(!(g.length<this.k)&&!b){let x=g.filter(E=>!Vn(E,y));console.debug("repo-service:redirect",{peerId:y.toString(),reason:"not-cluster-member",operation:"pend",blockId:d,cluster:g.map(E=>E.toString?.()??String(E))}),h=Tu(x.map(E=>({id:E.toString(),addrs:[]})))}else h=await this.repo.pend(u.pend,{expiration:l.expiration})}else h=await this.repo.pend(u.pend,{expiration:l.expiration})}else if("cancel"in u)h=await this.repo.cancel(u.cancel.actionRef,{expiration:l.expiration});else if("commit"in u){let f=(await et.digest(new TextEncoder().encode(u.commit.tailId))).digest,p=this.components.libp2p?.services?.networkManager;if(p?.getCluster){let m=await p.getCluster(f);l.cluster=m.map(w=>w.toString?.()??String(w));let g=this.components.libp2p.peerId,y=m.some(w=>Vn(w,g));if(!(m.length<this.k)&&!y){let w=m.filter(x=>!Vn(x,g));console.debug("repo-service:redirect",{peerId:g.toString(),reason:"not-cluster-member",operation:"commit",tailId:u.commit.tailId,cluster:m.map(x=>x.toString?.()??String(x))}),h=Tu(w.map(x=>({id:x.toString(),addrs:[]})))}else h=await this.repo.commit(u.commit,{expiration:l.expiration})}else h=await this.repo.commit(u.commit,{expiration:l.expiration})}yield new TextEncoder().encode(JSON.stringify(h))}};Promise.resolve().then(async()=>{await Qe(t,i=>Zt(i),o.bind(this),i=>dr(i),t)}).catch(i=>{this.log.error("error handling repo protocol message from %p - %e",n,i)})}};function vb(r){if(r.length<=1)return r;r.sort((t,s)=>t[0]-s[0]);let e=[r[0]];for(let t of r.slice(1)){let s=e[e.length-1];s[1]!==void 0&&(t[0]<=s[1]?t[1]===void 0?s[1]=void 0:s[1]=Math.max(s[1],t[1]):e.push(t))}return e}var Ei=class{blockId;storage;restoreCallback;constructor(e,t,s){this.blockId=e,this.storage=t,this.restoreCallback=s}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 s=e??t.latest?.rev;if(s===void 0)throw new Error(`No revision specified and no latest revision exists for block ${this.blockId}`);return await this.ensureRevision(t,s),await this.materializeBlock(t,s)}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 s=await this.storage.getMetadata(this.blockId);s||(s={latest:void 0,ranges:[[0]]},await this.storage.saveMetadata(this.blockId,s)),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 s=`BlockStorage.ensureRevision:${this.blockId}`,n=await qn.acquire(s);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=vb(o.ranges),await this.storage.saveMetadata(this.blockId,o)}finally{n()}}async materializeBlock(e,t){let s,n,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){s=a,n=i;break}else o.push(i)}if(!s||!n)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}`);s=Qa(s,c)}if(!s)throw new Error(`Block ${this.blockId} has been deleted`);return o.length?(await this.storage.saveMaterializedBlock(this.blockId,o[0].actionId,s),{block:s,actionRev:o[0]}):{block:s,actionRev:n}}async restoreBlock(e){if(this.restoreCallback)return await this.restoreCallback(this.blockId,e)}async saveRestored(e){let t=Object.entries(e.revisions).map(([s,n])=>({rev:Number(s),data:n}));for(let{rev:s,data:{action:n,block:o}}of t)await Promise.all([this.storage.saveRevision(this.blockId,s,n.actionId),this.storage.saveTransaction(this.blockId,n.actionId,n.transform),o?this.storage.saveMaterializedBlock(this.blockId,n.actionId,o):Promise.resolve()])}inRanges(e,t){return t.some(s=>e>=s[0]&&(s[1]===void 0||e<s[1]))}};var As=oe("fs"),Nr=xe(oe("path"),1);var Pu=yr("storage:file"),oc=class{basePath;constructor(e){this.basePath=e}async getMetadata(e){return this.readIfExists(this.getMetadataPath(e))}async saveMetadata(e,t){await this.ensureAndWriteFile(this.getMetadataPath(e),JSON.stringify(t))}async getRevision(e,t){return this.readIfExists(this.getRevisionPath(e,t))}async saveRevision(e,t,s){await this.ensureAndWriteFile(this.getRevisionPath(e,t),s)}async getPendingTransaction(e,t){return this.readIfExists(this.getPendingActionPath(e,t))}async savePendingTransaction(e,t,s){await this.ensureAndWriteFile(this.getPendingActionPath(e,t),JSON.stringify(s))}async deletePendingTransaction(e,t){let s=this.getPendingActionPath(e,t);await As.promises.unlink(s).catch(n=>{n?.code!=="ENOENT"&&Pu("deletePendingTransaction unlink failed for %s/%s - %o",e,t,n)})}async*listPendingTransactions(e){let t=Nr.join(this.getBlockPath(e),"pend"),s=await As.promises.readdir(t).catch(n=>(Pu("listPendingTransactions readdir failed for %s - %o",e,n),[]));for(let n of s){if(!n.endsWith(".json"))continue;let o=n.slice(0,-5);/^[\w\d]+-[\w\d]+-[\w\d]+-[\w\d]+-[\w\d]+$/.test(o)&&(yield o)}}async getTransaction(e,t){return this.readIfExists(this.getActionPath(e,t))}async*listRevisions(e,t,s){for(let n=t;t<=s?n<=s:n>=s;t<=s?++n:--n){let o=await this.getRevision(e,n);o&&(yield{actionId:o,rev:n})}}async saveTransaction(e,t,s){await this.ensureAndWriteFile(this.getActionPath(e,t),JSON.stringify(s))}async getMaterializedBlock(e,t){return this.readIfExists(this.getMaterializedPath(e,t))}async saveMaterializedBlock(e,t,s){s?await this.ensureAndWriteFile(this.getMaterializedPath(e,t),JSON.stringify(s)):await As.promises.unlink(this.getMaterializedPath(e,t)).catch(n=>{n?.code!=="ENOENT"&&Pu("saveMaterializedBlock unlink failed for %s/%s - %o",e,t,n)})}async promotePendingTransaction(e,t){let s=this.getPendingActionPath(e,t),n=this.getActionPath(e,t);return await As.promises.mkdir(Nr.dirname(n),{recursive:!0}),As.promises.rename(s,n).catch(o=>{throw o.code==="ENOENT"?new Error(`Pending action ${t} not found for block ${e}`):(Pu("promotePendingTransaction rename failed for %s/%s - %o",e,t,o),o)})}getBlockPath(e){return Nr.join(this.basePath,e)}getMetadataPath(e){return Nr.join(this.getBlockPath(e),"meta.json")}getRevisionPath(e,t){return Nr.join(this.getBlockPath(e),"revs",`${t}.json`)}getPendingActionPath(e,t){return Nr.join(this.getBlockPath(e),"pend",`${t}.json`)}getActionPath(e,t){return Nr.join(this.getBlockPath(e),"actions",`${t}.json`)}getMaterializedPath(e,t){return Nr.join(this.getBlockPath(e),"blocks",`${t}.json`)}async readIfExists(e){return As.promises.readFile(e,"utf-8").then(t=>JSON.parse(t)).catch(t=>{if(t.code!=="ENOENT")throw t})}async ensureAndWriteFile(e,t){await As.promises.mkdir(Nr.dirname(e),{recursive:!0}),await As.promises.writeFile(e,t)}};var ic=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,s){this.revisions.set(this.getRevisionKey(e,t),s)}async*listRevisions(e,t,s){let n=t<=s,o=n?t:s,i=n?s: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})}n||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,s){this.pendingActions.set(this.getActionKey(e,t),s)}async deletePendingTransaction(e,t){this.pendingActions.delete(this.getActionKey(e,t))}async*listPendingTransactions(e){let t=`${e}:`;for(let[s]of Array.from(this.pendingActions.entries()))s.startsWith(t)&&(yield s.substring(t.length))}async getTransaction(e,t){return this.actions.get(this.getActionKey(e,t))}async saveTransaction(e,t,s){this.actions.set(this.getActionKey(e,t),s)}async getMaterializedBlock(e,t){return this.materializedBlocks.get(this.getActionKey(e,t))}async saveMaterializedBlock(e,t,s){let n=this.getActionKey(e,t);s?this.materializedBlocks.set(n,s):this.materializedBlocks.delete(n)}async promotePendingTransaction(e,t){let s=this.getActionKey(e,t),n=this.pendingActions.get(s);n&&(this.actions.set(s,n),this.pendingActions.delete(s))}};var ac=class{createBlockStorage;validatePend;constructor(e,t){this.createBlockStorage=e,this.validatePend=t?.validatePend}async get({blockIds:e,context:t},s){let n=Array.from(new Set(e)),o=await Promise.all(n.map(async i=>{let a=this.createBlockStorage(i);if(t){let u=await a.getLatest(),h=u?t.committed.filter(d=>d.rev>u.rev):t.committed;for(let{actionId:d,rev:f}of h.sort((p,m)=>p.rev-m.rev))await a.getPendingTransaction(d)&&await this.internalCommit(i,d,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 h=Qa(c.block,u);return[i,{block:h,state:{latest:await a.getLatest(),pendings:[t.actionId]}}]}let l=await va(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 s=zn(e.transforms),n=[],o=[];for(let i of s){let a=this.createBlockStorage(i),c=yu(e.transforms,i),l=await va(a.listPendingTransactions());if(n.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 h=await va(a.listRevisions(e.rev??0,u.rev));for(let d of h){let f=await a.getTransaction(d.actionId);if(!f)throw new Error(`Missing action ${d.actionId} for block ${i}`);o.push({actionId:d.actionId,rev:d.rev,transforms:c0(f,i)})}}}}if(o.length)return{success:!1,missing:o};if(n.length>0){if(e.policy==="f")return{success:!1,pending:n};if(e.policy==="r")return{success:!1,pending:await Promise.all(n.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(s.map(i=>{let a=this.createBlockStorage(i),c=yu(e.transforms,i);return a.savePendingTransaction(e.actionId,c)})),{success:!0,pending:n,blockIds:s}}async cancel(e,t){await Promise.all(e.blockIds.map(s=>this.createBlockStorage(s).deletePendingTransaction(e.actionId)))}async commit(e,t){let s=Array.from(new Set(e.blockIds)).sort(),n=[];try{for(let c of s){let l=`StorageRepo.commit:${c}`,u=await qn.acquire(l);n.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 h=[];for await(let d of l.listRevisions(e.rev,u.rev)){let f=await l.getTransaction(d.actionId);if(!f)throw new Error(`Missing action ${d.actionId} for block ${c}`);h.push({actionId:d.actionId,rev:d.rev,transform:f})}i.push({blockId:c,transforms:h})}}if(i.length)return{success:!1,missing:WA(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{n.reverse().forEach(o=>o())}return{success:!0}}async internalCommit(e,t,s,n){let o=await n.getPendingTransaction(t);if(!o)throw new Error(`Consistency Error: Pending action ${t} disappeared for block ${e} within critical section.`);let i=await n.getLatest(),a=i?(await n.getBlock(i.rev))?.block:void 0,c=Qa(a,o);c&&await n.saveMaterializedBlock(t,c),await n.saveRevision(s,t),await n.promotePendingTransaction(t),await n.setLatest({actionId:t,rev:s})}};function WA(r){let e=r.flatMap(({blockId:s,transforms:n})=>n.map(o=>({blockId:s,transform:o}))),t=L0(e,({transform:s})=>s.actionId);return Object.entries(t).map(([s,n])=>n.reduce((o,{blockId:i,transform:a})=>(l0(o.transforms,i,a.transform),o),{actionId:s,rev:n[0].transform.rev,transforms:a0()}))}var rs=class{entries;constructor(e){this.entries=e}},cc=class{partitions;nodes;constructor(e,t){this.partitions=e,this.nodes=t}};var Ts=class r{node;index;constructor(e,t){this.node=e,this.index=t}clone(){return new r(this.node,this.index)}},Si=class r{branches;leafNode;leafIndex;on;version;constructor(e,t,s,n,o){this.branches=e,this.leafNode=t,this.leafIndex=s,this.on=n,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 br=64,ku=class{keyFromEntry;compare;_root;_version=0;constructor(e=s=>s,t=(s,n)=>s<n?-1:s>n?1:0){this.keyFromEntry=e,this.compare=t,this._root=new rs([])}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(),s=e.last?this.findLast(e):e.isAscending?this.last():this.first(),n=this.keyFromEntry(s.leafNode.entries[s.leafIndex]),o=e.isAscending?this.internalAscending(t):this.internalDescending(t),i=e.isAscending?1:-1;for(let a of o){if(!a.on||!s.on||this.compareKeys(this.keyFromEntry(a.leafNode.entries[a.leafIndex]),n)*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 s=this.internalUpdate(e,t);return s[0].on&&(s[0].version=++this._version),s}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 s=this.keyFromEntry(e),n=this.find(s);if(n.on){let o=this.updateAt(n,t(n.leafNode.entries[n.leafIndex]));return o[0].on&&(o[0].version=++this._version),o}else return this.internalInsertAt(n,Object.freeze(e)),n.on=!0,n.version=++this._version,[n,!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,s=e?e.path.clone():this.first();if(e?.ascending??!0)for(;s.on;)t+=s.leafNode.entries.length-s.leafIndex,s.leafIndex=s.leafNode.entries.length-1,this.internalNext(s);else for(;s.on;)t+=s.leafIndex+1,s.leafIndex=0,this.internalPrior(s);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 s=this.compare(e,t);if(s!==0&&s===this.compare(t,e))throw new Error("Inconsistent comparison function for given values");return s}*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 rs){let s=e,[n,o]=this.indexOfEntry(s.entries,t);return new Si([],s,o,n,this._version)}else{let s=e,n=this.indexOfKey(s.partitions,t),o=this.getPath(s.nodes[n],t);return o.branches.unshift(new Ts(s,n)),o}}indexOfEntry(e,t){let s=0,n=e.length-1,o=0,i=-1;for(;s<=n;){if(o=s+n>>>1,i=this.compareKeys(t,this.keyFromEntry(e[o])),i===0)return[!0,o];i<0?n=o-1:s=o+1}return[!1,s]}indexOfKey(e,t){let s=0,n=e.length-1,o=0,i=-1;for(;s<=n;){if(o=s+n>>>1,i=this.compareKeys(t,e[o]),i===0)return o+1;i<0?n=o-1:s=o+1}return s}internalNext(e){if(e.on)if(e.leafIndex>=e.leafNode.entries.length-1){let t=0,s=!1,n=e.branches.length-1;for(;t<=n&&!s;){let o=e.branches[n-t];o.index===o.node.partitions.length?++t:s=!0}if(!s)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,s=!1,n=e.branches.length-1;for(;t<=n&&!s;)e.branches[n-t].index===0?++t:s=!0;if(!s)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 s=this.keyFromEntry(e.leafNode.entries[e.leafIndex]),n=this.keyFromEntry(t);if(this.compareKeys(s,n)!==0){let o=this.internalInsert(t);return o.on&&(this.internalDelete(this.find(s)),o=this.find(n)),[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 s=e.branches.at(-1);this.updatePartition(s.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 s=this.leafInsert(e,t),n=e.branches.length-1;for(;s&&n>=0;)s=this.branchInsert(e,n,s),--n;if(s){let o=new cc([s.key],[this._root,s.right]);this._root=o,e.branches.unshift(new Ts(o,s.indexDelta))}}moveToFirst(e,t){if(e instanceof rs){let s=e;t.leafNode=s,t.leafIndex=0,t.on=s.entries.length>0}else t.branches.push(new Ts(e,0)),this.moveToFirst(e.nodes[0],t)}moveToLast(e,t){if(e instanceof rs){let s=e,n=s.entries.length;t.leafNode=s,t.on=n>0,t.leafIndex=n>0?n-1:0}else{let s=e,n=new Ts(s,s.partitions.length);t.branches.push(n),this.moveToLast(s.nodes[n.index],t)}}getFirst(e){if(e instanceof rs){let t=e;return new Si([],t,0,t.entries.length>0,this._version)}else{let t=e,s=this.getFirst(t.nodes[0]);return s.branches.unshift(new Ts(t,0)),s}}getLast(e){if(e instanceof rs){let t=e,s=t.entries.length;return new Si([],t,s>0?s-1:0,s>0,this._version)}else{let t=e,s=t.nodes.length-1,n=this.getLast(t.nodes[s]);return n.branches.unshift(new Ts(t,s)),n}}leafInsert(e,t){let{leafNode:s,leafIndex:n}=e;if(s.entries.length<br){s.entries.splice(n,0,t);return}let o=s.entries.length+1>>>1,i=s.entries.splice(o),a=new rs(i),c=n<o?0:1;return c?(e.leafNode=a,e.leafIndex-=s.entries.length,a.entries.splice(e.leafIndex,0,t)):s.entries.splice(n,0,t),new Du(this.keyFromEntry(i[0]),a,c)}branchInsert(e,t,s){let n=e.branches[t],{index:o,node:i}=n;if(n.index+=s.indexDelta,i.partitions.splice(o,0,s.key),i.nodes.splice(o+1,0,s.right),i.nodes.length<=br)return;let a=i.nodes.length>>>1,c=i.partitions.splice(a),l=i.partitions.pop(),u=i.nodes.splice(a),h=new cc(c,u),d=n.index<a?0:1;return d&&(n.index-=a,n.node=h),new Du(l,h,d)}rebalanceLeaf(e){if(e.leafNode.entries.length>=br>>>1)return;let t=e.leafNode,s=e.branches.at(-1),n=e.branches.length-1,o=s.index,i=s.node,a=i.nodes[o+1];if(a&&a.entries.length>br>>>1){let l=a.entries.shift();t.entries.push(l),this.updatePartition(o+1,e,n,this.keyFromEntry(a.entries[0]));return}let c=i.nodes[o-1];if(c&&c.entries.length>br>>>1){let l=c.entries.pop();t.entries.unshift(l),this.updatePartition(o,e,n,this.keyFromEntry(l)),e.leafIndex+=1;return}if(a&&a.entries.length+t.entries.length<=br)return t.entries.push(...a.entries),i.partitions.splice(o,1),i.nodes.splice(o+1,1),o===0&&this.updatePartition(o,e,n,this.keyFromEntry(t.entries[0])),this.rebalanceBranch(e,n);if(c&&c.entries.length+t.entries.length<=br)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,n)}rebalanceBranch(e,t){let s=e.branches[t],n=s.node;if(t===0&&n.partitions.length===0)return e.branches[t+1]?.node??e.leafNode;if(t===0||n.nodes.length>=br<<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>br>>>1){n.partitions.push(a.partitions[i]);let u=c.nodes.shift();n.nodes.push(u);let h=c.partitions.shift();this.updatePartition(i+1,e,t-1,h);return}let l=a.nodes[i-1];if(l&&l.nodes.length>br>>>1){n.partitions.unshift(a.partitions[i-1]);let u=l.nodes.pop();n.nodes.unshift(u);let h=l.partitions.pop();s.index+=1,this.updatePartition(i,e,t-1,h);return}if(c&&c.nodes.length+n.nodes.length<=br){let u=a.partitions.splice(i,1)[0];return n.partitions.push(u),n.partitions.push(...c.partitions),n.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+n.nodes.length<=br){s.node=l,s.index+=l.nodes.length;let u=a.partitions.splice(i-1,1)[0];return l.partitions.push(u),l.partitions.push(...n.partitions),l.nodes.push(...n.nodes),a.nodes.splice(i,1),this.rebalanceBranch(e,t-1)}}updatePartition(e,t,s,n){let o=t.branches[s];e>0?o.node.partitions[e-1]=n:s!==0&&this.updatePartition(t.branches[s-1].index,t,s-1,n)}validatePath(e){if(!this.isValid(e))throw new Error("Path is invalid due to mutation of the tree")}},Du=class{key;right;indexDelta;constructor(e,t,s){this.key=e,this.right=t,this.indexDelta=s}};function lc(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function Mu(r){return`${lc(r.coord)}|${r.id}`}var Ou=class{byKey;byId;constructor(){this.byKey=new ku(e=>Mu(e)),this.byId=new Map}insert(e){let t=Mu(e);this.byKey.insert(e),this.byId.set(e.id,t)}upsert(e,t){let s=Date.now(),n=this.byId.get(e);if(n){let i=this.byKey.find(n);i.on&&this.byKey.deleteAt(i),this.byId.delete(e)}let o={id:e,coord:t,relevance:0,lastAccess:s,state:"disconnected",accessCount:0,successCount:0,failureCount:0,avgLatencyMs:0};return this.insert(o),o}update(e,t){let s=this.byId.get(e);if(!s)return;let n=this.byKey.find(s),o=this.byKey.at(n);if(!o)return;let i={...o,...t};this.byKey.updateAt(n,i),Mu(o)!==Mu(i)&&(this.byKey.deleteAt(n),this.insert(i))}getById(e){let t=this.byId.get(e);if(!t)return;let s=this.byKey.find(t);return s.on?this.byKey.at(s):void 0}remove(e){let t=this.byId.get(e);if(!t)return;let s=this.byKey.find(t);s.on&&this.byKey.deleteAt(s),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 s=new Set;for(let n of this.neighborsRight(e,t))s.add(n);for(let n of this.neighborsLeft(e,t))s.add(n);return s}ceilPath(e){let t=`${e}|\0`,s=this.byKey.find(t);return s.on||(s=this.byKey.next(s)),s}floorPath(e){let t=`${e}|\uFFFF`,s=this.byKey.find(t);return s.on||(s=this.byKey.prior(s)),s}successorOfCoord(e){let t=lc(e),s=this.ceilPath(t);if(s.on)return this.byKey.at(s);let n=this.byKey.first();return n.on?this.byKey.at(n):void 0}predecessorOfCoord(e){let t=lc(e),s=this.floorPath(t);if(s.on)return this.byKey.at(s);let n=this.byKey.last();return n.on?this.byKey.at(n):void 0}neighborsRight(e,t){let s=[],n=lc(e),o=this.ceilPath(n);o=o.on?o:this.byKey.first();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.first(),!o.on));)s.push(this.byKey.at(o).id),o=this.byKey.next(o),i++;return Array.from(new Set(s))}neighborsLeft(e,t){let s=[],n=lc(e),o=this.floorPath(n);o=o.on?o:this.byKey.last();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.last(),!o.on));)s.push(this.byKey.at(o).id),o=this.byKey.prior(o),i++;return Array.from(new Set(s))}};jr();Pe();be();async function qe(r){let e=r.toMultihash().bytes;return await et.encode(e)}async function rr(r){return await et.encode(r)}function Eb(r){return U(r,"base64url")}function Sb(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 V0="/optimystic/default/fret/1.0.0/neighbors",W0="/optimystic/default/fret/1.0.0/neighbors/announce",j0="/optimystic/default/fret/1.0.0/maybeAct",Y0="/optimystic/default/fret/1.0.0/leave",X0="/optimystic/default/fret/1.0.0/ping";async function wr(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)}async function ss(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 s=new TextDecoder().decode(r.subarray(e,t));return JSON.parse(s)}ce();var Ib=xe(K0(),1),jA="optimystic:fret";function an(r){return(0,Ib.default)(`${jA}:${r}`)}var Z0=an("rpc:neighbors");function _b(r,e,t,s={PROTOCOL_NEIGHBORS:V0,PROTOCOL_NEIGHBORS_ANNOUNCE:W0}){r.handle(s.PROTOCOL_NEIGHBORS,async({stream:n})=>{try{let o=await e();await n.sink((async function*(){yield await wr(o)})());try{n.close?.()}catch{}}catch(o){console.error("neighbors handler error:",o)}}),t&&r.handle(s.PROTOCOL_NEIGHBORS_ANNOUNCE,async({stream:n})=>{try{let o=await Tb(n),i=await ss(o);t(i.from,i),await n.sink((async function*(){yield await wr({ok:!0})})());try{n.close?.()}catch{}}catch(o){console.error("neighbors announce handler error:",o)}})}async function Ab(r,e,t=V0){let s=G(e),n=r.getConnections?.(s)??[];if(!Array.isArray(n)||n.length===0||typeof n[0]?.newStream!="function")return{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""};let o;try{o=await n[0].newStream([t]);let i=await Tb(o);return await ss(i)}catch(i){return Z0("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 Q0(r,e,t,s=W0){let n=G(e),o=r.getConnections?.(n)??[];if(!Array.isArray(o)||o.length===0||typeof o[0]?.newStream!="function")return;let i;try{i=await o[0].newStream([s]),await i.sink((async function*(){yield await wr(t)})())}catch(a){Z0("announceNeighbors failed to %s - %o",e,a)}finally{if(i)try{await i.close()}catch{}}}function YA(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")try{return e.subarray(0)}catch(t){Z0("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 Tb(r){let e=[];for await(let o of r.source)e.push(YA(o));let t=0;for(let o of e)t+=o.length;let s=new Uint8Array(t),n=0;for(let o of e)s.set(o,n),n+=o.length;return s}ce();function Cb(r,e,t=j0){r.handle(t,async({stream:s})=>{try{let n=await kb(s),o=await ss(n),i=await e(o);await s.sink((async function*(){yield await wr(i)})())}catch(n){console.error("maybeAct handler error:",n)}})}async function Pb(r,e,t,s=j0){let n=G(e),o=r.getConnections?.(n)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([s]):i=await r.dialProtocol(n,[s]),await i.sink((async function*(){yield await wr(t)})());let a=await kb(i);return await ss(a)}finally{if(i)try{await i.close()}catch{}}}function XA(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 kb(r){let e=[];for await(let o of r.source)e.push(XA(o));let t=0;for(let o of e)t+=o.length;let s=new Uint8Array(t),n=0;for(let o of e)s.set(o,n),n+=o.length;return s}ce();function Db(r,e,t=Y0){r.handle(t,async({stream:s})=>{try{let n=await QA(s),o=await ss(n);await e(o),await s.sink((async function*(){yield await wr({ok:!0})})())}catch(n){console.error("leave handler error:",n)}})}async function Mb(r,e,t,s=Y0){let n=G(e),o=r.getConnections?.(n)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([s]):i=await r.dialProtocol(n,[s]),await i.sink((async function*(){yield await wr(t)})())}finally{if(i)try{await i.close()}catch{}}}function ZA(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 QA(r){let e=[];for await(let o of r.source)e.push(ZA(o));let t=0;for(let o of e)t+=o.length;let s=new Uint8Array(t),n=0;for(let o of e)s.set(o,n),n+=o.length;return s}ce();var J0=an("rpc:ping");function Ob(r,e=X0,t){r.handle(e,async({stream:s})=>{let n={ok:!0,ts:Date.now()};if(t)try{let o=await t();o.size_estimate!==void 0&&(n.size_estimate=o.size_estimate,n.confidence=o.confidence)}catch(o){J0("getSizeEstimate failed - %o",o)}await s.sink((async function*(){yield await wr(n)})())})}async function uc(r,e,t=X0){let s=Date.now(),n=G(e),o;try{try{let l=r.getConnections?.(n)??[];if(Array.isArray(l)&&l.length>0&&typeof l[0]?.newStream=="function")o=await l[0].newStream([t]);else{let u=await r.dialProtocol(n,[t]);o=u.stream??u}}catch{let u=await r.dialProtocol(n,[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){J0("sendPing chunk handling failed - %o",u)}let a=Math.max(0,Date.now()-s);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 ss(i);return{ok:!!l.ok,rttMs:a,size_estimate:l.size_estimate,confidence:l.confidence}}catch(l){return J0("sendPing decode failed - %o",l),{ok:!1,rttMs:a}}}finally{if(o)try{await o.close()}catch{}}}be();function JA(r){let e=0n;for(let t=0;t<r.length;t++)e=e<<8n|BigInt(r[t]);return e}function eT(r){if(r.length===0)return 0n;let e=[...r].sort((s,n)=>s<n?-1:s>n?1:0),t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2n:e[t]}function Ru(r,e){let t=r.list(),s=t.length;if(s===0)return{n:0,confidence:0};if(s===1)return{n:1,confidence:.2};let n=1n<<256n,o=t.map(g=>JA(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]+n-o[o.length-1]);let a=eT(i),c=a>0n?a:n/BigInt(Math.max(1,s)),l=n/c,u=Math.max(1,Math.min(Number(l),1e9)),h=i[0],d=i[0];for(let g of i)g<h&&(h=g),g>d&&(d=g);let f=Math.min(1,s/Math.max(1,e*2)),p=d===0n?0:Number(h)/Number(d),m=Math.max(.05,Math.min(1,.5*f+.5*p));return{n:u,confidence:m}}var Ii=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 s=(e-this.tokens)/this.refillPerSec;return Math.ceil(s*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)}};ce();Pe();var yt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Cs=class extends Error{static name="ValidationError";name="ValidationError"},hc=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Lu=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};Qt();Cr();Gt();be();Pe();Ar();Vr();be();Pe();var $e=oe("node:net");Rf();Pl();Yo();Lf();Vr();be();Pe();function t2(r){return e=>U(e,r)}function r2(r){return e=>R(e,r)}function _i(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Wn(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Rb(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=R(e[0],"base32"),s=parseInt(e[1],10);if(s<1||s>65536)throw new Error("Port number is not in range(1, 65536)");let n=Wn(s);return st([t,n],t.length+n.length)}function Lb(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=pr.decode(`b${e[0]}`),s=parseInt(e[1],10);if(s<1||s>65536)throw new Error("Port number is not in range(1, 65536)");let n=Wn(s);return st([t,n],t.length+n.length)}function s2(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),s=U(e,"base32"),n=_i(t);return`${s}:${n}`}var n2=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,s)=>{let n=parseInt(t,10);if(isNaN(n)||n<0||n>255)throw new yt("Invalid byte value in IP address");e[s]=n}),e},Nb=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),s;for(s=0;s<t.length;s++){let o=(0,$e.isIPv4)(t[s]),i;o&&(i=n2(t[s]),t[s]=U(i.subarray(0,2),"base16")),i!=null&&++s<8&&t.splice(s,0,U(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(s=0;s<t.length&&t[s]!=="";s++);let o=[s,1];for(s=9-t.length;s>0;s--)o.push("0");t.splice.apply(t,o)}let n=new Uint8Array(e+16);for(s=0;s<t.length;s++){t[s]===""&&(t[s]="0");let o=parseInt(t[s],16);if(isNaN(o)||o<0||o>65535)throw new yt("Invalid byte value in IP address");n[e++]=o>>8&255,n[e++]=o&255}return n},Bb=function(r){if(r.byteLength!==4)throw new yt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Fb=function(r){if(r.byteLength!==16)throw new yt("IPv6 address was incorrect length");let e=[];for(let s=0;s<r.byteLength;s+=2){let n=r[s],o=r[s+1],i=`${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let s=new URL(`http://[${t}]`);return s.hostname.substring(1,s.hostname.length-1)}catch{throw new yt(`Invalid IPv6 address "${t}"`)}};function Ub(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new yt(`Invalid IPv6 address "${r}"`)}}var e2=Object.values(Ta).map(r=>r.decoder),tT=(function(){let r=e2[0].or(e2[1]);return e2.slice(2).forEach(e=>r=r.or(e)),r})();function Kb(r){return tT.decode(r)}function Hb(r){return e=>r.encoder.encode(e)}function rT(r){if(parseInt(r).toString()!==r)throw new Cs("Value must be an integer")}function sT(r){if(r<0)throw new Cs("Value must be a positive integer, or zero")}function nT(r){return e=>{if(e>r)throw new Cs(`Value must be smaller than or equal to ${r}`)}}function oT(...r){return e=>{for(let t of r)t(e)}}var dc=oT(rT,sT,nT(65535));var dt=-1,o2=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 Lu(`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(s=>{this.protocolsByName.delete(s)}))}},Kt=new o2,xT=[{code:4,name:"ip4",size:32,valueToBytes:n2,bytesToValue:Bb,validate:r=>{if(!(0,$e.isIPv4)(r))throw new Cs(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Wn,bytesToValue:_i,validate:dc},{code:273,name:"udp",size:16,valueToBytes:Wn,bytesToValue:_i,validate:dc},{code:33,name:"dccp",size:16,valueToBytes:Wn,bytesToValue:_i,validate:dc},{code:41,name:"ip6",size:128,valueToBytes:Nb,bytesToValue:Fb,stringToValue:Ub,validate:r=>{if(!(0,$e.isIPv6)(r))throw new Cs(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:dt},{code:43,name:"ipcidr",size:8,bytesToValue:t2("base10"),valueToBytes:r2("base10")},{code:53,name:"dns",size:dt,resolvable:!0},{code:54,name:"dns4",size:dt,resolvable:!0},{code:55,name:"dns6",size:dt,resolvable:!0},{code:56,name:"dnsaddr",size:dt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Wn,bytesToValue:_i,validate:dc},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:dt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:dt,bytesToValue:t2("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?r2("base58btc")(r):Re.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:s2,valueToBytes:Rb},{code:445,name:"onion3",size:296,bytesToValue:s2,valueToBytes:Lb},{code:446,name:"garlic64",size:dt},{code:447,name:"garlic32",size:dt},{code:448,name:"tls"},{code:449,name:"sni",size:dt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:dt,bytesToValue:Hb(_f),valueToBytes:Kb},{code:480,name:"http"},{code:481,name:"http-path",size:dt,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:dt}];xT.forEach(r=>{Kt.addProtocol(r)});function zb(r){let e=[],t=0;for(;t<r.length;){let s=ms(r,t),n=Kt.getProtocol(s),o=Ue(s),i=vT(n,r,t+o),a=0;i>0&&n.size===dt&&(a=Ue(i));let c=o+a+i,l={code:s,name:n.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,h=r.subarray(u,u+i);l.value=n.bytesToValue?.(h)??U(h)}e.push(l),t+=c}return e}function qb(r){let e=0,t=[];for(let s of r){if(s.bytes==null){let n=Kt.getProtocol(s.code),o=Ue(s.code),i,a=0,c=0;s.value!=null&&(i=n.valueToBytes?.(s.value)??R(s.value),a=i.byteLength,n.size===dt&&(c=Ue(a)));let l=new Uint8Array(o+c+a),u=0;$o(s.code,l,u),u+=o,i!=null&&(n.size===dt&&($o(a,l,u),u+=c),l.set(i,u)),s.bytes=l}t.push(s.bytes),e+=s.bytes.byteLength}return st(t,e)}function $b(r){if(r.charAt(0)!=="/")throw new yt('String multiaddr must start with "/"');let e=[],t="protocol",s="",n="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?n+=r.charAt(o):s+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=Kt.getProtocol(n);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),s="",n="",t="protocol";continue}else if(a)throw new yt(`Component ${n} 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(s==="")throw new yt(`Component ${n} was missing value`);l.value=c.stringToValue?.(s)??s}e.push(l),s="",n="",t="protocol"}}}if(n!==""&&s!=="")throw new yt("Incomplete multiaddr");return e}function Gb(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Kt.getProtocol(e.code);if(t==null)throw new yt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function vT(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ms(e,t)}var ET=Symbol.for("nodejs.util.inspect.custom"),m2=Symbol.for("@multiformats/multiaddr"),ST=[53,54,55,56],p2=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function IT(r){if(r==null&&(r="/"),ln(r))return r.getComponents();if(r instanceof Uint8Array)return zb(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),$b(r);if(Array.isArray(r))return r;throw new yt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Uu=class r{[m2]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=IT(e),t.validate!==!1&&_T(this)}get bytes(){return this.#r==null&&(this.#r=qb(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Gb(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,s,n,o="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(o=`%${l??""}`),ST.includes(a)&&(t="tcp",n=443,s=`${l??""}${o}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",n=parseInt(l??"")),(a===4||a===41)&&(t="tcp",s=`${l??""}${o}`,e=a===41?6:4);if(e==null||t==null||s==null||n==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:s,transport:t,port:n}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let s=Kt.getProtocol(e);return{code:e,size:s.size??0,name:s.name,resolvable:!!s.resolvable,path:!!s.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 s=Kt.getProtocol(e),n=[e];return t!=null&&n.push(s.valueToBytes?.(t)??R(t)),n})}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(),s=this.toString(),n=s.lastIndexOf(t);if(n<0)throw new hc(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(s.slice(0,n),{validate:!1})}decapsulateCode(e){let t;for(let s=this.#e.length-1;s>-1;s--)if(this.#e[s].code===e){t=s;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:s,value:n})=>{s===421&&e.push([s,n]),s===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let s=t[1];return s[0]==="Q"||s[0]==="1"?U(ye.decode(`z${s}`),"base58btc"):U(Re.parse(s).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(Kt.getProtocol(e.code).path)return e.value??null;return null}equals(e){return de(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let s=Vb.get(t.name);if(s==null)throw new p2(`no available resolver for ${t.name}`);return(await s(this,e)).map(o=>q(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)}[ET](){return`Multiaddr(${this.toString()})`}};function _T(r){r.getComponents().forEach(e=>{let t=Kt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}var Ku=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,s=e();return s===void 0&&(this.index=t),s}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,s){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return s()})}readNumber(e,t,s,n){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*n)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let d=Number.parseInt(h,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!s&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let s=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(s===void 0)return;e[t]=s}return e})}readIPv6Addr(){let e=t=>{for(let s=0;s<t.length/2;s++){let n=s*2;if(s<t.length-3){let i=this.readSeparator(":",s,()=>this.readIPv4Addr());if(i!==void 0)return t[n]=i[0],t[n+1]=i[1],t[n+2]=i[2],t[n+3]=i[3],[n+4,!0]}let o=this.readSeparator(":",s,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[n,!1];t[n]=o>>8,t[n+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[s,n]=e(t);if(s===16)return t;if(n||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(s+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Wb=45,AT=15,Pi=new Ku;function jb(r){if(!(r.length>AT))return Pi.new(r).parseWith(()=>Pi.readIPv4Addr())}function Yb(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Wb))return Pi.new(r).parseWith(()=>Pi.readIPv6Addr())}function pc(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Wb)return;let t=Pi.new(r).parseWith(()=>Pi.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 Xb(r,e,t){let s=0;for(let n of r)if(!(s<e)){if(s>t)break;if(n!==255)return!1;s++}return!0}function Zb(r,e,t,s){let n=0;for(let o of r)if(!(n<t)){if(n>s)break;if(o!==e[n])return!1;n++}return!0}function g2(r){switch(r.length){case Qn:return r.join(".");case Jn:{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 Qb(r){let e=0;for(let[t,s]of r.entries()){if(s===255){e+=8;continue}for(;(s&128)!=0;)e++,s=s<<1;if((s&128)!=0)return-1;for(let n=t+1;n<r.length;n++)if(r[n]!=0)return-1;break}return e}function Jb(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Qn=4,Jn=16,r$=parseInt("0xFFFF",16),TT=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function mc(r,e){e.length===Jn&&r.length===Qn&&Xb(e,0,11)&&(e=e.slice(12)),e.length===Qn&&r.length===Jn&&Zb(r,TT,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let s=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=r[n]&e[n];return s}function e4(r,e){if(typeof e=="string"&&(e=pc(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 y2(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let s=Qn,n=jb(e);if(n==null&&(s=Jn,n=Yb(e),n==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>s*8)throw new Error("Failed to parse given CIDR: "+r);let i=b2(o,8*s);return{network:mc(n,i),mask:i}}function b2(r,e){if(e!==8*Qn&&e!==8*Jn)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,s=new Uint8Array(t);for(let n=0;n<t;n++){if(r>=8){s[n]=255,r-=8;continue}s[n]=255-(255>>r),r=0}return s}var eo=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=y2(e));else{let s=pc(e);if(s==null)throw new Error("Failed to parse network");t=String(t);let n=parseInt(t,10);if(Number.isNaN(n)||String(n).length!==t.length||n<0||n>s.length*8){let o=pc(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=b2(n,8*s.length);this.network=mc(s,this.mask)}}contains(e){return e4({network:this.network,mask:this.mask},e)}toString(){let e=Qb(this.mask),t=e!==-1?String(e):Jb(this.mask);return g2(this.network)+"/"+t}};function t4(r,e){return new eo(r).contains(e)}be();Pe();function w2(r){let e,t;if(r.getComponents().forEach(s=>{(s.name==="ip4"||s.name==="ip6")&&(t=s.value),s.name==="ipcidr"&&(e=s.value)}),e==null||t==null)throw new Error("Invalid multiaddr");return new eo(t,e)}function r4(r,e){return Kt.getProtocol(r).bytesToValue?.(e)??U(e,"base16")}var Vb=new Map;function ln(r){return!!r?.[m2]}function q(r){return new Uu(r)}function ki(r){let e=Kt.getProtocol(r);return{code:e.code,size:e.size??0,name:e.name,resolvable:!!e.resolvable,path:!!e.path}}function Hu(r,e){let t=Math.max(r.length,e.length),s=new Uint8Array(t);for(let n=0;n<t;n++){let o=r[r.length-1-n]??0,i=e[e.length-1-n]??0;s[t-1-n]=o^i}return s}function x2(r,e){let t=Math.max(r.length,e.length);for(let s=0;s<t;s++){let n=r[s]??0,o=e[s]??0;if(n<o)return!0;if(n>o)return!1}return!1}function s4(r){for(let e=0;e<r.length;e++)if(r[e]!==0)return e;return Number.POSITIVE_INFINITY}function CT(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 n4(r,e,t,s){return x2(e,s)?!0:x2(s,e)?!1:r<t}function zu(r,e,t,s,n,o=1){let i,a=[];for(let u of t){let h=r.getById(u);if(!h)continue;let d=Hu(h.coord,e),f=s(u),p=(f?1:0)+.25*n(u);a.push({id:u,dist:d,connected:f,score:p}),(!i||n4(u,d,i.id,i.dist))&&(i={id:u,dist:d})}if(!i)return;let c=s4(i.dist),l;for(let u of a){if(!u.connected)continue;if(s4(u.dist)<=c+o){if(!l){l={id:u.id,dist:u.dist,score:u.score};continue}n4(u.id,u.dist,l.id,l.dist)?l={id:u.id,dist:u.dist,score:u.score}:CT(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 o4(r=12,e=.08,t=.03,s=.6,n=.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:s,sMin:n,sMax:o,eps:i}}function qu(r,e){let t=Hu(r,e),s=0;for(let o=0;o<t.length;o++){let i=t[o]??0;if(i===0){s+=8;continue}let a=7-Math.floor(Math.log2(i));s+=a;break}return 1-Math.min(256,s)/256}function i4(r,e){let t=r/Math.max(1e-9,e);return Math.exp(-.5*t*t)}function v2(r,e){for(let t=0;t<r.centers.length;t++){let s=i4(Math.abs(e-r.centers[t]),r.sigma);r.occupancy[t]=(1-r.alpha)*r.occupancy[t]+r.alpha*s}}function E2(r,e){let t=0,s=0;for(let i=0;i<r.centers.length;i++){let a=i4(Math.abs(e-r.centers[i]),r.sigma);t+=r.occupancy[i]*a,s+=1*a}let n=(s+r.eps)/(t+r.eps),o=Math.pow(n,r.beta);return Math.max(r.sMin,Math.min(r.sMax,o))}function PT(r,e){let t=Math.max(0,e-r.lastAccess),n=Math.log(2)/Math.max(1,6e4);return Math.exp(-n*t)}function kT(r){return Math.log1p(r.accessCount)/5}function DT(r){let e=r.successCount+r.failureCount,t=e>0?r.successCount/e:.5,s=r.avgLatencyMs>0?Math.min(1,r.avgLatencyMs/1e3):.5,n=.5*t+.5*(1-s);return Math.max(0,n)}function S2(r,e){return .4*PT(r,e)+.2*kT(r)+.4*DT(r)}function I2(r,e){return{...r,...e}}function a4(r,e,t,s=Date.now()){v2(t,e);let n=S2(r,s),o=E2(t,e),i=n*o;return I2(r,{lastAccess:s,relevance:i,accessCount:r.accessCount+1})}function c4(r,e,t,s,n=Date.now()){v2(s,t);let o=.2,i=r.avgLatencyMs>0?(1-o)*r.avgLatencyMs+o*e:e,a=S2({...r,avgLatencyMs:i,successCount:r.successCount+1},n),c=E2(s,t),l=a*c;return I2(r,{lastAccess:n,relevance:l,successCount:r.successCount+1,avgLatencyMs:i})}function l4(r,e,t,s=Date.now()){v2(t,e);let n=S2({...r,failureCount:r.failureCount+1},s)*.7,o=E2(t,e),i=n*o;return I2(r,{lastAccess:s,relevance:i,failureCount:r.failureCount+1})}var Br=an("service:fret"),Di=class{mode="passive";store=new Ou;cfg;node;stabilizing=!1;inflightAct=0;bucketNeighbors;bucketMaybeAct;bucketDiscovery;announcedIds=new Map;postBootstrapAnnounced=!1;sparsity=o4();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=Sb(this.cfg.networkName),this.bucketDiscovery=new Ii(this.cfg.profile==="core"?50:10,this.cfg.profile==="core"?25:3),this.bucketNeighbors=new Ii(this.cfg.profile==="core"?20:8,this.cfg.profile==="core"?10:4),this.bucketMaybeAct=new Ii(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 s=this.store.protectedIdsAround(t,Math.max(2,this.cfg.m)),n=this.store.list();n.sort((o,i)=>o.relevance-i.relevance);for(let o of n){if(this.store.size()<=e)break;s.has(o.id)||this.store.remove(o.id)}}async applyTouch(e,t){let s=this.store.getById(e)??this.store.upsert(e,t),n=qu(await this.selfCoord(),t),o=a4(s,n,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,accessCount:o.accessCount})}async applySuccess(e,t,s){let n=this.store.getById(e)??this.store.upsert(e,t),o=qu(await this.selfCoord(),t),i=c4(n,s,o,this.sparsity);this.store.update(e,{lastAccess:i.lastAccess,relevance:i.relevance,successCount:i.successCount,avgLatencyMs:i.avgLatencyMs})}async applyFailure(e,t){let s=this.store.getById(e)??this.store.upsert(e,t),n=qu(await this.selfCoord(),t),o=l4(s,n,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){Br("postBootstrap announce failed - %o",t)}}}),this.node.addEventListener("peer:connect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let s=this.store.getById(t)?.coord??await qe(G(t));this.store.setState(t,"connected"),await this.applyTouch(t,s)}catch(t){Br("peer:connect handler failed - %o",t)}}),this.node.addEventListener("peer:disconnect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let s=this.store.getById(t)?.coord??await qe(G(t));this.store.setState(t,"disconnected"),await this.applyFailure(t,s)}catch(t){Br("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(){_b(this.node,async()=>this.handleNeighborsRequest(),(e,t)=>{this.mergeAnnounceSnapshot(e,t)},this.protocols),Cb(this.node,async e=>this.handleMaybeAct(e),this.protocols.PROTOCOL_MAYBE_ACT),Db(this.node,async e=>this.handleLeave(e.from),this.protocols.PROTOCOL_LEAVE),Ob(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(s){return console.error("routeAct failed:",s),await this.nearAnchorOnly(e)}finally{this.inflightAct--}}isConnected(e){try{return this.node.getConnections(G(e)).length>0}catch{return!1}}hasAddresses(e){try{let t=this.node.getMultiaddrsForPeer?.(G(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),s=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(t,"right",this.cfg.m),...this.getNeighbors(t,"left",this.cfg.m)])).filter(i=>i!==s).slice(0,e),o=await this.snapshot();for(let i of n)if(this.isConnected(i)||this.hasAddresses(i))try{await Q0(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(),s=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(n=>n!==t);for(let n of s)if(this.isConnected(n)||this.hasAddresses(n))try{await uc(this.node,n,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(o){Br("preconnectNeighbors ping failed for %s - %o",n,o)}}catch(e){Br("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(),s=this.node.peerId.toString(),n=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!==s).slice(0,n);for(let i of o)if(this.isConnected(i)||this.hasAddresses(i))try{await uc(this.node,i,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(a){Br("active preconnect ping failed for %s - %o",i,a)}}catch(t){Br("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(),s=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),n={v:1,from:this.node.peerId.toString(),timestamp:Date.now()};for(let o of s)try{await Mb(this.node,o,n,this.protocols.PROTOCOL_LEAVE)}catch(i){Br("sendLeave failed for %s - %o",o,i)}}catch(e){Br("sendLeaveToNeighbors outer failed - %o",e)}}async handleLeave(e){try{let t=null,s=this.store.getById(e);if(s)t=s.coord;else try{t=await qe(G(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 n=Array.from(new Set([...this.store.neighborsRight(t,this.cfg.m),...this.store.neighborsLeft(t,this.cfg.m)])),o=this.expandCohort(n,t,Math.max(2,Math.ceil(this.cfg.m/2))),i=new Set(n),a=o.filter(l=>!i.has(l)),c=a.slice(0,Math.min(a.length,6));for(let l of c)try{if(await uc(this.node,l,this.protocols.PROTOCOL_PING),!this.isConnected(l)){let u=await this.snapshot();await Q0(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 s=G(e),n=await qe(s),o=[];this.store.getById(e)||o.push(e),this.store.upsert(e,n),await this.applyTouch(e,n),t.metadata&&this.store.update(e,{metadata:t.metadata});for(let i of[...t.successors??[],...t.predecessors??[]])try{let a=await qe(G(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=R(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){Br("mergeAnnounceSnapshot sample upsert failed for %s - %o",i.id,a)}this.enforceCapacity(),this.emitDiscovered(o)}catch(s){console.warn("mergeAnnounceSnapshot failed for",e,s)}}async seedFromPeerStore(){try{let e=this.node.peerStore?.getPeers?.()??[],t=[];for(let s of e)try{let n=await qe(s.id),o=s.id.toString();this.store.getById(o)||t.push(o),this.store.upsert(o,n)}catch(n){console.warn("failed to add peer from peerStore",s?.id?.toString?.(),n)}try{let s=await qe(this.node.peerId),n=this.node.peerId.toString();this.store.getById(n)||t.push(n),this.store.upsert(n,s)}catch(s){console.error("failed to add self to store",s)}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 s=t;if(t.startsWith("/"))try{let a=q(t).getPeerId();a&&(s=a)}catch{}let n=G(s),o=await qe(n);this.store.getById(s)||e.push(s),this.store.upsert(s,o),await this.applyTouch(s,o)}catch(s){console.warn("seedFromBootstraps failed for",t,s)}this.enforceCapacity(),this.emitDiscovered(e)}async stabilizeOnce(){let e=await qe(this.node.peerId),t=this.node.peerId.toString(),n=this.getNeighbors(e,"both",Math.max(2,this.cfg.m)).filter(o=>o!==t&&(this.isConnected(o)||this.hasAddresses(o)));await this.probeNeighborsLatency(n.slice(0,4)),await this.mergeNeighborSnapshots(n.slice(0,4))}async probeNeighborsLatency(e){for(let t of e)try{let s=await uc(this.node,t,this.protocols.PROTOCOL_PING);if(this.diag.pingsSent++,s.ok){let n=this.store.getById(t)?.coord??await qe(G(t));await this.applySuccess(t,n,s.rttMs),this.diag.pingsOk++}else{let n=this.store.getById(t)?.coord??await qe(G(t));await this.applyFailure(t,n),this.diag.pingsFail++}}catch{try{let n=this.store.getById(t)?.coord??await qe(G(t));await this.applyFailure(t,n),this.diag.pingsFail++}catch{}}}async mergeNeighborSnapshots(e){let t=[];for(let s of e)try{let n=await Ab(this.node,s,this.protocols.PROTOCOL_NEIGHBORS);this.diag.snapshotsFetched++;let o=this.cfg.profile==="core"?16:8,i=this.cfg.profile==="core"?16:8,a=(n.successors??[]).slice(0,o),c=(n.predecessors??[]).slice(0,i);for(let u of[...a,...c])try{let h=await qe(G(u));this.store.getById(u)||t.push(u),this.store.upsert(u,h),await this.applyTouch(u,h)}catch(h){console.warn("failed to merge neighbor",u,h)}let l=this.cfg.profile==="core"?8:6;for(let u of(n.sample??[]).slice(0,l))try{let h=R(u.coord,"base64url");this.store.getById(u.id)||t.push(u.id),this.store.upsert(u.id,h),await this.applyTouch(u.id,h)}catch(h){Br("mergeNeighborSnapshots sample upsert failed for %s - %o",u.id,h)}}catch(n){console.warn("fetchNeighbors failed for",s,n)}this.enforceCapacity(),this.emitDiscovered(t)}async snapshot(){let e=await qe(this.node.peerId),{n:t,confidence:s}=Ru(this.store,this.cfg.m),n=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,n),u=c.slice(0,o),h=Array.from(new Set([...l.slice(0,4),...u.slice(0,4)])).slice(0,i),d=await Promise.all(h.map(async f=>{let p=this.store.getById(f);return p?{id:f,coord:Eb(p.coord),relevance:p.relevance}:{id:f,coord:"",relevance:0}}));return{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:l,predecessors:u,sample:d,size_estimate:t,confidence:s,sig:"",metadata:this.metadata}}neighborDistance(e,t,s){let n=new Set,o=Math.max(1,s),a=this.assembleCohort(t,o,n).findIndex(c=>c===e);return a>=0?a:Number.POSITIVE_INFINITY}getNeighbors(e,t,s){let n=[];return(t==="right"||t==="both")&&n.push(...this.store.neighborsRight(e,s)),(t==="left"||t==="both")&&n.push(...this.store.neighborsLeft(e,s)),Array.from(new Set(n)).slice(0,s)}nextSuccessor(e,t){let s=t.findIndex(n=>n.id===e.id);return t[(s+1)%t.length]}nextPredecessor(e,t){let s=t.findIndex(n=>n.id===e.id);return t[(s-1+t.length)%t.length]}assembleCohort(e,t,s){let n=[],o=s??new Set,i=this.store.neighborsRight(e,t*2),a=this.store.neighborsLeft(e,t*2),c=0,l=0;for(;n.length<t&&(c<i.length||l<a.length);)if(n.length%2===0){let u=i[c++];u&&!o.has(u)&&n.push(u)}else{let u=a[l++];u&&!o.has(u)&&n.push(u)}return Array.from(new Set(n)).slice(0,t)}expandCohort(e,t,s,n){let o=new Set(e),i=this.assembleCohort(t,e.length+s,n);for(let a of i)o.add(a);return Array.from(o)}async nearAnchorOnly(e){let t=R(e.key,"base64url"),s=await rr(t),n=this.getNeighbors(s,"right",this.cfg.m),o=this.getNeighbors(s,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...n.slice(0,3),...o.slice(0,3)]),cohort_hint:Array.from(new Set([...n.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(),s=this.cfg.profile==="core"?10*6e4:30*6e4,n=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=G(i);n.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:c,multiaddrs:[]}})),this.announcedIds.set(i,t+s),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 s=c=>.5,n=new Uint8Array(32),o=zu(this.store,n,t,c=>this.isConnected(c),s),i=t.filter(c=>c!==o),a=zu(this.store,n,i,c=>this.isConnected(c),s);return[o,a].filter(c=>!!c)}async routeAct(e){let t=R(e.key,"base64url"),s=await rr(t),n=this.node.peerId.toString();if(this.neighborDistance(n,s,2)>1&&e.ttl>0){let h=new Set([...e.breadcrumbs??[],n]),d=this.assembleCohort(s,Math.max(4,this.cfg.m)).filter(m=>!h.has(m)),f=m=>.5,p=zu(this.store,s,d,m=>this.isConnected(m),f);if(p){let m={...e,ttl:e.ttl-1,breadcrumbs:[...e.breadcrumbs??[],n]};try{return await Pb(this.node,p,m,this.protocols.PROTOCOL_MAYBE_ACT)}catch(g){console.warn("forward maybeAct failed to",p,g)}}}let{n:i,confidence:a}=Ru(this.store,this.cfg.m),c=this.getNeighbors(s,"right",this.cfg.m),l=this.getNeighbors(s,"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,s="external"){let n=Date.now();this.networkObservations.push({estimate:e,confidence:t,timestamp:n,source:s});let o=n-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=Ru(this.store,this.cfg.m),t=Date.now(),s=[{estimate:e.n,confidence:e.confidence,timestamp:t,source:"fret"},...this.networkObservations];if(s.length===0)return{size_estimate:0,confidence:0,sources:0};let n=0,o=0,i=0;for(let l of s){let u=t-l.timestamp,h=Math.exp(-u/(this.observationWindowMs/3)),d=h*l.confidence;o+=l.estimate*d,i+=l.confidence*h,n+=d}if(n===0)return{size_estimate:0,confidence:0,sources:0};let a=Math.round(o/n),c=i/s.length;return{size_estimate:a,confidence:Math.min(1,c),sources:s.length}}getNetworkChurn(){if(this.networkObservations.length<2)return 0;let e=Date.now(),t=this.observationWindowMs/2,s=e-t,n=this.networkObservations.filter(l=>l.timestamp>s),o=this.networkObservations.filter(l=>l.timestamp<=s);if(n.length===0||o.length===0)return 0;let i=n.reduce((l,u)=>l+u.estimate,0)/n.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,s=this.networkObservations.filter(c=>c.timestamp<t);if(s.length<3)return!1;let n=s.slice(-5).reduce((c,l)=>c+l.estimate,0)/Math.min(5,s.length);if(e.size_estimate/n<.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}))}};ce();var MT=an("service:discovery");function _2(r,e){let t=r;for(let s of e.list())try{let n=G(s.id);t.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:n,multiaddrs:[]}}))}catch(n){MT("seedDiscovery failed for %s - %o",s.id,n)}}var $u=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 Di(this.nodeRef,this.cfg)}return this.inner}async start(){if(this.ensure(),!this.nodeRef)throw new Error("Libp2pFretService.start: libp2p node not injected");_2(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,s){return this.ensure().getNeighbors(e,t,s)}assembleCohortForKey(e,t){return this.ensure().assembleCohort(e,t)}getDiagnostics(){return this.ensure().getDiagnostics?.()}neighborDistance(e,t,s){return this.ensure().neighborDistance(e,t,s)}getNeighbors(e,t,s){return this.ensure().getNeighbors(e,t,s)}assembleCohort(e,t,s){return this.ensure().assembleCohort(e,t,s)}expandCohort(e,t,s,n){return this.ensure().expandCohort(e,t,s,n)}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 A2(r){return e=>new $u(e,r)}ce();var u4="/db-p2p/sync/",h4="1.0.0",gc=(r="")=>`${r}${u4}${h4}`;var yc=class extends gs{protocol;constructor(e,t,s=""){super(e,t),this.protocol=gc(s)}async requestBlock(e){return await this.processMessage(e,this.protocol)}getProtocol(){return this.protocol}};var bc=class{fretAdapter;peerNetwork;protocolPrefix;metrics={totalRequests:0,successByRing:new Map,failureByRing:new Map,averageDurationMs:0};constructor(e,t,s){this.fretAdapter=e,this.peerNetwork=t,this.protocolPrefix=s}log=yr("storage:restoration");async restore(e,t){let s=Date.now();this.metrics.totalRequests++;let n=await this.getMyRingPeers(e),o=this.getMyRingDepth();for(let a of n){let c=await this.queryPeer(a,e,t);if(c)return this.recordSuccess(o,e,Date.now()-s),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 h=await this.queryPeer(u,e,t);if(h)return this.recordSuccess(a,e,Date.now()-s),h}}let i=Date.now()-s;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),s=await rr(t);return this.fretAdapter.getFret().assembleCohort(s,10)}getMyRingDepth(){return this.fretAdapter.getMyArachnodeInfo()?.ringDepth??8}filterByPartition(e,t,s){if(s===0)return e;let n=this.extractBlockPrefix(t,s);return e.filter(o=>{let i=this.fretAdapter.getArachnodeInfo(o);return!i||!i.partition?!1:i.partition.prefixValue===n})}extractBlockPrefix(e,t){let s=new TextEncoder().encode(e),n=new Uint8Array(32);for(let i=0;i<Math.min(s.length,n.length);i++)n[i]=s[i];let o=0;for(let i=0;i<t;i++){let a=Math.floor(i/8),c=7-i%8,l=n[a]>>c&1;o=o<<1|l}return o}async queryPeer(e,t,s){try{let n=G(e),i=await new yc(n,this.peerNetwork,this.protocolPrefix).requestBlock({blockId:t,rev:s});return i.success?i.archive:void 0}catch(n){this.log("queryPeer failed for %s - %o",e,n);return}}recordSuccess(e,t,s){let n=this.metrics.successByRing.get(e)??0;this.metrics.successByRing.set(e,n+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+s)/o,console.log(`[Ring ${e}] Successfully restored block ${t} in ${s}ms`)}getMetrics(){return{...this.metrics}}};var wc=class{fretAdapter;storageMonitor;config;constructor(e,t,s){this.fretAdapter=e,this.storageMonitor=t,this.config=s}async determineRing(){let e=await this.storageMonitor.getCapacity();if(e.available<this.config.minCapacity)return-1;let n=1e3*(100*1024),o=e.available/n,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 s=await qe({toString:()=>t}),n=e,o=this.extractPrefix(s,n);return{prefixBits:n,prefixValue:o}}async createArachnodeInfo(e){let t=await this.storageMonitor.getCapacity(),s=await this.determineRing(),n=s>=0?await this.calculatePartition(s,e):void 0;return{ringDepth:Math.max(0,s),partition:n,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 s=await this.determineRing();if(s>0)return{shouldMove:!0,direction:"in",newRingDepth:s-1}}return{shouldMove:!1}}extractPrefix(e,t){let s=0;for(let n=0;n<t;n++){let o=Math.floor(n/8),i=7-n%8,a=e[o]>>i&1;s=s<<1|a}return s}};var xc=class{storage;config;constructor(e,t={}){this.storage=e,this.config=t}async getCapacity(){let t=this.config.totalBytes??10737418240,s=this.config.usedBytes,n=this.config.availableBytes;if(s!==void 0||n!==void 0||this.config.totalBytes!==void 0){let a=s??Math.max(0,t-(n??t)),c=n??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 vc=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(s=>s.metadata?.[r.ARACHNODE_KEY]?.ringDepth===e).map(s=>s.id)}getKnownRings(){let e=this.fret.listPeers(),t=new Set;for(let s of e){let n=s.metadata?.[r.ARACHNODE_KEY];n?.ringDepth!==void 0&&t.add(n.ringDepth)}return Array.from(t).sort((s,n)=>s-n)}getRingStats(){let e=this.fret.listPeers(),t=new Map;for(let s of e){let n=s.metadata?.[r.ARACHNODE_KEY];if(n){let o=t.get(n.ringDepth)??{count:0,totalCapacity:0};t.set(n.ringDepth,{count:o.count+1,totalCapacity:o.totalCapacity+n.capacity.available})}}return Array.from(t.entries()).map(([s,n])=>({ringDepth:s,peerCount:n.count,avgCapacity:n.totalCapacity/n.count})).sort((s,n)=>s.ringDepth-n.ringDepth)}getFret(){return this.fret}};be();Pe();var Gu=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=gc(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 s=await this.buildArchive(t.blockId,t.rev,t.includePending,t.maxRevisions),n=s?{success:!0,archive:s,responderId:e.id}:{success:!1,error:"Block not found in local storage"};await this.sendResponse(e,n),this.log("[Ring Zulu] %s sync request for block %s",n.success?"Fulfilled":"Failed",t.blockId)}catch(t){this.log.error("Error handling sync request:",t);try{let s={success:!1,error:t instanceof Error?t.message:"Unknown error"};await this.sendResponse(e,s)}catch(s){this.log.error("Failed to send error response:",s)}}finally{try{await e.close()}catch{}}}async readRequest(e){let t=[];if(await Qe(e.source,Zt,async n=>{for await(let o of n)t.push(o.subarray())}),t.length===0)throw new Error("No request received");let s=U(t[0],"utf8");return JSON.parse(s)}async sendResponse(e,t){let s=JSON.stringify(t),n=R(s,"utf8");await Qe([n],dr,e.sink)}async buildArchive(e,t,s,n){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}}},T2=(r={})=>e=>new Gu(e,r);Pe();ce();var Ec=class r{libp2p;clusterSize;selfCoordinationConfig;networkHighWaterMark=1;lastConnectedTime=Date.now();constructor(e,t=16,s){this.libp2p=e,this.clusterSize=t,this.selfCoordinationConfig={gracePeriodMs:s?.gracePeriodMs??3e4,shrinkageThreshold:s?.shrinkageThreshold??.5,allowSelfCoordination:s?.allowSelfCoordination??!0},this.setupConnectionTracking()}coordinatorCache=new Map;static MAX_CACHE_ENTRIES=1e3;log=yr("libp2p-key-network");toCacheKey(e){return U(e,"base64url")}setupConnectionTracking(){this.libp2p.addEventListener("connection:open",()=>{this.updateNetworkObservations()})}updateNetworkObservations(){(this.libp2p.getConnections?.()??[]).length>0&&(this.lastConnectedTime=Date.now());try{let s=this.getFret().getNetworkSizeEstimate();s.size_estimate>this.networkHighWaterMark&&(this.networkHighWaterMark=s.size_estimate,this.log("network-hwm-updated mark=%d confidence=%f",this.networkHighWaterMark,s.confidence))}catch{let s=(this.libp2p.getConnections?.().length??0)+1;s>this.networkHighWaterMark&&(this.networkHighWaterMark=s,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 s=t.getNetworkSizeEstimate(),n=1-s.size_estimate/this.networkHighWaterMark;if(n>this.selfCoordinationConfig.shrinkageThreshold)return this.log("self-coord-blocked: suspicious-shrinkage current=%d hwm=%d shrinkage=%f",s.size_estimate,this.networkHighWaterMark,n),{allow:!1,reason:"suspicious-shrinkage"}}catch{let t=this.libp2p.getConnections?.()??[];if(this.networkHighWaterMark>1&&t.length===0){let s=Date.now()-this.lastConnectedTime;if(s<this.selfCoordinationConfig.gracePeriodMs)return this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",s),{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,s=1800*1e3){let n=this.toCacheKey(e),o=Date.now();for(let[i,a]of this.coordinatorCache)a.expires<=o&&this.coordinatorCache.delete(i);for(this.coordinatorCache.set(n,{id:t,expires:o+s});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),s=this.coordinatorCache.get(t);if(s&&s.expires>Date.now())return s.id;s&&this.coordinatorCache.delete(t)}connect(e,t,s){let n=this.libp2p.getConnections?.(e)??[];if(Array.isArray(n)&&n.length>0&&typeof n[0]?.newStream=="function")return n[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 s=this.getFret(),n=await rr(e),o=s.getNeighbors(n,"both",t);return Array.from(new Set(o)).slice(0,t)}async findCoordinator(e,t){let s=new Set((t?.excludedPeers??[]).map(l=>l.toString())),n=this.toCacheKey(e).substring(0,12);this.log("findCoordinator:start key=%s excluded=%o",n,Array.from(s).map(l=>l.substring(0,12)));let o=this.getCachedCoordinator(e);if(o!=null&&!s.has(o.toString()))return this.log("findCoordinator:cached-hit key=%s coordinator=%s",n,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),h=new Set(u.map(f=>f.toString()));this.log("findCoordinator:connected-peers key=%s count=%d peers=%o attempt=%d",n,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",n,f.map(g=>g.substring(0,12)));let p=f.filter(g=>h.has(g)||g===this.libp2p.peerId.toString());this.log("findCoordinator:fret-connected key=%s count=%d peers=%o",n,p.length,p.map(g=>g.substring(0,12)));let m=p.find(g=>!s.has(g));if(m){let g=G(m);return this.recordCoordinator(e,g),this.log("findCoordinator:fret-selected key=%s coordinator=%s",n,m.substring(0,12)),g}}catch(f){this.log("findCoordinator getNeighborIdsForKey failed - %o",f)}let d=u.find(f=>!s.has(f.toString()));if(d)return this.recordCoordinator(e,d),this.log("findCoordinator:connected-fallback key=%s coordinator=%s",n,d.toString().substring(0,12)),d;if(u.length===0&&l<i-1){this.log("findCoordinator:no-connections-retry key=%s attempt=%d delay=%dms",n,l,a),await new Promise(f=>setTimeout(f,a));continue}}let c=this.libp2p.peerId;if(!s.has(c.toString())){let l=this.shouldAllowSelfCoordination();if(!l.allow)throw this.log("findCoordinator:self-coord-blocked key=%s reason=%s",n,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",n,c.toString().substring(0,12),l.reason):this.log("findCoordinator:self-selected key=%s coordinator=%s reason=%s",n,c.toString().substring(0,12),l.reason),c}throw this.log("findCoordinator:all-excluded key=%s self=%s",n,c.toString().substring(0,12)),new Error("No coordinator available for key (all candidates excluded)")}getConnectedAddrsByPeer(){let e=this.libp2p.getConnections(),t={};for(let s of e){let n=s.remotePeer.toString(),o=s.remoteAddr?.toString?.();o&&(t[n]??=[]).push(o)}return t}parseMultiaddrs(e){let t=[];for(let s of e)try{t.push(q(s))}catch(n){console.warn("invalid multiaddr from connection",s,n)}return t}async findCluster(e){let t=this.getFret(),s=await rr(e),n=t.assembleCohort(s,this.clusterSize),o=this.toCacheKey(e).substring(0,12),i=Array.from(new Set([...n,this.libp2p.peerId.toString()])),a=this.getConnectedAddrsByPeer(),c=Object.keys(a);this.log("findCluster key=%s fretCohort=%d connected=%d cohortPeers=%o",o,n.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(),publicKey:this.libp2p.peerId.publicKey?.raw??new Uint8Array};continue}let h=a[u]??[],d=this.parseMultiaddrs(h);l[u]={multiaddrs: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}};lt();ce();X();function Mi(r){if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:f4}=Object.prototype,{propertyIsEnumerable:OT}=Object,Oi=(r,e,t)=>{Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})},RT=void 0,d4={concatArrays:!1,ignoreUndefined:!1},Vu=r=>{let e=[];for(let t in r)f4.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let s of t)OT.call(r,s)&&e.push(s)}return e};function Ri(r){return Array.isArray(r)?LT(r):Mi(r)?NT(r):r}function LT(r){let e=r.slice(0,0);return Vu(r).forEach(t=>{Oi(e,t,Ri(r[t]))}),e}function NT(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return Vu(r).forEach(t=>{Oi(e,t,Ri(r[t]))}),e}var p4=(r,e,t,s)=>(t.forEach(n=>{typeof e[n]>"u"&&s.ignoreUndefined||(n in r&&r[n]!==Object.getPrototypeOf(r)?Oi(r,n,C2(r[n],e[n],s)):Oi(r,n,Ri(e[n])))}),r),BT=(r,e,t)=>{let s=r.slice(0,0),n=0;return[r,e].forEach(o=>{let i=[];for(let a=0;a<o.length;a++)f4.call(o,a)&&(i.push(String(a)),o===r?Oi(s,n++,o[a]):Oi(s,n++,Ri(o[a])));s=p4(s,o,Vu(o).filter(a=>!i.includes(a)),t)}),s};function C2(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?BT(r,e,t):!Mi(e)||!Mi(r)?Ri(e):p4(r,e,Vu(e),t)}function Wu(...r){let e=C2(Ri(d4),this!==RT&&this||{},d4),t={_:{}};for(let s of r)if(s!==void 0){if(!Mi(s))throw new TypeError("`"+s+"` is not an Option Object");t=C2(t,{_:s},e)}return t._}var ke=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var g4=oe("dns/promises");function ju(r){let e=[_t.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}Pe();var P2=60;function Yu(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:_t[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:_t[e.type],TTL:e.TTL??e.ttl??P2,data:e.data instanceof Uint8Array?U(e.data):e.data}))}}var FT=async(r,e={})=>{let t=new g4.Resolver,s=()=>{t.cancel()},n=ju(e.types);try{e.signal?.addEventListener("abort",s);let o=await Promise.all(n.map(async i=>{if(i===_t.A)return Xu(r,i,await t.resolve4(r));if(i===_t.CNAME)return Xu(r,i,await t.resolveCname(r));if(i===_t.TXT)return Xu(r,i,await t.resolveTxt(r));if(i===_t.AAAA)return Xu(r,i,await t.resolve6(r));throw new TypeError("Unsupported DNS record type")}));return Yu({Question:n.map(i=>({name:r,type:i})),Answer:o.flat()})}finally{e.signal?.removeEventListener("abort",s)}};function y4(){return[FT]}function m4(r,e,t){return{name:r,type:e,data:t}}function Xu(r,e,t){return Array.isArray(t)||(t=[t]),t.map(s=>Array.isArray(s)?s.map(n=>m4(r,e,n)):m4(r,e,s)).flat()}var x4=xe(w4(),1);var k2=class{lru;constructor(e){this.lru=(0,x4.default)(e)}get(e,t){let s=!0,n=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){s=!1;break}n.push(...i)}if(s)return Yu({answers:n})}getAnswers(e,t){let s=`${e.toLowerCase()}-${t}`,n=this.lru.get(s);if(n!=null){let o=n.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:_t[a.type]}));return o.length===0&&this.lru.remove(s),o}return[]}add(e,t){let s=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(s)??[];n.push({expires:Date.now()+(t.TTL??P2)*1e3,value:t}),this.lru.set(s,n)}remove(e,t){let s=`${e.toLowerCase()}-${t}`;this.lru.remove(s)}clear(){this.lru.clear()}};function v4(r){return new k2(r)}var UT=1e3,Zu=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=v4(e.cacheSize??UT),Object.entries(e.resolvers??{}).forEach(([t,s])=>{Array.isArray(s)||(s=[s]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=s}),this.resolvers["."]==null&&(this.resolvers["."]=y4())}async query(e,t={}){let s=ju(t.types),n=t.cached!==!1?this.cache.get(e,s):void 0;if(n!=null)return t.onProgress?.(new ke("dns:cache",n)),n;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:s});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new ke("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${s} failed`)}};var _t;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(_t||(_t={}));function E4(r={}){return new Zu(r)}var D2=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let s=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(s==null)return[e];let o=await this.getDNS(t).query(`_dnsaddr.${s}`,{signal:t?.signal,types:[_t.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=E4()),this.dns)}},to=new D2;var KT={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:to}},transportManager:{faultTolerance:Nn.FATAL_ALL}};async function S4(r){let e=Wu(KT,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new V("Private network is enforced, but no protector was provided");return e}lt();X();Yo();Qt();Pl();var A4=xe(oe("node:tty"),1),rh=xe(oe("node:util"),1);function HT(r,e){if(typeof r=="string")return zT(r);if(typeof r=="number")return GT(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var Qu=HT;function zT(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:s="ms"}=e.groups,n=parseFloat(t),o=s.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return n*315576e5;case"months":case"month":case"mo":return n*26298e5;case"weeks":case"week":case"w":return n*6048e5;case"days":case"day":case"d":return n*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return n*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return n*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return n*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function qT(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 $T(r){let e=Math.abs(r);return e>=315576e5?ro(r,e,315576e5,"year"):e>=26298e5?ro(r,e,26298e5,"month"):e>=6048e5?ro(r,e,6048e5,"week"):e>=864e5?ro(r,e,864e5,"day"):e>=36e5?ro(r,e,36e5,"hour"):e>=6e4?ro(r,e,6e4,"minute"):e>=1e3?ro(r,e,1e3,"second"):`${r} ms`}function GT(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?$T(r):qT(r)}function ro(r,e,t,s){let n=e>=t*1.5;return`${Math.round(r/t)} ${s}${n?"s":""}`}var eh=xe(oe("node:process"),1),_4=xe(oe("node:os"),1),M2=xe(oe("node:tty"),1);function vr(r,e=globalThis.Deno?globalThis.Deno.args:eh.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",s=e.indexOf(t+r),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}var{env:Le}=eh.default,Ju;vr("no-color")||vr("no-colors")||vr("color=false")||vr("color=never")?Ju=0:(vr("color")||vr("colors")||vr("color=true")||vr("color=always"))&&(Ju=1);function VT(){if(!("FORCE_COLOR"in Le))return;if(Le.FORCE_COLOR==="true")return 1;if(Le.FORCE_COLOR==="false")return 0;if(Le.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(Le.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function WT(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function jT(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let s=VT();s!==void 0&&(Ju=s);let n=t?Ju:s;if(n===0)return 0;if(t){if(vr("color=16m")||vr("color=full")||vr("color=truecolor"))return 3;if(vr("color=256"))return 2}if("TF_BUILD"in Le&&"AGENT_NAME"in Le)return 1;if(r&&!e&&n===void 0)return 0;let o=n||0;if(Le.TERM==="dumb")return o;if(eh.default.platform==="win32"){let i=_4.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in Le)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in Le)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in Le)||Le.CI_NAME==="codeship"?1:o;if("TEAMCITY_VERSION"in Le)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Le.TEAMCITY_VERSION)?1:0;if(Le.COLORTERM==="truecolor"||Le.TERM==="xterm-kitty"||Le.TERM==="xterm-ghostty"||Le.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Le){let i=Number.parseInt((Le.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Le.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Le.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Le.TERM)||"COLORTERM"in Le?1:o}function I4(r,e={}){let t=jT(r,{streamIsTTY:r&&r.isTTY,...e});return WT(t)}var YT={stdout:I4({isTTY:M2.default.isatty(1)}),stderr:I4({isTTY:M2.default.isatty(2)})},th=YT;function O2(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=i,t.humanize=Qu,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let h=0;for(let d=0;d<u.length;d++)h=(h<<5)-h+u.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(u){let h,d=null,f,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(h||b);y.diff=w,y.prev=h,y.curr=b,h=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,(P,C)=>{if(P==="%%")return"%";x++;let D=t.formatters[C];if(typeof D=="function"){let v=g[x];P=D.call(y,v),g.splice(x,1),x--}return P}),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=s,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(u)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function s(u,h){let d=t(this.namespace+(typeof h>"u"?":":h)+u);return d.log=this.log,d}function n(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let h,d=(typeof u=="string"?u:"").split(/[\s,]+/),f=d.length;for(h=0;h<f;h++)d[h]&&(u=d[h].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(h=>"-"+h)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let h,d;for(h=0,d=t.skips.length;h<d;h++)if(t.skips[h].test(u))return!1;for(h=0,d=t.names.length;h<d;h++)if(t.names[h].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 T4=[6,2,3,4,5,1];th.stderr!==!1&&(th.stderr??th).level>=2&&(T4=[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 Li=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,o)=>o.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function XT(){return"colors"in Li?!!Li.colors:A4.default.isatty(process.stderr.fd)}function ZT(r){let{namespace:e,useColors:t}=this;if(t===!0){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),o=` ${n};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
7
7
  `).join(`
8
- `+o),r.push(n+"m+"+Tu(this.diff)+"\x1B[0m")}else r[0]=zA()+e+" "+r[0]}function zA(){return Ei.hideDate!=null?"":new Date().toISOString()+" "}function qA(...r){return process.stderr.write(Mu.default.format(...r)+`
9
- `)}function $A(r){r!=null?process.env.DEBUG=r:delete process.env.DEBUG}function GA(){return process.env.DEBUG}function VA(r){r.inspectOpts={};let e=Object.keys(Ei);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=Ei[e[t]]}function WA(r){r.o=function(e){return this.inspectOpts.colors=this.useColors,Mu.default.inspect(e,this.inspectOpts).split(`
10
- `).map(t=>t.trim()).join(" ")},r.O=function(e){return this.inspectOpts.colors=this.useColors,Mu.default.inspect(e,this.inspectOpts)}}var B4=X0({init:VA,log:qA,formatArgs:HA,save:$A,load:GA,useColors:KA,setupFormatters:WA,colors:N4,inspectOpts:Ei});var $t=B4;$t.formatters.b=r=>r==null?"undefined":me.baseEncode(r);$t.formatters.t=r=>r==null?"undefined":or.baseEncode(r);$t.formatters.m=r=>r==null?"undefined":Fd.baseEncode(r);$t.formatters.p=r=>r==null?"undefined":r.toString();$t.formatters.c=r=>r==null?"undefined":r.toString();$t.formatters.k=r=>r==null?"undefined":r.toString();$t.formatters.a=r=>r==null?"undefined":r.toString();$t.formatters.e=r=>r==null?"undefined":F4(r.stack)??F4(r.message)??r.toString();function jA(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 Ou(){return{forComponent(r){return U4(r)}}}function U4(r){let e=jA(`${r}:trace`);return $t.enabled(`${r}:trace`)&&$t.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=$t(`${r}:trace`)),Object.assign($t(r),{error:$t(`${r}:error`),trace:e,newScope:t=>U4(`${r}:${t}`)})}function F4(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}ce();Vt();ir();function $n(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let s=r.next(),n=s.value;return s.done===!0||n==null?{done:!0,value:void 0}:{done:!1,value:e(n)}}};return t}function Lu(r){let e=Ht(me.decode(`z${r}`));return Pr(e)}var pr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,s]of e.entries())this.map.set(t.toString(),{key:t,value:s})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return $n(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,s)=>{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 $n(this.map.values(),e=>e.key)}values(){return $n(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Gn=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 $n(this.set.entries(),e=>{let t=Lu(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let s=Lu(t);e(s,s,this)})}has(e){return this.set.has(e.toString())}values(){return $n(this.set.values(),e=>Lu(e))}intersection(e){let t=new r;for(let s of e)this.has(s)&&t.add(s);return t}difference(e){let t=new r;for(let s of this)e.has(s)||t.add(s);return t}union(e){let t=new r;for(let s of e)t.add(s);for(let s of this)t.add(s);return t}};m6();var Z0={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},K4={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},H4=new globalThis.TextEncoder;function YA(r,e){let t=Z0[e],s=K4[e];for(let n=0;n<r.length;n++)s^=BigInt(r[n]),s=BigInt.asUintN(e,s*t);return s}function XA(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let s=Z0[e],n=K4[e],o=r;for(;o.length>0;){let i=H4.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)n^=BigInt(t[a]),n=BigInt.asUintN(e,n*s)}return n}function Q0(r,{size:e=32,utf8Buffer:t}={}){if(!Z0[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 XA(r,e,t);r=H4.encode(r)}return YA(r,e)}ge();var ac={hash:r=>Number(Q0(r,{size:32})),hashV:(r,e)=>ZA(ac.hash(r,e))};function ZA(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}ge();nt();Kt();var J0=64,Mr=class{fp;h;seed;constructor(e,t,s,n=2){if(n>J0)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,s),i=ie(n);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=s}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ae(this.fp,e.fp):!1}};function Vn(r,e){return Math.floor(Math.random()*(e-r))+r}var Wn=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Mr))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Mr))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 Mr))throw new TypeError("Invalid Fingerprint");let t=Vn(0,this.contents.length-1),s=this.contents[t];return this.contents[t]=e,s}remove(e){if(!(e instanceof Mr))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(s=>e.equals(s));return t>-1?(this.contents[t]=null,!0):!1}};var QA=500,cc=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??ac,this.seed=e.seed??Vn(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new Mr(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,n=(s^t.hash())%this.filterSize;if(this.buckets[s]==null&&(this.buckets[s]=new Wn(this.bucketSize)),this.buckets[n]==null&&(this.buckets[n]=new Wn(this.bucketSize)),this.buckets[s].add(t)||this.buckets[n].add(t))return this.count++,!0;let o=[s,n],i=o[Vn(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Wn(this.bucketSize));for(let a=0;a<QA;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 Wn(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new Mr(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[s]?.has(t)??!1;if(n)return n;let o=(s^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new Mr(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[s]?.remove(t)??!1;if(n)return this.count--,n;let o=(s^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}},JA={1:.5,2:.84,4:.95,8:.98};function eC(r=.001){return r>.002?2:r>1e-5?4:8}function z4(r,e=.001){let t=eC(e),s=JA[t],n=Math.round(r/s),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),J0);return{filterSize:n,bucketSize:t,fingerprintSize:o}}ge();var Ru=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??ac,this.seed=e.seed??Vn(0,Math.pow(2,10)),this.filterSeries=[new cc({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(s=>s.reliable);if(t==null){let s=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new cc({filterSize:s,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function lc(r,e=.001,t){return new Ru({...z4(r,e),...t??{}})}var e2=class extends pr{metric;constructor(e){super();let{name:t,metrics:s}=e;this.metric=s.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 t2(r){let{name:e,metrics:t}=r,s;return t!=null?s=new e2({name:e,metrics:t}):s=new pr,s}ce();X();ce();ft();wr();ot();Kt();ge();zs();nt();var uc;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(s.uint32(10),s.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(s.uint32(18),s.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(s.uint32(26),s.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(s.uint32(42),s.bytes(t.signature)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={publicKey:ie(0),payloadType:ie(0),payload:ie(0),signature:ie(0)},i=s==null?t.len:t.pos+s;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=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(uc||(uc={}));var Nu=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Or=class r{static createFromProtobuf=e=>{let t=uc.decode(e),s=Je(t.publicKey);return new r({publicKey:s,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,s)=>{if(t==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,i=e.marshal(),a=q4(n,o,i),c=await t.sign(a.subarray(),s);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,s)=>{let n=r.createFromProtobuf(e);if(!await n.validate(t,s))throw new Nu("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:s,payload:n,signature:o}=e;this.publicKey=t,this.payloadType=s,this.payload=n,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=uc.encode({publicKey:Ve(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:ae(this.marshal(),e.marshal())}async validate(e,t){let s=q4(e,this.payloadType,this.payload);return this.publicKey.verify(s.subarray(),this.signature,t)}},q4=(r,e,t)=>{let s=L(r),n=rr(s.byteLength),o=rr(e.length),i=rr(t.length);return new W(n,s,o,e,i,t)};ce();function $4(r,e){let t=(s,n)=>s.toString().localeCompare(n.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((s,n)=>e[n].equals(s)))}ir();var G4="libp2p-peer-record",V4=Uint8Array.from([3,1]);zs();nt();var hc;(function(r){let e;(function(s){let n;s.codec=()=>(n==null&&(n=he((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:ie(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})),n),s.encode=o=>ue(o,s.codec()),s.decode=(o,i)=>le(o,s.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=he((s,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),s.peerId!=null&&s.peerId.byteLength>0&&(n.uint32(10),n.bytes(s.peerId)),s.seq!=null&&s.seq!==0n&&(n.uint32(16),n.uint64(s.seq)),s.addresses!=null)for(let i of s.addresses)n.uint32(26),r.AddressInfo.codec().encode(i,n);o.lengthDelimited!==!1&&n.ldelim()},(s,n,o={})=>{let i={peerId:ie(0),seq:0n,addresses:[]},a=n==null?s.len:s.pos+n;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:{i.peerId=s.bytes();break}case 2:{i.seq=s.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(s,s.uint32(),{limits:o.limits?.addresses$}));break}default:{s.skipType(c&7);break}}}return i})),t),r.encode=s=>ue(s,r.codec()),r.decode=(s,n)=>le(s,r.codec(),n)})(hc||(hc={}));var Qt=class r{static createFromProtobuf=e=>{let t=hc.decode(e),s=Pr(Ht(t.peerId)),n=(t.addresses??[]).map(i=>G(i.multiaddr)),o=t.seq;return new r({peerId:s,multiaddrs:n,seqNumber:o})};static DOMAIN=G4;static CODEC=V4;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:s,seqNumber:n}=e;this.peerId=t,this.multiaddrs=s??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=hc.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||!$4(this.multiaddrs,e.multiaddrs))}};function tC(r){return r[Symbol.asyncIterator]!=null}function rC(r){if(tC(r))return(async()=>{let t=[];for await(let s of r)t.push(s);return t})();let e=[];for(let t of r)e.push(t);return e}var dc=rC;X();ce();var Jt=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};Ze();async function er(r,e,t,s){let n=new Jt(s?.errorMessage);s?.errorCode!=null&&(n.code=s.errorCode);let o=s?.errorEvent??"error";return t?.aborted===!0?Promise.reject(n):new Promise((i,a)=>{function c(){s2(t,"abort",h),s2(r,e,l),s2(r,o,u)}let l=d=>{try{if(s?.filter?.(d)===!1)return}catch(f){c(),a(f);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??s?.error??new Error(`The "${s?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(n)};r2(t,"abort",h),r2(r,e,l),r2(r,o,u)})}function r2(r,e,t){r!=null&&(W4(r)?r.addEventListener(e,t):r.addListener(e,t))}function s2(r,e,t){r!=null&&(W4(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function W4(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Bu=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};Ze();var Fu=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 Jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function sC(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Uu=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=sC(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,J(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,s)=>t&&s.signal?.aborted===!0,!0)&&(this.controller.abort(new Jt),this.cleanup())}async join(e={}){let t=new Fu(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 Ce(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 n2(r,e){let t,s=function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)};return s.start=()=>{},s.stop=()=>{clearTimeout(t)},s}var fc=class extends Xe{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=n2(this.emitEmpty.bind(this),1),this.emitIdle=n2(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 Bu;let s=new Uu(e,t);return this.enqueue(s),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),s.join(t).then(n=>(this.safeDispatchEvent("success",{detail:{job:s,result:n}}),n)).catch(n=>{if(s.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===s){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:s,error:n}}),n})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Jt)}),this.clear()}async onEmpty(e){this.size!==0&&await er(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await er(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await er(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=dt({objectMode:!0}),s=c=>{c!=null?this.abort():this.clear(),t.end(c)},n=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{s(c.detail.error)},i=()=>{s()},a=()=>{s(new Jt("Queue aborted"))};this.addEventListener("success",n),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",n),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),s()}}};var mc=we(re("node:cluster"),1),qu=we(re("node:worker_threads"),1);Ze();var jn="lock:worker:request-read",Yn="lock:worker:abort-read-request",Xn="lock:worker:release-read",Zn="lock:master:grant-read",Qn="lock:master:error-read",Jn="lock:worker:request-write",eo="lock:worker:abort-write-request",to="lock:worker:release-write",ro="lock:master:grant-write",so="lock:master:error-write",en="lock:worker:finalize",Ku="mortice",j4={singleProcess:!1};var o2=(r,e,t,s,n,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===n&&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(h=>{let d=f=>{if(f?.data==null)return;let p={type:f.data.type,name:f.data.name,identifier:f.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",d),h())};e.addEventListener("message",d)})},onError:h=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:h.message,name:h.name,stack:h.stack}})}}}),u.type===o&&r.safeDispatchEvent(s,{detail:{name:u.name,identifier:u.identifier}}),u.type===en&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var i2=(r,e,t,s,n,o,i,a)=>(c,l)=>{l!=null&&(l.type===s&&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 h=d=>{d.type===i&&d.identifier===l.identifier&&(c.removeListener("message",h),u())};c.on("message",h)})},onError:u=>{c.send({type:o,name:l.name,identifier:l.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),l.type===n&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier}}),l.type===en&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}}))};var pc=(r=10)=>Math.random().toString().substring(2,r+2);var Hu=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Ku)}readLock(e){return this.sendRequest(jn,Yn,Zn,Qn,Xn,e)}writeLock(e){return this.sendRequest(Jn,eo,ro,so,to,e)}finalize(){this.channel.postMessage({type:en,name:this.name}),this.channel.close()}async sendRequest(e,t,s,n,o,i){i?.signal?.throwIfAborted();let a=pc();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 h=d=>{if(d.data?.identifier===a&&(d.data?.type===s&&(this.channel.removeEventListener("message",h),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),d.data.type===n)){this.channel.removeEventListener("message",h),i?.signal?.removeEventListener("abort",u);let f=new Error;d.data.error!=null&&(f.message=d.data.error.message,f.name=d.data.error.name,f.stack=d.data.error.stack),l(f)}};this.channel.addEventListener("message",h)})}};var zu=class{name;constructor(e){this.name=e}readLock(e){return this.sendRequest(jn,Yn,Zn,Qn,Xn,e)}writeLock(e){return this.sendRequest(Jn,eo,ro,so,to,e)}finalize(){if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");process.send({type:en,identifier:pc(),name:this.name})}async sendRequest(e,t,s,n,o,i){i?.signal?.throwIfAborted();let a=pc();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 h=d=>{if(d.identifier===a&&(d.type===s&&(process.removeListener("message",h),i?.signal?.removeEventListener("abort",u),c(()=>{process.send?.({type:o,identifier:a,name:this.name})})),d.type===n)){process.removeListener("message",h),i?.signal?.removeEventListener("abort",u);let f=new Error;d.error!=null&&(f.message=d.error.message,f.name=d.error.name,f.stack=d.error.stack),l(f)}};process.on("message",h)})}};function nC(){return qu.default.isMainThread===!1||qu.default.isInternalThread===!0?!1:mc.default.isPrimary}var Y4=r=>{if(r=Object.assign({},j4,r),nC()||r.singleProcess){let e=new Xe;mc.default.on("message",i2(e,"requestReadLock","abortReadLockRequest",jn,Yn,Qn,Xn,Zn)),mc.default.on("message",i2(e,"requestWriteLock","abortWriteLockRequest",Jn,eo,so,to,ro));let t=new BroadcastChannel(Ku);return t.addEventListener("message",o2(e,t,"requestReadLock","abortReadLockRequest",jn,Yn,Qn,Xn,Zn)),t.addEventListener("message",o2(e,t,"requestWriteLock","abortWriteLockRequest",Jn,eo,so,to,ro)),t.unref?.(),e}if(mc.default.isWorker)return new zu(r.name);if(qu.default.isMainThread===!1)return new Hu(r.name);throw new Error("Not a cluster worker or worker thread")};var no=new Map,gc;function X4(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function oC(r){if(gc==null&&(gc=Y4(r),!X4(gc))){let e=gc;e.addEventListener("requestReadLock",t=>{let s=t.detail.name,n=t.detail.identifier,o=no.get(s);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==s||c.detail.identifier!==n||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 s=t.detail.name,n=t.detail.identifier,o=no.get(s);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==s||c.detail.identifier!==n||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 s=t.detail.name,n=no.get(s);n?.finalize()})}return gc}async function a2(r,e){let t,s,n=new Promise((i,a)=>{t=i,s=a}),o=()=>{s(new Jt)};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=>{s(i)}),n}var Z4=(r,e)=>{let t=no.get(r);if(t!=null)return t;let s=oC(e);if(X4(s))return t=s,no.set(r,t),t;let n=new fc({concurrency:1}),o;return t={async readLock(i){if(o!=null)return a2(o,i);o=new fc({concurrency:e.concurrency,autoStart:!1});let a=o,c=a2(o,i);return n.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(i){return o=null,a2(n,i)},finalize:()=>{no.delete(r)},queue:n},no.set(r,t),e.autoFinalize===!0&&n.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var iC={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function c2(r){let e=Object.assign({},iC,r);return Z4(e.name,e)}Ro();zr();zs();nt();var xs;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=he((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ie(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let h=i.uint32();switch(h>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(h&7);break}}}return l})),o),n.encode=i=>ue(i,n.codec()),n.decode=(i,a)=>le(i,n.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(n){let o;n.codec=()=>(o==null&&(o=he((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Gu.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 h=i.uint32();switch(h>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Gu.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(h&7);break}}}return l})),o),n.encode=i=>ue(i,n.codec()),n.decode=(i,a)=>le(i,n.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let s;r.codec=()=>(s==null&&(s=he((n,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),n.addresses!=null)for(let a of n.addresses)o.uint32(10),$u.codec().encode(a,o);if(n.protocols!=null)for(let a of n.protocols)o.uint32(18),o.string(a);if(n.publicKey!=null&&(o.uint32(34),o.bytes(n.publicKey)),n.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(n.peerRecordEnvelope)),n.metadata!=null&&n.metadata.size!==0)for(let[a,c]of n.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(n.tags!=null&&n.tags.size!==0)for(let[a,c]of n.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);n.updated!=null&&(o.uint32(64),o.uint64Number(n.updated)),i.lengthDelimited!==!1&&o.ldelim()},(n,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?n.len:n.pos+o;for(;n.pos<c;){let l=n.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($u.codec().decode(n,n.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(n.string());break}case 4:{a.publicKey=n.bytes();break}case 5:{a.peerRecordEnvelope=n.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new ba('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(n,n.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new ba('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(n,n.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=n.uint64Number();break}default:{n.skipType(l&7);break}}}return a})),s),r.encode=n=>ue(n,r.codec()),r.decode=(n,o)=>le(n,r.codec(),o)})(xs||(xs={}));var $u;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(t.multiaddr)),t.isCertified!=null&&(s.uint32(16),s.bool(t.isCertified)),t.observed!=null&&(s.uint32(24),s.uint64Number(t.observed)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={multiaddr:ie(0)},i=s==null?t.len:t.pos+s;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=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})($u||($u={}));var Gu;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.value!=null&&t.value!==0&&(s.uint32(8),s.uint32(t.value)),t.expiry!=null&&(s.uint32(16),s.uint64(t.expiry)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={value:0},i=s==null?t.len:t.pos+s;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=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(Gu||(Gu={}));ft();ce();function aC(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let s=Je(e.publicKey,t);return gs(s)}function Q4(r,e,t){let s=xs.decode(e);return Si(r,s,t)}function Si(r,e,t){let s=new Map,n=BigInt(Date.now());for(let[o,i]of e.tags.entries())i.expiry!=null&&i.expiry<n||s.set(o,i);return{...e,id:aC(r,e),addresses:e.addresses.filter(({observed:o})=>o!=null&&o>Date.now()-t).map(({multiaddr:o,isCertified:i})=>({multiaddr:G(o),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:s}}Kt();function J4(r,e){return cC(r.addresses,e.addresses)&&lC(r.protocols,e.protocols)&&uC(r.publicKey,e.publicKey)&&hC(r.peerRecordEnvelope,e.peerRecordEnvelope)&&dC(r.metadata,e.metadata)&&fC(r.tags,e.tags)}function cC(r,e){return tb(r,e,(t,s)=>!(t.isCertified!==s.isCertified||!ae(t.multiaddr,s.multiaddr)))}function lC(r,e){return tb(r,e,(t,s)=>t===s)}function uC(r,e){return eb(r,e)}function hC(r,e){return eb(r,e)}function dC(r,e){return rb(r,e,(t,s)=>ae(t,s))}function fC(r,e){return rb(r,e,(t,s)=>t.value===s.value&&t.expiry===s.expiry)}function eb(r,e){return r==null&&e==null?!0:r!=null&&e!=null?ae(r,e):!1}function tb(r,e,t){if(r.length!==e.length)return!1;for(let s=0;s<r.length;s++)if(!t(r[s],e[s]))return!1;return!0}function rb(r,e,t){if(r.size!==e.size)return!1;for(let[s,n]of r.entries()){let o=e.get(s);if(o==null||!t(n,o))return!1}return!0}X();ge();Se();var vs="/",sb=new TextEncoder().encode(vs),Vu=sb[0],oo=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Vu)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(vs))}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=sb),this._buf[0]!==Vu){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Vu,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Vu;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),s=e.list();for(let n=0;n<t.length;n++){if(s.length<n+1)return!1;let o=t[n],i=s[n];if(o<i)return!0;if(o>i)return!1}return t.length<s.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(vs).slice(1)}type(){return pC(this.baseNamespace())}name(){return mC(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(vs)||(e+=vs),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(vs):new r(e.slice(0,-1).join(vs))}child(e){return this.toString()===vs?e:e.toString()===vs?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(),...gC(e.map(t=>t.namespaces()))])}};function pC(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function mC(r){let e=r.split(":");return e[e.length-1]}function gC(r){return[].concat(...r)}var l2="/peers/";function yc(r){if(!Vs(r)||r.type==null)throw new V("Invalid PeerId");let e=r.toCID().toString();return new oo(`${l2}${e}`)}ft();X();Kt();X();async function nb(r,e,t,s,n){let o=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=G(i.multiaddr)),!Js(i.multiaddr))throw new V("Multiaddr was invalid");if(!await e(r,i.multiaddr,n))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.getPeerId();return r.equals(c)&&(a=a.decapsulate(G(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function ju(r,e,t,s){if(e==null)throw new V("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new V("publicKey bytes do not match peer id publicKey bytes");let n=s.existingPeer?.peer;if(n!=null&&!r.equals(n.id))throw new V("peer id did not match existing peer id");let o=n?.addresses??[],i=new Set(n?.protocols??[]),a=n?.metadata??new Map,c=n?.tags??new Map,l=n?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Wu(d,{validate:ob})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Wu(d,{validate:ib,map:ab})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,p]of d)p==null?a.delete(f):a.set(f,p);a=Wu([...a.entries()],{validate:ob})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[p,m]of d)m==null?f.delete(p):f.set(p,m);c=Wu([...f.entries()],{validate:ib,map:ab})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;n?.id.publicKey!=null?u=Ve(n.id.publicKey):e.publicKey!=null?u=Ve(e.publicKey):r.publicKey!=null&&(u=Ve(r.publicKey));let h={addresses:await nb(r,s.addressFilter??(async()=>!0),o,s.existingPeer?.peerPB.addresses,s),protocols:[...i.values()].sort((d,f)=>d.localeCompare(f)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return h.addresses.forEach(d=>{d.observed=s.existingPeer?.peerPB.addresses?.find(f=>ae(f.multiaddr,f.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete h.publicKey,h}function Wu(r,e){let t=new Map;for(let[s,n]of r)n!=null&&e.validate(s,n);for(let[s,n]of r.sort(([o],[i])=>o.localeCompare(i)))n!=null&&t.set(s,e.map?.(s,n)??n);return t}function ob(r,e){if(typeof r!="string")throw new V("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new V("Metadata value must be a Uint8Array")}function ib(r,e){if(typeof r!="string")throw new V("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new V("Tag value must be an integer");if(e.value<0||e.value>100)throw new V("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new V("Tag ttl must be an integer");if(e.ttl<0)throw new V("Tag ttl must be between greater than 0")}}function ab(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let s={value:e.value??0};return t!=null&&(s.expiry=t),s}function cb(r){let e=r.toString().split("/")[2],t=De.parse(e,or);return Wr(t)}function u2(r,e,t){let s=cb(r);return Q4(s,e,t)}function yC(r,e){return{prefix:l2,filters:(r.filters??[]).map(t=>({key:s,value:n})=>t(u2(s,n,e))),orders:(r.orders??[]).map(t=>(s,n)=>t(u2(s.key,s.value,e),u2(n.key,n.value,e)))}}var Yu=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=t2({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:c2({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 s=this.getLock(e);try{let n=await s.lock.readLock(t);return()=>{n(),this.maybeRemoveLock(e,s)}}catch(n){throw this.maybeRemoveLock(e,s),n}}async getWriteLock(e,t){let s=this.getLock(e);try{let n=await s.lock.writeLock(t);return()=>{n(),this.maybeRemoveLock(e,s)}}catch(n){throw this.maybeRemoveLock(e,s),n}}async has(e,t){try{return await this.load(e,t),!0}catch(s){if(s.name!=="NotFoundError")throw s}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(yc(e),t)}async load(e,t){let s=yc(e),n=await this.datastore.get(s,t),o=xs.decode(n);if(this.#r(e,o))throw await this.datastore.delete(s,t),new An;return Si(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,s){let n=await this.#e(e,s),o=await ju(e,t,"patch",{...s,addressFilter:this.addressFilter});return this.#t(e,o,n)}async patch(e,t,s){let n=await this.#e(e,s),o=await ju(e,t,"patch",{...s,addressFilter:this.addressFilter,existingPeer:n});return this.#t(e,o,n)}async merge(e,t,s){let n=await this.#e(e,s),o=await ju(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#t(e,o,n)}async*all(e){for await(let{key:t,value:s}of this.datastore.query(yC(e??{},this.maxAddressAge),e)){let n=cb(t);if(n.equals(this.peerId))continue;let o=xs.decode(s);if(this.#r(n,o)){await this.datastore.delete(t,e);continue}yield Si(n,o,this.peerId.equals(n)?1/0:this.maxAddressAge)}}async#e(e,t){try{let s=yc(e),n=await this.datastore.get(s,t),o=xs.decode(n);if(this.#r(e,o))throw await this.datastore.delete(s,t),new An;return{peerPB:o,peer:Si(e,o,this.maxAddressAge)}}catch(s){s.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",s)}}async#t(e,t,s,n){t.updated=Date.now();let o=xs.encode(t);return await this.datastore.put(yc(e),o,n),{peer:Si(e,t,this.maxAddressAge),previous:s?.peer,updated:s==null||!J4(t,s.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let s=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,o=t.addresses.filter(i=>i.observed!=null&&i.observed>n);return s&&o.length===0}};var h2=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 Yu(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let s of this.store.all(t))e(s)}async all(e){return dc(this.store.all(e))}async delete(e,t){let s=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{s()}}async has(e,t){let s=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),s?.()}}async get(e,t){let s=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{s?.()}}async getInfo(e,t){let s=await this.get(e,t);return{id:s.id,multiaddrs:s.addresses.map(({multiaddr:n})=>n)}}async save(e,t,s){let n=await this.store.getWriteLock(e,s);try{let o=await this.store.save(e,t,s);return this.#e(e,o),o.peer}finally{n?.()}}async patch(e,t,s){let n=await this.store.getWriteLock(e,s);try{let o=await this.store.patch(e,t,s);return this.#e(e,o),o.peer}finally{n?.()}}async merge(e,t,s){let n=await this.store.getWriteLock(e,s);try{let o=await this.store.merge(e,t,s);return this.#e(e,o),o.peer}finally{n?.()}}async consumePeerRecord(e,t,s){let n=Vs(t)?t:Vs(t?.expectedPeer)?t.expectedPeer:void 0,o=Vs(t)||t===void 0?s:t,i=await Or.openAndCertify(e,Qt.DOMAIN,o),a=Wr(i.publicKey.toCID());if(n?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",n,a),!1;let c=Qt.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=Or.createFromProtobuf(l.peerRecordEnvelope),h=Qt.createFromProtobuf(u.payload);if(h.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",h.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 lb(r,e={}){return new h2(r,e)}var Xu=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 bC(r){return r[Symbol.asyncIterator]!=null}function wC(r){if(bC(r))return(async()=>{for await(let e of r);})();for(let e of r);}var d2=wC;function xC(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],s=[];return{peek:()=>e.next(),push:n=>{s.push(n)},next:()=>s.length>0?{done:!1,value:s.shift()}:e.next(),[t](){return this}}}var Zu=xC;function vC(r){return r[Symbol.asyncIterator]!=null}function EC(r,e){let t=0;if(vC(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let s=Zu(r),{value:n,done:o}=s.next();if(o===!0)return(function*(){})();let i=e(n,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield n);for(let c of s)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield n);for(let c of s)a(c,t++)&&(yield c)})()}var io=EC;function SC(r){return r[Symbol.asyncIterator]!=null}function IC(r,e){return SC(r)?(async function*(){yield*(await dc(r)).sort(e)})():(function*(){yield*dc(r).sort(e)})()}var f2=IC;function _C(r){return r[Symbol.asyncIterator]!=null}function AC(r,e){return _C(r)?(async function*(){let t=0;if(!(e<1)){for await(let s of r)if(yield s,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let s of r)if(yield s,t++,t===e)return}})()}var p2=AC;var Qu=class{put(e,t,s){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:s,value:n}of e)await this.put(s,n,t),yield s}async*getMany(e,t={}){for await(let s of e)yield{key:s,value:await this.get(s,t)}}async*deleteMany(e,t={}){for await(let s of e)await this.delete(s,t),yield s}batch(){let e=[],t=[];return{put(s,n){e.push({key:s,value:n})},delete(s){t.push(s)},commit:async s=>{await d2(this.putMany(e,s)),e=[],await d2(this.deleteMany(t,s)),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 s=this._all(e,t);if(e.prefix!=null){let n=e.prefix;s=io(s,o=>o.key.toString().startsWith(n))}if(Array.isArray(e.filters)&&(s=e.filters.reduce((n,o)=>io(n,o),s)),Array.isArray(e.orders)&&(s=e.orders.reduce((n,o)=>f2(n,o),s)),e.offset!=null){let n=0,o=e.offset;s=io(s,()=>n++>=o)}return e.limit!=null&&(s=p2(s,e.limit)),s}queryKeys(e,t){let s=this._allKeys(e,t);if(e.prefix!=null){let n=e.prefix;s=io(s,o=>o.toString().startsWith(n))}if(Array.isArray(e.filters)&&(s=e.filters.reduce((n,o)=>io(n,o),s)),Array.isArray(e.orders)&&(s=e.orders.reduce((n,o)=>f2(n,o),s)),e.offset!=null){let n=e.offset,o=0;s=io(s,()=>o++>=n)}return e.limit!=null&&(s=p2(s,e.limit)),s}};var Ju=class extends Qu{data;constructor(){super(),this.data=new Map}put(e,t,s){return s?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let s=this.data.get(e.toString());if(s==null)throw new Xu;return s}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[s,n]of this.data.entries())yield{key:new oo(s),value:n},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let s of this.data.keys())yield new oo(s),t?.signal?.throwIfAborted()}};Ze();Kr();ge();ce();function bc(r,e){let t,s=function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)};return s.start=()=>{},s.stop=()=>{clearTimeout(t)},s}var hb=we(ub(),1),CC=["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"],TC=CC.map(r=>new hb.Netmask(r));function m2(r){for(let e of TC)if(e.contains(r))return!0;return!1}function PC(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function kC(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),s=e[e.length-2].padStart(4,"0"),n=`${parseInt(s.substring(0,2),16)}.${parseInt(s.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return m2(n)}function DC(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function MC(r){let e=r.split(":"),t=e[e.length-1];return m2(t)}function OC(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 Ii(r){if((0,Fe.isIPv4)(r))return m2(r);if(PC(r))return kC(r);if(DC(r))return MC(r);if((0,Fe.isIPv6)(r))return OC(r)}var Pe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Y=(r,e)=>({match:t=>{let s=t[0];return s?.code!==r||s.value==null||e!=null&&s.value!==e?!1:t.slice(1)}}),ne=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),St=(...r)=>({match:e=>{let t;for(let s of r){let n=s.match(e);n!==!1&&(t==null||n.length<t.length)&&(t=n)}return t??!1}}),ye=(...r)=>({match:e=>{for(let t of r){let s=t.match(e);if(s===!1)return!1;e=s}return e}});function Ae(...r){function e(n){if(n==null)return!1;let o=n.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(n){return e(n)!==!1}function s(n){let o=e(n);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:s}}var LC=Y(421),db=Ae(LC),t1=Y(54),r1=Y(55),s1=Y(56),y2=Y(53),Bj=Ae(t1,ne(Y(421))),Fj=Ae(r1,ne(Y(421))),Uj=Ae(s1,ne(Y(421))),Kj=Ae(St(y2,s1,t1,r1),ne(Y(421))),fb=ye(Y(4),ne(Y(43))),pb=ye(ne(Y(42)),Y(41),ne(Y(43))),b2=St(fb,pb),ao=St(b2,y2,t1,r1,s1),mb=Ae(St(b2,ye(St(y2,s1,t1,r1),ne(Y(421))))),w2=Ae(fb),x2=Ae(pb),Hj=Ae(b2),v2=ye(ao,Y(6)),xc=ye(ao,Y(273)),Es=Ae(ye(v2,ne(Y(421)))),zj=Ae(xc),E2=ye(xc,Pe(460),ne(Y(421))),n1=ye(xc,Pe(461),ne(Y(421))),RC=St(E2,n1),qj=Ae(E2),gb=Ae(n1),g2=St(ao,v2,xc,E2,n1),yb=St(ye(g2,Pe(477),ne(Y(421)))),vc=Ae(yb),bb=St(ye(g2,Pe(478),ne(Y(421))),ye(g2,Pe(448),ne(Y(449)),Pe(477),ne(Y(421)))),Ec=Ae(bb),wb=ye(xc,Pe(280),ne(Y(466)),ne(Y(466)),ne(Y(421))),S2=Ae(wb),xb=ye(n1,Pe(465),ne(Y(466)),ne(Y(466)),ne(Y(421))),I2=Ae(xb),e1=St(yb,bb,ye(v2,ne(Y(421))),ye(RC,ne(Y(421))),ye(ao,ne(Y(421))),wb,xb,Y(421)),$j=Ae(e1),NC=ye(e1,Pe(290),Y(421)),Sc=Ae(NC),BC=St(ye(e1,Pe(290),Pe(281),ne(Y(421))),ye(e1,Pe(281),ne(Y(421))),ye(Pe(281),ne(Y(421)))),_2=Ae(BC),FC=St(ye(ao,Y(6),Pe(480),ne(Y(421))),ye(ao,Pe(480),ne(Y(421)))),Gj=Ae(FC),UC=ye(ao,St(ye(Y(6,"443"),Pe(480)),ye(Y(6),Pe(443)),ye(Y(6),Pe(448),Pe(480)),ye(Pe(448),Pe(480)),Pe(448),Pe(443)),ne(Y(421))),Vj=Ae(UC),KC=St(ye(Y(777),ne(Y(421)))),Wj=Ae(KC),HC=St(ye(Y(400),ne(Y(421)))),jj=Ae(HC);var A2=class extends Map{metric;constructor(e){super();let{name:t,metrics:s}=e;this.metric=s.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 It(r){let{name:e,metrics:t}=r,s;return t!=null?s=new A2({name:e,metrics:t}):s=new Map,s}var vb=864e13;var zC=448,C2=449,qC=53,$C=54,GC=55,VC=56,o1=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=It({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=this.findHost(e);for(let s of this.mappings.values())if(s.domain===t)return!0;return!1}add(e,t){t.forEach(s=>{this.log("add DNS mapping %s to %s",s,e);let n=Ii(s)===!0;this.mappings.set(s,{domain:e,verified:n,expires:n?vb-Date.now():0,lastVerified:n?vb-Date.now():void 0})})}remove(e){let t=this.findHost(e),s=!1;for(let[n,o]of this.mappings.entries())o.domain===t&&(this.log("removing %s to %s DNS mapping %e",n,o.domain),this.mappings.delete(n),s=s||o.verified);return s}getAll(e){let t=[];for(let s=0;s<e.length;s++){let o=e[s].multiaddr.stringTuples(),i=o[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(o,c.domain)&&(e.splice(s,1),s--,t.push({multiaddr:G(`/${o.map(u=>[yi(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let s=0;s<e.length;s++)if(e[s][0]===zC&&e[s+1]?.[0]!==C2)return e.splice(s+1,0,[C2,t]),!0;return!1}confirm(e,t){let s=this.findHost(e),n=!1;for(let[o,i]of this.mappings.entries())i.domain===s&&(this.log("marking %s to %s DNS mapping as verified",o,i.domain),n=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return n}unconfirm(e,t){let s=this.findHost(e),n=!1;for(let[o,i]of this.mappings.entries())i.domain===s&&(this.log("removing verification of %s to %s DNS mapping",o,i.domain),n=n||i.verified,i.verified=!1,i.expires=Date.now()+t);return n}findHost(e){for(let t of e.stringTuples())if(t[0]===C2||t[0]===qC||t[0]===$C||t[0]===GC||t[0]===VC)return t[1]}};var T2=4,P2=41,k2=6,WC=273,i1=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=It({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=e.stringTuples();for(let s of this.mappings.values())for(let n of s)if(n.externalIp===t[0][1])return!0;return!1}add(e,t,s,n=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:s,externalPort:n,externalFamily:(0,Fe.isIPv4)(s)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=e.stringTuples(),s=t[0][1]??"",n=t[1][0]===k2?"tcp":"udp",o=parseInt(t[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===s&&u.externalPort===o&&u.protocol===n&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,s,o,n),i=i||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return i}getAll(e){let t=[];for(let{multiaddr:s}of e){let n=s.stringTuples(),o;if((n[0][0]===T2||n[0][0]===P2)&&n[1][0]===k2?o=`${n[0][1]}-${n[1][1]}-tcp`:(n[0][0]===T2||n[0][0]===P2)&&n[1][0]===WC&&(o=`${n[0][1]}-${n[1][1]}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)n[0][0]=a.externalFamily===4?T2:P2,n[0][1]=a.externalIp,n[1][1]=`${a.externalPort}`,t.push({multiaddr:G(`/${n.map(c=>[yi(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let n=e.stringTuples()[0][1],o=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===n&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let s=e.stringTuples(),n=s[0][1]??"",o=s[1][0]===k2?"tcp":"udp",i=parseInt(s[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===i&&u.protocol===o&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,i,o),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function Eb(r){try{for(let{code:e,value:t}of r.getComponents())if(e!==42&&t!=null){if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}}catch{}return!1}function a1(r){try{for(let{code:e}of r.getComponents())if(e!==42)return e===4||e===41}catch{}return!1}function Ss(r){try{if(!a1(r))return!1;let[[,e]]=r.stringTuples();return e==null?!1:Ii(e)??!1}catch{}return!0}var jC={maxObservedAddresses:10},c1=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=It({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??jC.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&&(Ss(e)||Eb(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:G(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 s=e.toString(),n=this.addresses.get(s)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.log("marking observed address %a as verified",s),this.addresses.set(s,n),o}};var YC=[4,41,53,54,55,56];function D2(r){try{for(let{code:e}of r.getComponents())if(e!==42)return YC.includes(e)}catch{}return!1}var XC={maxObservedAddresses:10},l1=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=It({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??XC.maxObservedAddresses}get(e,t){if(Ss(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let s=this.toKey(e),n=this.addresses.get(s);return n==null&&(n={verified:!D2(e),expires:0},this.addresses.set(s,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),s=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),s}confirm(e,t){let s=this.toKey(e),n=this.addresses.get(s)??{verified:!1,expires:0,lastVerified:0},o=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.addresses.set(s,n),o}unconfirm(e,t){let s=this.toKey(e),n=this.addresses.get(s)??{verified:!1,expires:0},o=n.verified;return n.verified=!1,n.expires=Date.now()+t,this.addresses.set(s,n),o}toKey(e){if(D2(e)){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}};var Sb=6e4,Ib={maxObservedAddresses:10,addressVerificationTTL:Sb*10,addressVerificationRetry:Sb*5},ZC=r=>r;function M2(r,e){let t=r.getPeerId();return t!=null&&$(t).equals(e)&&(r=r.decapsulate(G(`/p2p/${e.toString()}`))),r}var u1=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:s=[],announce:n=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=s.map(i=>i.toString()),this.announce=new Set(n.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new c1(e,t),this.dnsMappings=new o1(e,t),this.ipMappings=new i1(e,t),this.transportAddresses=new l1(e,t),this.announceFilter=t.announceFilter??ZC,this.observedAddressFilter=lc(1024),this.addressVerificationTTL=t.addressVerificationTTL??Ib.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Ib.addressVerificationRetry,this._updatePeerStoreAddresses=bc(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.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>G(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>G(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>G(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),s=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(s)||(this.observedAddressFilter.add(s),e=M2(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=M2(e,this.components.peerId);let s=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),s=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1)),s||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=M2(e,this.components.peerId);let s=!1;this.observed.has(e)&&!this.observed.remove(e)&&s&&(s=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&s&&(s=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&s&&(s=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&s&&(s=!1),s&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(s=>{if(!s.verified)return!1;let n=s.multiaddr.toString();return e.has(n)?!1:(e.add(n),!0)}).map(s=>s.multiaddr);return this.announceFilter(t.map(s=>{let n=G(s);return n.getComponents().pop()?.value===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(e)}),e.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL)));let s=this.getAppendAnnounceAddrs();return s.length>0&&(this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(s)}),t=t.concat(s.map(n=>({multiaddr:n,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(G(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,s,n=t,o="tcp"){this.ipMappings.add(e,t,s,n,o),this.observed.removePrefixed(`/ip${(0,Fe.isIPv4)(s)?4:6}/${s}/${o}/${n}`)}removePublicAddressMapping(e,t,s,n=t,o="tcp"){this.ipMappings.remove(G(`/ip${(0,Fe.isIPv4)(s)?4:6}/${s}/${o}/${n}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;let t=e.toOptions();if(t.family===6||t.host==="127.0.0.1"||Ii(t.host)===!0)return!1;let s=this.components.transportManager.getListeners(),n=[o=>vc.exactMatch(o)||Ec.exactMatch(o),o=>Es.exactMatch(o),o=>gb.exactMatch(o)];for(let o of n){if(!o(e))continue;let i=s.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.transport),!0}return!1}};X();var _b;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(_b||(_b={}));var h1=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},d1=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},_i=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Ic=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},f1=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},p1=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},m1=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},_c=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},g1=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},y1=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},b1=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},w1=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},x1=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},co=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},lo=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},v1=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},E1=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var O2=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,s]of Object.entries(e))this.components[t]=s;this.components.logger==null&&(this.components.logger=Ou())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Gl(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")}},JC=["metrics","connectionProtector","dns"],e7=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Ab(r={}){let e=new O2(r);return new Proxy(e,{get(s,n,o){if(typeof n=="string"&&!e7.includes(n)){let i=e.components[n];if(i==null&&!JC.includes(n))throw new h1(`${n} not set`);return i}return Reflect.get(s,n,o)},set(s,n,o){return typeof n=="string"?e.components[n]=o:Reflect.set(s,n,o),!0}})}function Cb(r){let e={};for(let t of Object.values(r.components))for(let s of t7(t))e[s]=!0;for(let t of Object.values(r.components))for(let s of r7(t))if(e[s]!==!0)throw new d1(`Service "${s7(t)}" required capability "${s}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function t7(r){return Array.isArray(r?.[et])?r[et]:[]}function r7(r){return Array.isArray(r?.[ka])?r[ka]:[]}function s7(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function Tb(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async()=>!1,denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}X();var Pb=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},n7=new WeakMap;function o7({clearTimeout:r,setTimeout:e}={}){return(t,{value:s,signal:n}={})=>{if(n?.aborted)return Promise.reject(Pb());let o,i,a,c=r??clearTimeout,l=()=>{c(o),a(Pb())},u=()=>{n&&n.removeEventListener("abort",l)},h=new Promise((d,f)=>{i=()=>{u(),d(s)},a=f,o=(e??setTimeout)(i,t)});return n&&n.addEventListener("abort",l,{once:!0}),n7.set(h,()=>{c(o),o=null,i()}),h}}var i7=o7(),kb=i7;var S1=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}},I1=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var _1=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new L2}async consume(e,t=1,s={}){let n=this.getKey(e),o=this._getKeySecDuration(s),i=this.memoryStorage.incrby(n,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(n,i.consumedPoints,this.blockDuration)),new S1("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await kb(a)}return i}penalty(e,t=1,s={}){let n=this.getKey(e),o=this._getKeySecDuration(s),i=this.memoryStorage.incrby(n,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,s={}){let n=this.getKey(e),o=this._getKeySecDuration(s),i=this.memoryStorage.incrby(n,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let s=t*1e3,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:n,isFirstInDuration:!1}}set(e,t,s=0){let n=(s>=0?s:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,s),{remainingPoints:0,msBeforeNext:n===0?-1:n,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)}},L2=class{storage;constructor(){this.storage=new Map}incrby(e,t,s){let n=this.storage.get(e);if(n!=null){let o=n.expiresAt!=null?n.expiresAt.getTime()-new Date().getTime():-1;return n.expiresAt==null||o>0?(n.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,s)}return this.set(e,t,s)}set(e,t,s){let n=s*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},n),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:n===0?-1:n,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}};X();ce();function A1(r){if(Vs(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let s=e[0].getPeerId();t=s==null?void 0:$(s),e.forEach(n=>{if(!Js(n))throw new js("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(t!=null)throw new V("Multiaddrs must all have the same peer id or have no peer id")}else{let i=$(o);if(t?.equals(i)!==!0)throw new V("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(s=>!db.exactMatch(s)),{peerId:t,multiaddrs:e}}var a7=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Db(r,e){let t=r?.streams?.map(n=>n.protocol)??[],s=e?.closableProtocols??a7;if(!(t.filter(n=>n!=null&&!s.includes(n)).length>0))try{await r?.close(e)}catch(n){r?.abort(n)}}function Ac(r){try{let e;typeof r=="string"?e=G(r):e=r;let t=new Set([...e.getComponents().map(s=>s.name)]);if(!t.has("ipcidr")){let n=t.has("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(n)}return N0(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var C1=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(s=>Ac(s)),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,s=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,s),t<=s)return;let n=new pr;for(let c of e){let l=c.remotePeer;if(!n.has(l)){n.set(l,0);try{let u=await this.peerStore.get(l);n.set(l,[...u.tags.values()].reduce((h,d)=>h+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),i=Math.max(t-s,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=>u.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Db(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((s,n)=>{let o=s.timeline.open,i=n.timeline.open;return o<i?1:o>i?-1:0}).sort((s,n)=>s.direction==="outbound"&&n.direction==="inbound"?1:s.direction==="inbound"&&n.direction==="outbound"?-1:0).sort((s,n)=>s.streams.length>n.streams.length?1:s.streams.length<n.streams.length?-1:0).sort((s,n)=>{let o=t.get(s.remotePeer)??0,i=t.get(n.remotePeer)??0;return o>i?1:o<i?-1:0})}};var Mb="last-dial-failure",Ob="last-dial-success";var Lb=300,T1=100;X();X();Ze();X();Ze();X();var P1=class{deferred;signal;constructor(e){this.signal=e,this.deferred=fe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Lt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function c7(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var k1=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=c7(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,J(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,s)=>t&&s.signal?.aborted===!0,!0)&&(this.controller.abort(new Lt),this.cleanup())}async join(e={}){let t=new P1(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 Ce(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 Ai=class extends Xe{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=bc(this.emitEmpty.bind(this),1),this.emitIdle=bc(this.emitIdle.bind(this),1)}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.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 I1;let s=new k1(e,t);return this.enqueue(s),this.safeDispatchEvent("add"),this.tryToStartAnother(),s.join(t).then(n=>(this.safeDispatchEvent("completed",{detail:n}),this.safeDispatchEvent("success",{detail:{job:s,result:n}}),n)).catch(n=>{if(s.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===s){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:s,error:n}}),n})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Lt)}),this.clear()}async onEmpty(e){this.size!==0&&await er(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await er(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await er(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=dt({objectMode:!0}),s=c=>{c!=null?this.abort():this.clear(),t.end(c)},n=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{s(c.detail.error)},i=()=>{s()},a=()=>{s(new Lt("Queue aborted"))};this.addEventListener("completed",n),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),s()}}};var D1=class extends Ai{constructor(e={}){super({...e,sort:(t,s)=>t.options.priority>s.options.priority?-1:t.options.priority<s.options.priority?1:0})}};function Is(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 s(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let n=e.signal;return n.clear=s,n}Ze();ge();function Rb(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function R2(r){if(!a1(r))return!1;let{address:e}=r.nodeAddress();return Rb(e)}function l7(r,e){let t=Es.exactMatch(r.multiaddr),s=Es.exactMatch(e.multiaddr);if(t&&!s)return-1;if(!t&&s)return 1;let n=Ec.exactMatch(r.multiaddr),o=Ec.exactMatch(e.multiaddr);if(n&&!o)return-1;if(!n&&o)return 1;let i=vc.exactMatch(r.multiaddr),a=vc.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=_2.exactMatch(r.multiaddr),l=_2.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=S2.exactMatch(r.multiaddr),h=S2.exactMatch(e.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;let d=I2.exactMatch(r.multiaddr),f=I2.exactMatch(e.multiaddr);return d&&!f?-1:!d&&f?1:0}function u7(r,e){let t=R2(r.multiaddr),s=R2(e.multiaddr);return t&&!s?1:!t&&s?-1:0}function h7(r,e){let t=Ss(r.multiaddr),s=Ss(e.multiaddr);return t&&!s?1:!t&&s?-1:0}function d7(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function f7(r,e){let t=Sc.exactMatch(r.multiaddr),s=Sc.exactMatch(e.multiaddr);return t&&!s?1:!t&&s?-1:0}function Nb(r){return r.sort(l7).sort(d7).sort(f7).sort(h7).sort(u7)}async function N2(r,e,t){let s=t.depth??0;if(s>(t.maxRecursiveDepth??32))throw new E1("Max recursive depth reached");let n=!1,o=[];for(let i of Object.values(e))if(i.canResolve(r)){n=!0;let a=await i.resolve(r,t);for(let c of a)o.push(...await N2(c,e,{...t,depth:s+1}))}return n===!1&&o.push(r),o}var Cc={maxParallelDials:T1,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:zn}},M1=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Cc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Cc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Cc.dialTimeout,this.connections=t.connections??new pr,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Cc.resolvers,this.shutDownController=new AbortController,J(1/0,this.shutDownController.signal),this.queue=new D1({concurrency:t.maxParallelDials??Cc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",s=>{s.detail?.error.name!==Lt.name&&this.log.error("error in dial queue - %e",s.detail)})}start(){this.shutDownController=new AbortController,J(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:s,multiaddrs:n}=A1(e),o=Array.from(this.connections.values()).flat().find(a=>t.force===!0||a.limits!=null?!1:a.remotePeer.equals(s)?!0:n.find(c=>c.equals(a.remoteAddr)));if(o?.status==="open")return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new We("dial-queue:already-connected")),o;let i=this.queue.queue.find(a=>{if(s?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of n)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",s);for(let a of n)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new We("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Zo("Dial queue is full");return this.log("creating dial target for %p",s,n.map(a=>a.toString())),t.onProgress?.(new We("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new We("dial-queue:start-dial"));let c=Is([this.shutDownController.signal,a.signal]);J(1/0,c);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:s,priority:t.priority??K2,multiaddrs:new Set(n.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let s=e.peerId,n=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",s);i||n.size>0;){c++,i=!1;let u=[],h=new Set(e.multiaddrs);n.clear(),this.log("calculating addrs to dial %p from %s",s,[...h]);let d=await this.calculateMultiaddrs(s,h,{...e,signal:t});for(let f of d){if(o.has(f.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",f.multiaddr,s);continue}u.push(f)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",s,u.map(f=>f.multiaddr.toString())),e?.onProgress?.(new We("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 Zo("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(f.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",f.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[Ob]:L(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",s,m)}return p}catch(p){if(this.log.error("dial failed to %a",f.multiaddr,p),o.add(f.multiaddr.toString()),s!=null)try{await this.components.peerStore.merge(s,{metadata:{[Mb]:L(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",s,m)}if(t.aborted)throw new Vr(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,s={}){let n=[...t].map(h=>({multiaddr:G(h),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Zo("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new _c("The dial request is blocked by gater.allowDialPeer");if(n.length===0){this.log("loading multiaddrs for %p",e);try{let h=await this.components.peerStore.get(e);n.push(...h.addresses),this.log("loaded multiaddrs for %p",e,n.map(({multiaddr:d})=>d.toString()))}catch(h){if(h.name!=="NotFoundError")throw h}}if(n.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let h=await this.components.peerRouting.findPeer(e,s);this.log("found multiaddrs for %p in the peer routing",e,n.map(({multiaddr:d})=>d.toString())),n.push(...h.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(h){h.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,h)}}}let o=(await Promise.all(n.map(async h=>{let d=await N2(h.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...s});return d.length===1&&d[0].equals(h.multiaddr)?h:d.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let h=`/p2p/${e.toString()}`;o=o.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(h),isCertified:d.isCertified}:d)}let i=o.filter(h=>{if(this.components.transportManager.dialTransportForMultiaddr(h.multiaddr)==null)return!1;let d=h.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let h of i){let d=h.multiaddr.toString(),f=a.get(d);if(f!=null){f.isCertified=f.isCertified||h.isCertified||!1;continue}a.set(d,h)}let c=[...a.values()];if(c.length===0)throw new b1("The dial request has no valid addresses");let l=[];for(let h of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(h.multiaddr)||l.push(h);let u=this.addressSorter==null?Nb(l):l.sort(this.addressSorter);if(u.length===0)throw new _c("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:h})=>h.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:h})=>h.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let s=await this.calculateMultiaddrs(void 0,new Set(e.map(n=>n.toString())),t);return t.runOnLimitedConnection===!1?s.find(n=>!Sc.matches(n.multiaddr))!=null:!0}catch(s){this.log.trace("error calculating if multiaddr(s) were dialable",s)}return!1}};X();var O1=class extends Ai{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var qb=we(Hb(),1);var m7=Object.prototype.toString,g7=r=>m7.call(r)==="[object Error]",y7=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 H2(r){if(!(r&&g7(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:s}=r;return t==="Load failed"?s===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:y7.has(t)}var z2=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}},zb=(r,e,t)=>{let s=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=s,r};async function q2(r,e){return new Promise((t,s)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let n=qb.default.operation(e),o=()=>{n.stop(),s(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",o),n.stop()};n.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof z2)throw c.originalError;if(c instanceof TypeError&&!H2(c))throw c;if(zb(c,a,e),await e.shouldRetry(c)||(n.stop(),s(c)),await e.onFailedAttempt(c),!n.retry(c))throw n.mainError()}catch(l){zb(l,a,e),i(),s(l)}}})})}var L1=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 O1({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",s=>{this.maybeReconnect(s.detail).catch(n=>{this.log.error("failed to maybe reconnect to %p - %e",s.detail,n)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);$b(t)&&(this.queue.has(e)||this.queue.add(async s=>{await q2(async n=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:s?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,n,this.retries,o),o}},{signal:s?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async s=>{this.log.error("failed to reconnect to %p - %e",e,s);let n={};[...t.tags.keys()].forEach(o=>{o.startsWith(xp)&&(n[o]=void 0)}),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async s=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,s)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>$b(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(s=>{this.log.error(s)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function $b(r){for(let e of r.tags.keys())if(e.startsWith(xp))return!0;return!1}var K2=50,$2={maxConnections:Lb,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},R1=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??$2.maxConnections,this.maxConnections<1)throw new V("Connection Manager maxConnections must be greater than 0");this.connections=new pr,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(s=>Ac(s)),this.deny=(t.deny??[]).map(s=>Ac(s)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??$2.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new _1({points:t.inboundConnectionThreshold??$2.inboundConnectionThreshold,duration:1}),this.connectionPruner=new C1({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(s=>G(s))}),this.dialQueue=new M1(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??T1,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:zn},connections:this.connections}),this.reconnectQueue=new L1({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 s of t)e[s.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let s of t)for(let n of s.streams){let o=`${n.direction} ${n.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 s of this.connections.values())for(let n of s){let o={};for(let i of n.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[s,n]of Object.entries(e)){n=n.sort((i,a)=>i-a);let o=Math.floor(n.length*.9);t[s]=n[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await By(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 Fy(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let s of t)e.push((async()=>{try{await s.close()}catch(n){this.log.error(n)}})());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 V("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(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let s=t.remotePeer,n=!this.connections.has(s),o=this.connections.get(s)??[];o.push(t),this.connections.set(s,o),s.publicKey!=null&&s.type==="RSA"&&await this.peerStore.patch(s,{publicKey:s.publicKey}),n&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,s=t.remotePeer,o=(this.connections.get(s)??[]).filter(i=>i.id!==t.id);this.connections.set(s,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",s),this.connections.delete(s),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let s of this.connections.values())t=t.concat(s);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Tr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:s}=A1(e);if(this.peerId.equals(s))throw new Xo("Can not dial self");if(s!=null&&t.force!==!0){this.log("dial %p",s);let a=this.getConnections(s).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p as %a",s,a.remoteAddr),t.onProgress?.(new We("dial-queue:already-connected")),a}let n=await this.dialQueue.dial(e,{...t,priority:t.priority??K2});if(n.status!=="open")throw new Yo("Remote closed connection during opening");let o=this.connections.get(n.remotePeer);o==null&&(o=[],this.connections.set(n.remotePeer,o));let i=!1;for(let a of o)if(a.id===n.id&&(i=!0),t.force!==!0&&a.id!==n.id&&a.remoteAddr.equals(n.remoteAddr))return n.abort(new js("Duplicate multiaddr connection")),a;return i||o.push(n),n}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let s=this.connections.get(e)??[];await Promise.all(s.map(async n=>{try{await n.close(t)}catch(o){n.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(n=>n.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(n=>n.contains(e.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let n=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(n,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,n),!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(s=>G(s))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};X();Ze();var Ci=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 s=this.alpha(t,this.previousTime),n=e-this.movingAverage,o=s*n;this.movingAverage=s*e+(1-s)*this.movingAverage,this.variance=(1-s)*(this.variance+n*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+s*n}else this.movingAverage=e;this.previousTime=t}};var x7=1.2,v7=2,E7=5e3,S7=6e4,I7=5e3,N1=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??I7;this.success=new Ci(t),this.failure=new Ci(t),this.next=new Ci(t),this.failureMultiplier=e.failureMultiplier??v7,this.timeoutMultiplier=e.timeoutMultiplier??x7,this.minTimeout=e.minTimeout??E7,this.maxTimeout=e.maxTimeout??S7,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 s=AbortSignal.timeout(t),n=Is([e.signal,s]);return J(1/0,n,s),n.start=Date.now(),n.timeout=t,n}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}))}};ot();var B1=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ho(r,e){let t=Jc();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let s=r.source;r.source[Symbol.iterator]!=null?s=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(s=r.source[Symbol.asyncIterator]());let n=new W;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await Ce(s.next(),i?.signal);return c===!0?null:l}for(;n.byteLength<i.bytes;){let{value:c,done:l}=await Ce(s.next(),i?.signal);if(l===!0)throw new B1("unexpected end of input");n.append(c)}let a=n.sublist(0,i.bytes);return n.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(n.byteLength>0){let i=r.source;r.source=(async function*(){e?.yieldBytes===!1?yield n:yield*n,yield*i})()}return r}}}Ze();var _7=1e4,A7="1.0.0",C7="ping",T7="ipfs",Gb=32,P7=!0,F1=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??T7}/${C7}/${A7}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??_7,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??P7,this.timeout=new N1({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[et]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,J(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let s=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=await e.newStream(this.protocol,{signal:s,runOnLimitedConnection:!0}),o=ho(n);t=Date.now(),await Promise.all([o.write(Gr(Gb),{signal:s}),o.read({bytes:Gb,signal:s})]),e.rtt=Date.now()-t,await o.unwrap().close({signal:s})}catch(s){if(s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",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)}};X();Se();var U1=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:([s],n)=>({...n,cid:s.toString()}),getAttributesFromYieldedValue:(s,n)=>({...n,providers:[...Array.isArray(n.providers)?n.providers:[],s.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,cid:s.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,cid:s.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([s])=>({key:K(s,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([s])=>({key:K(s,"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 _i("No content routers available");let s=this,n=new Gn;for await(let o of dn(...s.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),!n.has(o.id)&&(n.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new _i("No content routers available");await Promise.all(this.routers.filter(s=>s.provide instanceof Function).map(async s=>{await s.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new _i("No content routers available");await Promise.all(this.routers.filter(s=>s.cancelReprovide instanceof Function).map(async s=>{await s.cancelReprovide(e,t)}))}async put(e,t,s){if(!this.isStarted())throw new Tr;await Promise.all(this.routers.filter(n=>n.put instanceof Function).map(async n=>{await n.put(e,t,s)}))}async get(e,t){if(!this.isStarted())throw new Tr;return Promise.any(this.routers.filter(s=>s.get instanceof Function).map(async s=>s.get(e,t)))}};X();var K1=globalThis.CustomEvent??Event;async function*G2(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let s=e.ordered??!1,n=new EventTarget,o=[],i=fe(),a=fe(),c=!1,l,u=!1;n.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(i=fe(),await i.promise),u)break;let m={done:!1};o.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,n.dispatchEvent(new K1("task-complete"))},g=>{m.done=!0,m.err=g,n.dispatchEvent(new K1("task-complete"))})}c=!0,n.dispatchEvent(new K1("task-complete"))}catch(p){l=p,n.dispatchEvent(new K1("task-complete"))}});function h(){return s?o[0]?.done:!!o.find(p=>p.done)}function*d(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*f(){for(;h();)for(let p=0;p<o.length;p++)if(o[p].done){let m=o[p];if(o.splice(p,1),p--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(h()||(a=fe(),await a.promise),l!=null||(s?yield*d():yield*f(),l!=null))throw l;if(c&&o.length===0)break}}Se();var H1=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:([s],n)=>({...n,peer:s.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,key:K(s,"base36")}),getAttributesFromYieldedValue:(s,n)=>({...n,peers:[...Array.isArray(n.peers)?n.peers:[],s.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Ic("No peer routers available");if(e.toString()===this.peerId.toString())throw new f1("Should not try to find self");let s=this,n=dn(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(i){s.log.error(i)}})()));for await(let o of n)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new An}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ic("No peer routers available");let s=this,n=lc(1024);for await(let o of G2((async function*(){let i=dn(...s.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 s.findPeer(a.id,{...t,useCache:!1})}catch(c){s.log.error("could not find peer multiaddrs",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!n.has(o.id.toMultihash().bytes)&&(n.add(o.id.toMultihash().bytes),yield o))}};Ze();var z1=class extends Xe{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,J(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,J(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Is([this.shutdownController.signal,e?.signal]);J(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=fe(),yield(await er(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,J(1/0,this.walkController.signal);let e=Is([this.walkController.signal,this.shutdownController.signal]);J(1/0,e);let t=Date.now(),s=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let n=Gr(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(n,{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),s++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ce(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",n,this.walkers,s)}catch(n){this.log.error("random walk errored",n),this.safeDispatchEvent("walk:error",{detail:n})}this.log("no walkers left, ended walk")}).catch(n=>{this.log.error("random walk errored",n)}).finally(()=>{this.log("finished walk, found %d peers after %dms",s,Date.now()-t),this.walking=!1})}};X();var V2=32,W2=64,q1=class{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[s,n]of this.topologies)t[s]=n.size;return t}}),this.handlers=It({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 p1(`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,s){if(this.handlers.has(e)&&s?.force!==!0)throw new m1(`Handler already registered for protocol ${e}`);let n=Su.bind({ignoreUndefined:!0})({maxInboundStreams:V2,maxOutboundStreams:W2},s);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},s)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new V("invalid topology");let s=`${(Math.random()*1e9).toString(36)}${Date.now()}`,n=this.topologies.get(e);return n==null&&(n=new Map,this.topologies.set(e,n)),n.set(s,t),s}unregister(e){for(let[t,s]of this.topologies.entries())s.has(e)&&(s.delete(e),s.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail,s={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,s).then(n=>{for(let o of n.protocols){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())a.filter?.has(t)!==!1&&(a.filter?.remove(t),a.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:s}=e.detail,n=(s?.protocols??[]).filter(o=>!t.protocols.includes(o));for(let o of n){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,s=e.detail.connection,n=e.detail.peerId;for(let o of t){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())s.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(n)!==!0&&(a.filter?.add(n),a.onConnect?.(n,s))}}};X();var $1=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=It({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=It({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??_n.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new V("Transport must have a valid tag");if(this.transports.has(t))throw new V(`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,s]of this.listeners)for(this.log("closing listeners for %s",t);s.length>0;){let n=s.pop();n!=null&&e.push(n.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 s=this.dialTransportForMultiaddr(e);if(s==null)throw new v1(`No transport available for address ${String(e)}`);return t?.onProgress?.(new We("transport-manager:selected-transport",s[Symbol.toStringTag])),s.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let s of t)e=[...e,...s.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 Tr("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 g1)});let s=[];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 h=u.findIndex(d=>d===l);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),w2.matches(c)?t.ipv4.attempts++:x2.matches(c)&&t.ipv6.attempts++,s.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),w2.matches(c)&&t.ipv4.success++,x2.matches(c)&&t.ipv6.success++},h=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,h),t.errors.set(c.toString(),h),h}))}}let n=await Promise.allSettled(s);if(!(n.length>0&&n.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===_n.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new y1(`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:
8
+ `+o),r.push(n+"m+"+Qu(this.diff)+"\x1B[0m")}else r[0]=QT()+e+" "+r[0]}function QT(){return Li.hideDate!=null?"":new Date().toISOString()+" "}function JT(...r){return process.stderr.write(rh.default.format(...r)+`
9
+ `)}function eC(r){r!=null?process.env.DEBUG=r:delete process.env.DEBUG}function tC(){return process.env.DEBUG}function rC(r){r.inspectOpts={};let e=Object.keys(Li);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=Li[e[t]]}function sC(r){r.o=function(e){return this.inspectOpts.colors=this.useColors,rh.default.inspect(e,this.inspectOpts).split(`
10
+ `).map(t=>t.trim()).join(" ")},r.O=function(e){return this.inspectOpts.colors=this.useColors,rh.default.inspect(e,this.inspectOpts)}}var C4=O2({init:rC,log:JT,formatArgs:ZT,save:eC,load:tC,useColors:XT,setupFormatters:sC,colors:T4,inspectOpts:Li});var Yt=C4;Yt.formatters.b=r=>r==null?"undefined":ye.baseEncode(r);Yt.formatters.t=r=>r==null?"undefined":pr.baseEncode(r);Yt.formatters.m=r=>r==null?"undefined":If.baseEncode(r);Yt.formatters.p=r=>r==null?"undefined":r.toString();Yt.formatters.c=r=>r==null?"undefined":r.toString();Yt.formatters.k=r=>r==null?"undefined":r.toString();Yt.formatters.a=r=>r==null?"undefined":r.toString();Yt.formatters.e=r=>r==null?"undefined":P4(r.stack)??P4(r.message)??r.toString();function nC(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 sh(){return{forComponent(r){return k4(r)}}}function k4(r){let e=nC(`${r}:trace`);return Yt.enabled(`${r}:trace`)&&Yt.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=Yt(`${r}:trace`)),Object.assign(Yt(r),{error:Yt(`${r}:error`),trace:e,newScope:t=>k4(`${r}:${t}`)})}function P4(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}ce();Qt();Vt();function so(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let s=r.next(),n=s.value;return s.done===!0||n==null?{done:!0,value:void 0}:{done:!1,value:e(n)}}};return t}function nh(r){let e=ct(ye.decode(`z${r}`));return Ut(e)}var Xt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,s]of e.entries())this.map.set(t.toString(),{key:t,value:s})}[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,s)=>{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 no=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=nh(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let s=nh(t);e(s,s,this)})}has(e){return this.set.has(e.toString())}values(){return so(this.set.values(),e=>nh(e))}intersection(e){let t=new r;for(let s of e)this.has(s)&&t.add(s);return t}difference(e){let t=new r;for(let s of this)e.has(s)||t.add(s);return t}union(e){let t=new r;for(let s of e)t.add(s);for(let s of this)t.add(s);return t}};l6();var R2={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},D4={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},M4=new globalThis.TextEncoder;function oC(r,e){let t=R2[e],s=D4[e];for(let n=0;n<r.length;n++)s^=BigInt(r[n]),s=BigInt.asUintN(e,s*t);return s}function iC(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let s=R2[e],n=D4[e],o=r;for(;o.length>0;){let i=M4.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)n^=BigInt(t[a]),n=BigInt.asUintN(e,n*s)}return n}function L2(r,{size:e=32,utf8Buffer:t}={}){if(!R2[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 iC(r,e,t);r=M4.encode(r)}return oC(r,e)}be();var Sc={hash:r=>Number(L2(r,{size:32})),hashV:(r,e)=>aC(Sc.hash(r,e))};function aC(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),R(e,"base16")}be();rt();Gt();var N2=64,Fr=class{fp;h;seed;constructor(e,t,s,n=2){if(n>N2)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,s),i=ee(n);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=s}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?de(this.fp,e.fp):!1}};function oo(r,e){return Math.floor(Math.random()*(e-r))+r}var io=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=oo(0,this.contents.length-1),s=this.contents[t];return this.contents[t]=e,s}remove(e){if(!(e instanceof Fr))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(s=>e.equals(s));return t>-1?(this.contents[t]=null,!0):!1}};var cC=500,Ic=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??Sc,this.seed=e.seed??oo(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=R(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,n=(s^t.hash())%this.filterSize;if(this.buckets[s]==null&&(this.buckets[s]=new io(this.bucketSize)),this.buckets[n]==null&&(this.buckets[n]=new io(this.bucketSize)),this.buckets[s].add(t)||this.buckets[n].add(t))return this.count++,!0;let o=[s,n],i=o[oo(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new io(this.bucketSize));for(let a=0;a<cC;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 io(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=R(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[s]?.has(t)??!1;if(n)return n;let o=(s^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=R(e));let t=new Fr(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[s]?.remove(t)??!1;if(n)return this.count--,n;let o=(s^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}},lC={1:.5,2:.84,4:.95,8:.98};function uC(r=.001){return r>.002?2:r>1e-5?4:8}function O4(r,e=.001){let t=uC(e),s=lC[t],n=Math.round(r/s),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),N2);return{filterSize:n,bucketSize:t,fingerprintSize:o}}be();var oh=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??Sc,this.seed=e.seed??oo(0,Math.pow(2,10)),this.filterSeries=[new Ic({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=R(e)),this.has(e))return!0;let t=this.filterSeries.find(s=>s.reliable);if(t==null){let s=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Ic({filterSize:s,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=R(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=R(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 os(r,e=.001,t){return new oh({...O4(r,e),...t??{}})}var ih=class{filter;constructor(e,t){this.filter=os(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 B2(r,e=.001){return new ih(r,e)}var F2=class extends Xt{metric;constructor(e){super();let{name:t,metrics:s}=e;this.metric=s.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 _c(r){let{name:e,metrics:t}=r,s;return t!=null?s=new F2({name:e,metrics:t}):s=new Xt,s}ce();X();ce();lt();Ar();at();Gt();be();ws();rt();var Ac;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(s.uint32(10),s.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(s.uint32(18),s.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(s.uint32(26),s.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(s.uint32(42),s.bytes(t.signature)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={publicKey:ee(0),payloadType:ee(0),payload:ee(0),signature:ee(0)},i=s==null?t.len:t.pos+s;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=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(Ac||(Ac={}));var ah=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var nr=class r{static createFromProtobuf=e=>{let t=Ac.decode(e),s=nt(t.publicKey);return new r({publicKey:s,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,s)=>{if(t==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,i=e.marshal(),a=R4(n,o,i),c=await t.sign(a.subarray(),s);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,s)=>{let n=r.createFromProtobuf(e);if(!await n.validate(t,s))throw new ah("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:s,payload:n,signature:o}=e;this.publicKey=t,this.payloadType=s,this.payload=n,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=Ac.encode({publicKey:He(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:de(this.marshal(),e.marshal())}async validate(e,t){let s=R4(e,this.payloadType,this.payload);return this.publicKey.verify(s.subarray(),this.signature,t)}},R4=(r,e,t)=>{let s=R(r),n=hr(s.byteLength),o=hr(e.length),i=hr(t.length);return new W(n,s,o,e,i,t)};ce();function L4(r,e){let t=(s,n)=>s.toString().localeCompare(n.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((s,n)=>e[n].equals(s)))}Vt();var N4="libp2p-peer-record",B4=Uint8Array.from([3,1]);ws();rt();var Tc;(function(r){let e;(function(s){let n;s.codec=()=>(n==null&&(n=se((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:ee(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})),n),s.encode=o=>re(o,s.codec()),s.decode=(o,i)=>te(o,s.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=se((s,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),s.peerId!=null&&s.peerId.byteLength>0&&(n.uint32(10),n.bytes(s.peerId)),s.seq!=null&&s.seq!==0n&&(n.uint32(16),n.uint64(s.seq)),s.addresses!=null)for(let i of s.addresses)n.uint32(26),r.AddressInfo.codec().encode(i,n);o.lengthDelimited!==!1&&n.ldelim()},(s,n,o={})=>{let i={peerId:ee(0),seq:0n,addresses:[]},a=n==null?s.len:s.pos+n;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:{i.peerId=s.bytes();break}case 2:{i.seq=s.uint64();break}case 3:{if(o.limits?.addresses!=null&&i.addresses.length===o.limits.addresses)throw new Se('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(s,s.uint32(),{limits:o.limits?.addresses$}));break}default:{s.skipType(c&7);break}}}return i})),t),r.encode=s=>re(s,r.codec()),r.decode=(s,n)=>te(s,r.codec(),n)})(Tc||(Tc={}));var or=class r{static createFromProtobuf=e=>{let t=Tc.decode(e),s=Ut(ct(t.peerId)),n=(t.addresses??[]).map(i=>q(i.multiaddr)),o=t.seq;return new r({peerId:s,multiaddrs:n,seqNumber:o})};static DOMAIN=N4;static CODEC=B4;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:s,seqNumber:n}=e;this.peerId=t,this.multiaddrs=s??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Tc.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||!L4(this.multiaddrs,e.multiaddrs))}};function hC(r){return r[Symbol.asyncIterator]!=null}function dC(r){if(hC(r))return(async()=>{let t=[];for await(let s of r)t.push(s);return t})();let e=[];for(let t of r)e.push(t);return e}var Cc=dC;X();ce();var ir=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};Oe();async function ar(r,e,t,s){let n=new ir(s?.errorMessage);s?.errorCode!=null&&(n.code=s.errorCode);let o=s?.errorEvent??"error";return t?.aborted===!0?Promise.reject(n):new Promise((i,a)=>{function c(){K2(t,"abort",h),K2(r,e,l),K2(r,o,u)}let l=d=>{try{if(s?.filter?.(d)===!1)return}catch(f){c(),a(f);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??s?.error??new Error(`The "${s?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(n)};U2(t,"abort",h),U2(r,e,l),U2(r,o,u)})}function U2(r,e,t){r!=null&&(F4(r)?r.addEventListener(e,t):r.addListener(e,t))}function K2(r,e,t){r!=null&&(F4(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function F4(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var ch=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};Oe();var lh=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 ir)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function fC(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var uh=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=fC(),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,s)=>t&&s.signal?.aborted===!0,!0)&&(this.controller.abort(new ir),this.cleanup())}async join(e={}){let t=new lh(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 Me(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 H2(r,e){let t,s=function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)};return s.start=()=>{},s.stop=()=>{clearTimeout(t)},s}var Pc=class extends Ae{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=H2(this.emitEmpty.bind(this),1),this.emitIdle=H2(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 ch;let s=new uh(e,t);return this.enqueue(s),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),s.join(t).then(n=>(this.safeDispatchEvent("success",{detail:{job:s,result:n}}),n)).catch(n=>{if(s.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===s){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:s,error:n}}),n})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ir)}),this.clear()}async onEmpty(e){this.size!==0&&await ar(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await ar(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ar(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=gt({objectMode:!0}),s=c=>{c!=null?this.abort():this.clear(),t.end(c)},n=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{s(c.detail.error)},i=()=>{s()},a=()=>{s(new ir("Queue aborted"))};this.addEventListener("success",n),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",n),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),s()}}};var Dc=xe(oe("node:cluster"),1),ph=xe(oe("node:worker_threads"),1);Oe();var ao="lock:worker:request-read",co="lock:worker:abort-read-request",lo="lock:worker:release-read",uo="lock:master:grant-read",ho="lock:master:error-read",fo="lock:worker:request-write",po="lock:worker:abort-write-request",mo="lock:worker:release-write",go="lock:master:grant-write",yo="lock:master:error-write",un="lock:worker:finalize",hh="mortice",U4={singleProcess:!1};var z2=(r,e,t,s,n,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===n&&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(h=>{let d=f=>{if(f?.data==null)return;let p={type:f.data.type,name:f.data.name,identifier:f.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",d),h())};e.addEventListener("message",d)})},onError:h=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:h.message,name:h.name,stack:h.stack}})}}}),u.type===o&&r.safeDispatchEvent(s,{detail:{name:u.name,identifier:u.identifier}}),u.type===un&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var q2=(r,e,t,s,n,o,i,a)=>(c,l)=>{l!=null&&(l.type===s&&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 h=d=>{d.type===i&&d.identifier===l.identifier&&(c.removeListener("message",h),u())};c.on("message",h)})},onError:u=>{c.send({type:o,name:l.name,identifier:l.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),l.type===n&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier}}),l.type===un&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}}))};var kc=(r=10)=>Math.random().toString().substring(2,r+2);var dh=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(hh)}readLock(e){return this.sendRequest(ao,co,uo,ho,lo,e)}writeLock(e){return this.sendRequest(fo,po,go,yo,mo,e)}finalize(){this.channel.postMessage({type:un,name:this.name}),this.channel.close()}async sendRequest(e,t,s,n,o,i){i?.signal?.throwIfAborted();let a=kc();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 h=d=>{if(d.data?.identifier===a&&(d.data?.type===s&&(this.channel.removeEventListener("message",h),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),d.data.type===n)){this.channel.removeEventListener("message",h),i?.signal?.removeEventListener("abort",u);let f=new Error;d.data.error!=null&&(f.message=d.data.error.message,f.name=d.data.error.name,f.stack=d.data.error.stack),l(f)}};this.channel.addEventListener("message",h)})}};var fh=class{name;constructor(e){this.name=e}readLock(e){return this.sendRequest(ao,co,uo,ho,lo,e)}writeLock(e){return this.sendRequest(fo,po,go,yo,mo,e)}finalize(){if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");process.send({type:un,identifier:kc(),name:this.name})}async sendRequest(e,t,s,n,o,i){i?.signal?.throwIfAborted();let a=kc();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 h=d=>{if(d.identifier===a&&(d.type===s&&(process.removeListener("message",h),i?.signal?.removeEventListener("abort",u),c(()=>{process.send?.({type:o,identifier:a,name:this.name})})),d.type===n)){process.removeListener("message",h),i?.signal?.removeEventListener("abort",u);let f=new Error;d.error!=null&&(f.message=d.error.message,f.name=d.error.name,f.stack=d.error.stack),l(f)}};process.on("message",h)})}};function pC(){return ph.default.isMainThread===!1||ph.default.isInternalThread===!0?!1:Dc.default.isPrimary}var K4=r=>{if(r=Object.assign({},U4,r),pC()||r.singleProcess){let e=new Ae;Dc.default.on("message",q2(e,"requestReadLock","abortReadLockRequest",ao,co,ho,lo,uo)),Dc.default.on("message",q2(e,"requestWriteLock","abortWriteLockRequest",fo,po,yo,mo,go));let t=new BroadcastChannel(hh);return t.addEventListener("message",z2(e,t,"requestReadLock","abortReadLockRequest",ao,co,ho,lo,uo)),t.addEventListener("message",z2(e,t,"requestWriteLock","abortWriteLockRequest",fo,po,yo,mo,go)),t.unref?.(),e}if(Dc.default.isWorker)return new fh(r.name);if(ph.default.isMainThread===!1)return new dh(r.name);throw new Error("Not a cluster worker or worker thread")};var bo=new Map,Mc;function H4(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function mC(r){if(Mc==null&&(Mc=K4(r),!H4(Mc))){let e=Mc;e.addEventListener("requestReadLock",t=>{let s=t.detail.name,n=t.detail.identifier,o=bo.get(s);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==s||c.detail.identifier!==n||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 s=t.detail.name,n=t.detail.identifier,o=bo.get(s);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==s||c.detail.identifier!==n||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 s=t.detail.name,n=bo.get(s);n?.finalize()})}return Mc}async function $2(r,e){let t,s,n=new Promise((i,a)=>{t=i,s=a}),o=()=>{s(new ir)};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=>{s(i)}),n}var z4=(r,e)=>{let t=bo.get(r);if(t!=null)return t;let s=mC(e);if(H4(s))return t=s,bo.set(r,t),t;let n=new Pc({concurrency:1}),o;return t={async readLock(i){if(o!=null)return $2(o,i);o=new Pc({concurrency:e.concurrency,autoStart:!1});let a=o,c=$2(o,i);return n.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(i){return o=null,$2(n,i)},finalize:()=>{bo.delete(r)},queue:n},bo.set(r,t),e.autoFinalize===!0&&n.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var gC={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function G2(r){let e=Object.assign({},gC,r);return z4(e.name,e)}Yo();Cr();ws();rt();var ks;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=se((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:ee(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let h=i.uint32();switch(h>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(h&7);break}}}return l})),o),n.encode=i=>re(i,n.codec()),n.decode=(i,a)=>te(i,n.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(n){let o;n.codec=()=>(o==null&&(o=se((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),gh.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 h=i.uint32();switch(h>>>3){case 1:{l.key=i.string();break}case 2:{l.value=gh.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(h&7);break}}}return l})),o),n.encode=i=>re(i,n.codec()),n.decode=(i,a)=>te(i,n.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let s;r.codec=()=>(s==null&&(s=se((n,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),n.addresses!=null)for(let a of n.addresses)o.uint32(10),mh.codec().encode(a,o);if(n.protocols!=null)for(let a of n.protocols)o.uint32(18),o.string(a);if(n.publicKey!=null&&(o.uint32(34),o.bytes(n.publicKey)),n.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(n.peerRecordEnvelope)),n.metadata!=null&&n.metadata.size!==0)for(let[a,c]of n.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(n.tags!=null&&n.tags.size!==0)for(let[a,c]of n.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);n.updated!=null&&(o.uint32(64),o.uint64Number(n.updated)),i.lengthDelimited!==!1&&o.ldelim()},(n,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?n.len:n.pos+o;for(;n.pos<c;){let l=n.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new Se('Decode error - map field "addresses" had too many elements');a.addresses.push(mh.codec().decode(n,n.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new Se('Decode error - map field "protocols" had too many elements');a.protocols.push(n.string());break}case 4:{a.publicKey=n.bytes();break}case 5:{a.peerRecordEnvelope=n.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new La('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(n,n.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new La('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(n,n.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=n.uint64Number();break}default:{n.skipType(l&7);break}}}return a})),s),r.encode=n=>re(n,r.codec()),r.decode=(n,o)=>te(n,r.codec(),o)})(ks||(ks={}));var mh;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(t.multiaddr)),t.isCertified!=null&&(s.uint32(16),s.bool(t.isCertified)),t.observed!=null&&(s.uint32(24),s.uint64Number(t.observed)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={multiaddr:ee(0)},i=s==null?t.len:t.pos+s;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=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(mh||(mh={}));var gh;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.value!=null&&t.value!==0&&(s.uint32(8),s.uint32(t.value)),t.expiry!=null&&(s.uint32(16),s.uint64(t.expiry)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={value:0},i=s==null?t.len:t.pos+s;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=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(gh||(gh={}));lt();ce();function yC(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let s=nt(e.publicKey,t);return _s(s)}function q4(r,e,t){let s=ks.decode(e);return Ni(r,s,t)}function Ni(r,e,t){let s=new Map,n=BigInt(Date.now());for(let[o,i]of e.tags.entries())i.expiry!=null&&i.expiry<n||s.set(o,i);return{...e,id:yC(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:s}}Gt();function $4(r,e){return bC(r.addresses,e.addresses)&&wC(r.protocols,e.protocols)&&xC(r.publicKey,e.publicKey)&&vC(r.peerRecordEnvelope,e.peerRecordEnvelope)&&EC(r.metadata,e.metadata)&&SC(r.tags,e.tags)}function bC(r,e){return V4(r,e,(t,s)=>!(t.isCertified!==s.isCertified||!de(t.multiaddr,s.multiaddr)))}function wC(r,e){return V4(r,e,(t,s)=>t===s)}function xC(r,e){return G4(r,e)}function vC(r,e){return G4(r,e)}function EC(r,e){return W4(r,e,(t,s)=>de(t,s))}function SC(r,e){return W4(r,e,(t,s)=>t.value===s.value&&t.expiry===s.expiry)}function G4(r,e){return r==null&&e==null?!0:r!=null&&e!=null?de(r,e):!1}function V4(r,e,t){if(r.length!==e.length)return!1;for(let s=0;s<r.length;s++)if(!t(r[s],e[s]))return!1;return!0}function W4(r,e,t){if(r.size!==e.size)return!1;for(let[s,n]of r.entries()){let o=e.get(s);if(o==null||!t(n,o))return!1}return!0}X();be();Pe();var Ds="/",j4=new TextEncoder().encode(Ds),yh=j4[0],wo=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=R(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]!==yh)throw new Error("Invalid key")}toString(e="utf8"){return U(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ds))}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=j4),this._buf[0]!==yh){let e=new Uint8Array(this._buf.byteLength+1);e.fill(yh,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===yh;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),s=e.list();for(let n=0;n<t.length;n++){if(s.length<n+1)return!1;let o=t[n],i=s[n];if(o<i)return!0;if(o>i)return!1}return t.length<s.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(Ds).slice(1)}type(){return IC(this.baseNamespace())}name(){return _C(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ds)||(e+=Ds),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ds):new r(e.slice(0,-1).join(Ds))}child(e){return this.toString()===Ds?e:e.toString()===Ds?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(),...AC(e.map(t=>t.namespaces()))])}};function IC(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function _C(r){let e=r.split(":");return e[e.length-1]}function AC(r){return[].concat(...r)}var V2="/peers/";function Oc(r){if(!tn(r)||r.type==null)throw new V("Invalid PeerId");let e=r.toCID().toString();return new wo(`${V2}${e}`)}lt();X();Gt();X();async function Y4(r,e,t,s,n){let o=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=q(i.multiaddr)),!ln(i.multiaddr))throw new V("Multiaddr was invalid");if(!await e(r,i.multiaddr,n))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.getPeerId();return r.equals(c)&&(a=a.decapsulate(q(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function wh(r,e,t,s){if(e==null)throw new V("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new V("publicKey bytes do not match peer id publicKey bytes");let n=s.existingPeer?.peer;if(n!=null&&!r.equals(n.id))throw new V("peer id did not match existing peer id");let o=n?.addresses??[],i=new Set(n?.protocols??[]),a=n?.metadata??new Map,c=n?.tags??new Map,l=n?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=bh(d,{validate:X4})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=bh(d,{validate:Z4,map:Q4})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,p]of d)p==null?a.delete(f):a.set(f,p);a=bh([...a.entries()],{validate:X4})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[p,m]of d)m==null?f.delete(p):f.set(p,m);c=bh([...f.entries()],{validate:Z4,map:Q4})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;n?.id.publicKey!=null?u=He(n.id.publicKey):e.publicKey!=null?u=He(e.publicKey):r.publicKey!=null&&(u=He(r.publicKey));let h={addresses:await Y4(r,s.addressFilter??(async()=>!0),o,s.existingPeer?.peerPB.addresses,s),protocols:[...i.values()].sort((d,f)=>d.localeCompare(f)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return h.addresses.forEach(d=>{d.observed=s.existingPeer?.peerPB.addresses?.find(f=>de(f.multiaddr,f.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete h.publicKey,h}function bh(r,e){let t=new Map;for(let[s,n]of r)n!=null&&e.validate(s,n);for(let[s,n]of r.sort(([o],[i])=>o.localeCompare(i)))n!=null&&t.set(s,e.map?.(s,n)??n);return t}function X4(r,e){if(typeof r!="string")throw new V("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new V("Metadata value must be a Uint8Array")}function Z4(r,e){if(typeof r!="string")throw new V("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new V("Tag value must be an integer");if(e.value<0||e.value>100)throw new V("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new V("Tag ttl must be an integer");if(e.ttl<0)throw new V("Tag ttl must be between greater than 0")}}function Q4(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let s={value:e.value??0};return t!=null&&(s.expiry=t),s}function J4(r){let e=r.toString().split("/")[2],t=Re.parse(e,pr);return Jr(t)}function W2(r,e,t){let s=J4(r);return q4(s,e,t)}function TC(r,e){return{prefix:V2,filters:(r.filters??[]).map(t=>({key:s,value:n})=>t(W2(s,n,e))),orders:(r.orders??[]).map(t=>(s,n)=>t(W2(s.key,s.value,e),W2(n.key,n.value,e)))}}var xh=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=_c({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:G2({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 s=this.getLock(e);try{let n=await s.lock.readLock(t);return()=>{n(),this.maybeRemoveLock(e,s)}}catch(n){throw this.maybeRemoveLock(e,s),n}}async getWriteLock(e,t){let s=this.getLock(e);try{let n=await s.lock.writeLock(t);return()=>{n(),this.maybeRemoveLock(e,s)}}catch(n){throw this.maybeRemoveLock(e,s),n}}async has(e,t){try{return await this.load(e,t),!0}catch(s){if(s.name!=="NotFoundError")throw s}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Oc(e),t)}async load(e,t){let s=Oc(e),n=await this.datastore.get(s,t),o=ks.decode(n);if(this.#r(e,o))throw await this.datastore.delete(s,t),new Bn;return Ni(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,s){let n=await this.#e(e,s),o=await wh(e,t,"patch",{...s,addressFilter:this.addressFilter});return this.#t(e,o,n)}async patch(e,t,s){let n=await this.#e(e,s),o=await wh(e,t,"patch",{...s,addressFilter:this.addressFilter,existingPeer:n});return this.#t(e,o,n)}async merge(e,t,s){let n=await this.#e(e,s),o=await wh(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#t(e,o,n)}async*all(e){for await(let{key:t,value:s}of this.datastore.query(TC(e??{},this.maxAddressAge),e)){let n=J4(t);if(n.equals(this.peerId))continue;let o=ks.decode(s);if(this.#r(n,o)){await this.datastore.delete(t,e);continue}yield Ni(n,o,this.peerId.equals(n)?1/0:this.maxAddressAge)}}async#e(e,t){try{let s=Oc(e),n=await this.datastore.get(s,t),o=ks.decode(n);if(this.#r(e,o))throw await this.datastore.delete(s,t),new Bn;return{peerPB:o,peer:Ni(e,o,this.maxAddressAge)}}catch(s){s.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",s)}}async#t(e,t,s,n){t.updated=Date.now();let o=ks.encode(t);return await this.datastore.put(Oc(e),o,n),{peer:Ni(e,t,this.maxAddressAge),previous:s?.peer,updated:s==null||!$4(t,s.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let s=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,o=t.addresses.filter(i=>i.observed!=null&&i.observed>n);return s&&o.length===0}};var j2=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 xh(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let s of this.store.all(t))e(s)}async all(e){return Cc(this.store.all(e))}async delete(e,t){let s=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{s()}}async has(e,t){let s=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),s?.()}}async get(e,t){let s=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{s?.()}}async getInfo(e,t){let s=await this.get(e,t);return{id:s.id,multiaddrs:s.addresses.map(({multiaddr:n})=>n)}}async save(e,t,s){let n=await this.store.getWriteLock(e,s);try{let o=await this.store.save(e,t,s);return this.#e(e,o),o.peer}finally{n?.()}}async patch(e,t,s){let n=await this.store.getWriteLock(e,s);try{let o=await this.store.patch(e,t,s);return this.#e(e,o),o.peer}finally{n?.()}}async merge(e,t,s){let n=await this.store.getWriteLock(e,s);try{let o=await this.store.merge(e,t,s);return this.#e(e,o),o.peer}finally{n?.()}}async consumePeerRecord(e,t,s){let n=tn(t)?t:tn(t?.expectedPeer)?t.expectedPeer:void 0,o=tn(t)||t===void 0?s:t,i=await nr.openAndCertify(e,or.DOMAIN,o),a=Jr(i.publicKey.toCID());if(n?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",n,a),!1;let c=or.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=nr.createFromProtobuf(l.peerRecordEnvelope),h=or.createFromProtobuf(u.payload);if(h.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",h.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 ew(r,e={}){return new j2(r,e)}var vh=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 CC(r){return r[Symbol.asyncIterator]!=null}function PC(r){if(CC(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Y2=PC;function kC(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],s=[];return{peek:()=>e.next(),push:n=>{s.push(n)},next:()=>s.length>0?{done:!1,value:s.shift()}:e.next(),[t](){return this}}}var Eh=kC;function DC(r){return r[Symbol.asyncIterator]!=null}function MC(r,e){let t=0;if(DC(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let s=Eh(r),{value:n,done:o}=s.next();if(o===!0)return(function*(){})();let i=e(n,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield n);for(let c of s)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield n);for(let c of s)a(c,t++)&&(yield c)})()}var xo=MC;function OC(r){return r[Symbol.asyncIterator]!=null}function RC(r,e){return OC(r)?(async function*(){yield*(await Cc(r)).sort(e)})():(function*(){yield*Cc(r).sort(e)})()}var X2=RC;function LC(r){return r[Symbol.asyncIterator]!=null}function NC(r,e){return LC(r)?(async function*(){let t=0;if(!(e<1)){for await(let s of r)if(yield s,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let s of r)if(yield s,t++,t===e)return}})()}var Z2=NC;var Sh=class{put(e,t,s){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:s,value:n}of e)await this.put(s,n,t),yield s}async*getMany(e,t={}){for await(let s of e)yield{key:s,value:await this.get(s,t)}}async*deleteMany(e,t={}){for await(let s of e)await this.delete(s,t),yield s}batch(){let e=[],t=[];return{put(s,n){e.push({key:s,value:n})},delete(s){t.push(s)},commit:async s=>{await Y2(this.putMany(e,s)),e=[],await Y2(this.deleteMany(t,s)),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 s=this._all(e,t);if(e.prefix!=null){let n=e.prefix;s=xo(s,o=>o.key.toString().startsWith(n))}if(Array.isArray(e.filters)&&(s=e.filters.reduce((n,o)=>xo(n,o),s)),Array.isArray(e.orders)&&(s=e.orders.reduce((n,o)=>X2(n,o),s)),e.offset!=null){let n=0,o=e.offset;s=xo(s,()=>n++>=o)}return e.limit!=null&&(s=Z2(s,e.limit)),s}queryKeys(e,t){let s=this._allKeys(e,t);if(e.prefix!=null){let n=e.prefix;s=xo(s,o=>o.toString().startsWith(n))}if(Array.isArray(e.filters)&&(s=e.filters.reduce((n,o)=>xo(n,o),s)),Array.isArray(e.orders)&&(s=e.orders.reduce((n,o)=>X2(n,o),s)),e.offset!=null){let n=e.offset,o=0;s=xo(s,()=>o++>=n)}return e.limit!=null&&(s=Z2(s,e.limit)),s}};var Ih=class extends Sh{data;constructor(){super(),this.data=new Map}put(e,t,s){return s?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let s=this.data.get(e.toString());if(s==null)throw new vh;return s}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[s,n]of this.data.entries())yield{key:new wo(s),value:n},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let s of this.data.keys())yield new wo(s),t?.signal?.throwIfAborted()}};Oe();Vr();be();ce();function Rc(r,e){let t,s=function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)};return s.start=()=>{},s.stop=()=>{clearTimeout(t)},s}var rw=xe(tw(),1),BC=["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"],FC=BC.map(r=>new rw.Netmask(r));function Q2(r){for(let e of FC)if(e.contains(r))return!0;return!1}function UC(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function KC(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),s=e[e.length-2].padStart(4,"0"),n=`${parseInt(s.substring(0,2),16)}.${parseInt(s.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Q2(n)}function HC(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function zC(r){let e=r.split(":"),t=e[e.length-1];return Q2(t)}function qC(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 Bi(r){if((0,$e.isIPv4)(r))return Q2(r);if(UC(r))return KC(r);if(HC(r))return zC(r);if((0,$e.isIPv6)(r))return qC(r)}var Ce=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Z=(r,e)=>({match:t=>{let s=t[0];return s?.code!==r||s.value==null||e!=null&&s.value!==e?!1:t.slice(1)}}),ue=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),At=(...r)=>({match:e=>{let t;for(let s of r){let n=s.match(e);n!==!1&&(t==null||n.length<t.length)&&(t=n)}return t??!1}}),fe=(...r)=>({match:e=>{for(let t of r){let s=t.match(e);if(s===!1)return!1;e=s}return e}});function Ie(...r){function e(n){if(n==null)return!1;let o=n.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(n){return e(n)!==!1}function s(n){let o=e(n);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:s}}var $C=Z(421),sw=Ie($C),Ah=Z(54),Th=Z(55),Ch=Z(56),em=Z(53),sX=Ie(Ah,ue(Z(421))),nX=Ie(Th,ue(Z(421))),oX=Ie(Ch,ue(Z(421))),iX=Ie(At(em,Ch,Ah,Th),ue(Z(421))),nw=fe(Z(4),ue(Z(43))),ow=fe(ue(Z(42)),Z(41),ue(Z(43))),tm=At(nw,ow),vo=At(tm,em,Ah,Th,Ch),iw=Ie(At(tm,fe(At(em,Ch,Ah,Th),ue(Z(421))))),rm=Ie(nw),sm=Ie(ow),aX=Ie(tm),nm=fe(vo,Z(6)),Nc=fe(vo,Z(273)),Ms=Ie(fe(nm,ue(Z(421)))),cX=Ie(Nc),om=fe(Nc,Ce(460),ue(Z(421))),Ph=fe(Nc,Ce(461),ue(Z(421))),GC=At(om,Ph),lX=Ie(om),aw=Ie(Ph),J2=At(vo,nm,Nc,om,Ph),cw=At(fe(J2,Ce(477),ue(Z(421)))),Bc=Ie(cw),lw=At(fe(J2,Ce(478),ue(Z(421))),fe(J2,Ce(448),ue(Z(449)),Ce(477),ue(Z(421)))),Fc=Ie(lw),uw=fe(Nc,Ce(280),ue(Z(466)),ue(Z(466)),ue(Z(421))),im=Ie(uw),hw=fe(Ph,Ce(465),ue(Z(466)),ue(Z(466)),ue(Z(421))),am=Ie(hw),_h=At(cw,lw,fe(nm,ue(Z(421))),fe(GC,ue(Z(421))),fe(vo,ue(Z(421))),uw,hw,Z(421)),dw=Ie(_h),VC=fe(_h,Ce(290),Z(421)),Os=Ie(VC),WC=At(fe(_h,Ce(290),Ce(281),ue(Z(421))),fe(_h,Ce(281),ue(Z(421))),fe(Ce(281),ue(Z(421)))),cm=Ie(WC),jC=At(fe(vo,Z(6),Ce(480),ue(Z(421))),fe(vo,Ce(480),ue(Z(421)))),uX=Ie(jC),YC=fe(vo,At(fe(Z(6,"443"),Ce(480)),fe(Z(6),Ce(443)),fe(Z(6),Ce(448),Ce(480)),fe(Ce(448),Ce(480)),Ce(448),Ce(443)),ue(Z(421))),hX=Ie(YC),XC=At(fe(Z(777),ue(Z(421)))),dX=Ie(XC),ZC=At(fe(Z(400),ue(Z(421)))),fX=Ie(ZC);var lm=class extends Map{metric;constructor(e){super();let{name:t,metrics:s}=e;this.metric=s.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 Tt(r){let{name:e,metrics:t}=r,s;return t!=null?s=new lm({name:e,metrics:t}):s=new Map,s}var fw=864e13;var QC=448,um=449,JC=53,e7=54,t7=55,r7=56,kh=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Tt({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=this.findHost(e);for(let s of this.mappings.values())if(s.domain===t)return!0;return!1}add(e,t){t.forEach(s=>{this.log("add DNS mapping %s to %s",s,e);let n=Bi(s)===!0;this.mappings.set(s,{domain:e,verified:n,expires:n?fw-Date.now():0,lastVerified:n?fw-Date.now():void 0})})}remove(e){let t=this.findHost(e),s=!1;for(let[n,o]of this.mappings.entries())o.domain===t&&(this.log("removing %s to %s DNS mapping %e",n,o.domain),this.mappings.delete(n),s=s||o.verified);return s}getAll(e){let t=[];for(let s=0;s<e.length;s++){let o=e[s].multiaddr.stringTuples(),i=o[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(o,c.domain)&&(e.splice(s,1),s--,t.push({multiaddr:q(`/${o.map(u=>[ki(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let s=0;s<e.length;s++)if(e[s][0]===QC&&e[s+1]?.[0]!==um)return e.splice(s+1,0,[um,t]),!0;return!1}confirm(e,t){let s=this.findHost(e),n=!1;for(let[o,i]of this.mappings.entries())i.domain===s&&(this.log("marking %s to %s DNS mapping as verified",o,i.domain),n=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return n}unconfirm(e,t){let s=this.findHost(e),n=!1;for(let[o,i]of this.mappings.entries())i.domain===s&&(this.log("removing verification of %s to %s DNS mapping",o,i.domain),n=n||i.verified,i.verified=!1,i.expires=Date.now()+t);return n}findHost(e){for(let t of e.stringTuples())if(t[0]===um||t[0]===JC||t[0]===e7||t[0]===t7||t[0]===r7)return t[1]}};var hm=4,dm=41,fm=6,s7=273,Dh=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Tt({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=e.stringTuples();for(let s of this.mappings.values())for(let n of s)if(n.externalIp===t[0][1])return!0;return!1}add(e,t,s,n=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:s,externalPort:n,externalFamily:(0,$e.isIPv4)(s)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=e.stringTuples(),s=t[0][1]??"",n=t[1][0]===fm?"tcp":"udp",o=parseInt(t[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===s&&u.externalPort===o&&u.protocol===n&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,s,o,n),i=i||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return i}getAll(e){let t=[];for(let{multiaddr:s}of e){let n=s.stringTuples(),o;if((n[0][0]===hm||n[0][0]===dm)&&n[1][0]===fm?o=`${n[0][1]}-${n[1][1]}-tcp`:(n[0][0]===hm||n[0][0]===dm)&&n[1][0]===s7&&(o=`${n[0][1]}-${n[1][1]}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)n[0][0]=a.externalFamily===4?hm:dm,n[0][1]=a.externalIp,n[1][1]=`${a.externalPort}`,t.push({multiaddr:q(`/${n.map(c=>[ki(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let n=e.stringTuples()[0][1],o=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===n&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let s=e.stringTuples(),n=s[0][1]??"",o=s[1][0]===fm?"tcp":"udp",i=parseInt(s[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===i&&u.protocol===o&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,i,o),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function pw(r){try{for(let{code:e,value:t}of r.getComponents())if(e!==42&&t!=null){if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}}catch{}return!1}function Mh(r){try{for(let{code:e}of r.getComponents())if(e!==42)return e===4||e===41}catch{}return!1}function Rs(r){try{if(!Mh(r))return!1;let[[,e]]=r.stringTuples();return e==null?!1:Bi(e)??!1}catch{}return!0}var n7={maxObservedAddresses:10},Oh=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Tt({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??n7.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&&(Rs(e)||pw(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 s=e.toString(),n=this.addresses.get(s)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.log("marking observed address %a as verified",s),this.addresses.set(s,n),o}};var o7=[4,41,53,54,55,56];function pm(r){try{for(let{code:e}of r.getComponents())if(e!==42)return o7.includes(e)}catch{}return!1}var i7={maxObservedAddresses:10},Rh=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Tt({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??i7.maxObservedAddresses}get(e,t){if(Rs(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let s=this.toKey(e),n=this.addresses.get(s);return n==null&&(n={verified:!pm(e),expires:0},this.addresses.set(s,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),s=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),s}confirm(e,t){let s=this.toKey(e),n=this.addresses.get(s)??{verified:!1,expires:0,lastVerified:0},o=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.addresses.set(s,n),o}unconfirm(e,t){let s=this.toKey(e),n=this.addresses.get(s)??{verified:!1,expires:0},o=n.verified;return n.verified=!1,n.expires=Date.now()+t,this.addresses.set(s,n),o}toKey(e){if(pm(e)){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}};var mw=6e4,gw={maxObservedAddresses:10,addressVerificationTTL:mw*10,addressVerificationRetry:mw*5},a7=r=>r;function mm(r,e){let t=r.getPeerId();return t!=null&&G(t).equals(e)&&(r=r.decapsulate(q(`/p2p/${e.toString()}`))),r}var Lh=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:s=[],announce:n=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=s.map(i=>i.toString()),this.announce=new Set(n.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new Oh(e,t),this.dnsMappings=new kh(e,t),this.ipMappings=new Dh(e,t),this.transportAddresses=new Rh(e,t),this.announceFilter=t.announceFilter??a7,this.observedAddressFilter=os(1024),this.addressVerificationTTL=t.addressVerificationTTL??gw.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??gw.addressVerificationRetry,this._updatePeerStoreAddresses=Rc(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.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>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=e.stringTuples(),s=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(s)||(this.observedAddressFilter.add(s),e=mm(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=mm(e,this.components.peerId);let s=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),s=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1)),s||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=mm(e,this.components.peerId);let s=!1;this.observed.has(e)&&!this.observed.remove(e)&&s&&(s=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&s&&(s=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&s&&(s=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&s&&(s=!1),s&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(s=>{if(!s.verified)return!1;let n=s.multiaddr.toString();return e.has(n)?!1:(e.add(n),!0)}).map(s=>s.multiaddr);return this.announceFilter(t.map(s=>{let n=q(s);return n.getComponents().pop()?.value===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(e)}),e.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL)));let s=this.getAppendAnnounceAddrs();return s.length>0&&(this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(s)}),t=t.concat(s.map(n=>({multiaddr:n,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,s,n=t,o="tcp"){this.ipMappings.add(e,t,s,n,o),this.observed.removePrefixed(`/ip${(0,$e.isIPv4)(s)?4:6}/${s}/${o}/${n}`)}removePublicAddressMapping(e,t,s,n=t,o="tcp"){this.ipMappings.remove(q(`/ip${(0,$e.isIPv4)(s)?4:6}/${s}/${o}/${n}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;let t=e.toOptions();if(t.family===6||t.host==="127.0.0.1"||Bi(t.host)===!0)return!1;let s=this.components.transportManager.getListeners(),n=[o=>Bc.exactMatch(o)||Fc.exactMatch(o),o=>Ms.exactMatch(o),o=>aw.exactMatch(o)];for(let o of n){if(!o(e))continue;let i=s.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.transport),!0}return!1}};X();var yw;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(yw||(yw={}));var Nh=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Bh=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Fi=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Uc=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Fh=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Uh=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Kh=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Kc=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Hh=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},zh=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},qh=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},$h=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Gh=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Eo=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},So=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Vh=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Wh=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var gm=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,s]of Object.entries(e))this.components[t]=s;this.components.logger==null&&(this.components.logger=sh())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>fu(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},l7=["metrics","connectionProtector","dns"],u7=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function bw(r={}){let e=new gm(r);return new Proxy(e,{get(s,n,o){if(typeof n=="string"&&!u7.includes(n)){let i=e.components[n];if(i==null&&!l7.includes(n))throw new Nh(`${n} not set`);return i}return Reflect.get(s,n,o)},set(s,n,o){return typeof n=="string"?e.components[n]=o:Reflect.set(s,n,o),!0}})}function ww(r){let e={};for(let t of Object.values(r.components))for(let s of h7(t))e[s]=!0;for(let t of Object.values(r.components))for(let s of d7(t))if(e[s]!==!0)throw new Bh(`Service "${f7(t)}" required capability "${s}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function h7(r){return Array.isArray(r?.[Ye])?r[Ye]:[]}function d7(r){return Array.isArray(r?.[Kn])?r[Kn]:[]}function f7(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function xw(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async()=>!1,denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}X();var vw=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},p7=new WeakMap;function m7({clearTimeout:r,setTimeout:e}={}){return(t,{value:s,signal:n}={})=>{if(n?.aborted)return Promise.reject(vw());let o,i,a,c=r??clearTimeout,l=()=>{c(o),a(vw())},u=()=>{n&&n.removeEventListener("abort",l)},h=new Promise((d,f)=>{i=()=>{u(),d(s)},a=f,o=(e??setTimeout)(i,t)});return n&&n.addEventListener("abort",l,{once:!0}),p7.set(h,()=>{c(o),o=null,i()}),h}}var g7=m7(),Ew=g7;var jh=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}},Yh=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Xh=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new ym}async consume(e,t=1,s={}){let n=this.getKey(e),o=this._getKeySecDuration(s),i=this.memoryStorage.incrby(n,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(n,i.consumedPoints,this.blockDuration)),new jh("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await Ew(a)}return i}penalty(e,t=1,s={}){let n=this.getKey(e),o=this._getKeySecDuration(s),i=this.memoryStorage.incrby(n,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,s={}){let n=this.getKey(e),o=this._getKeySecDuration(s),i=this.memoryStorage.incrby(n,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let s=t*1e3,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:n,isFirstInDuration:!1}}set(e,t,s=0){let n=(s>=0?s:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,s),{remainingPoints:0,msBeforeNext:n===0?-1:n,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)}},ym=class{storage;constructor(){this.storage=new Map}incrby(e,t,s){let n=this.storage.get(e);if(n!=null){let o=n.expiresAt!=null?n.expiresAt.getTime()-new Date().getTime():-1;return n.expiresAt==null||o>0?(n.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,s)}return this.set(e,t,s)}set(e,t,s){let n=s*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},n),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:n===0?-1:n,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}};X();ce();function Zh(r){if(tn(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let s=e[0].getPeerId();t=s==null?void 0:G(s),e.forEach(n=>{if(!ln(n))throw new sn("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(t!=null)throw new V("Multiaddrs must all have the same peer id or have no peer id")}else{let i=G(o);if(t?.equals(i)!==!0)throw new V("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(s=>!sw.exactMatch(s)),{peerId:t,multiaddrs:e}}var y7=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Sw(r,e){let t=r?.streams?.map(n=>n.protocol)??[],s=e?.closableProtocols??y7;if(!(t.filter(n=>n!=null&&!s.includes(n)).length>0))try{await r?.close(e)}catch(n){r?.abort(n)}}function Hc(r){try{let e;typeof r=="string"?e=q(r):e=r;let t=new Set([...e.getComponents().map(s=>s.name)]);if(!t.has("ipcidr")){let n=t.has("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(n)}return w2(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var Qh=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(s=>Hc(s)),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,s=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,s),t<=s)return;let n=new Xt;for(let c of e){let l=c.remotePeer;if(!n.has(l)){n.set(l,0);try{let u=await this.peerStore.get(l);n.set(l,[...u.tags.values()].reduce((h,d)=>h+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),i=Math.max(t-s,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=>u.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Sw(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((s,n)=>{let o=s.timeline.open,i=n.timeline.open;return o<i?1:o>i?-1:0}).sort((s,n)=>s.direction==="outbound"&&n.direction==="inbound"?1:s.direction==="inbound"&&n.direction==="outbound"?-1:0).sort((s,n)=>s.streams.length>n.streams.length?1:s.streams.length<n.streams.length?-1:0).sort((s,n)=>{let o=t.get(s.remotePeer)??0,i=t.get(n.remotePeer)??0;return o>i?1:o<i?-1:0})}};var Iw="last-dial-failure",_w="last-dial-success";var Aw=300,Jh=100;X();X();Oe();X();Oe();X();var ed=class{deferred;signal;constructor(e){this.signal=e,this.deferred=me(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Bt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function b7(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var td=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=b7(),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,s)=>t&&s.signal?.aborted===!0,!0)&&(this.controller.abort(new Bt),this.cleanup())}async join(e={}){let t=new ed(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 Me(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 Ui=class extends Ae{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Rc(this.emitEmpty.bind(this),1),this.emitIdle=Rc(this.emitIdle.bind(this),1)}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.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 Yh;let s=new td(e,t);return this.enqueue(s),this.safeDispatchEvent("add"),this.tryToStartAnother(),s.join(t).then(n=>(this.safeDispatchEvent("completed",{detail:n}),this.safeDispatchEvent("success",{detail:{job:s,result:n}}),n)).catch(n=>{if(s.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===s){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:s,error:n}}),n})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Bt)}),this.clear()}async onEmpty(e){this.size!==0&&await ar(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await ar(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ar(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=gt({objectMode:!0}),s=c=>{c!=null?this.abort():this.clear(),t.end(c)},n=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{s(c.detail.error)},i=()=>{s()},a=()=>{s(new Bt("Queue aborted"))};this.addEventListener("completed",n),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),s()}}};var rd=class extends Ui{constructor(e={}){super({...e,sort:(t,s)=>t.options.priority>s.options.priority?-1:t.options.priority<s.options.priority?1:0})}};function cr(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 s(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let n=e.signal;return n.clear=s,n}Oe();be();function Tw(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function bm(r){if(!Mh(r))return!1;let{address:e}=r.nodeAddress();return Tw(e)}function w7(r,e){let t=Ms.exactMatch(r.multiaddr),s=Ms.exactMatch(e.multiaddr);if(t&&!s)return-1;if(!t&&s)return 1;let n=Fc.exactMatch(r.multiaddr),o=Fc.exactMatch(e.multiaddr);if(n&&!o)return-1;if(!n&&o)return 1;let i=Bc.exactMatch(r.multiaddr),a=Bc.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=cm.exactMatch(r.multiaddr),l=cm.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=im.exactMatch(r.multiaddr),h=im.exactMatch(e.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;let d=am.exactMatch(r.multiaddr),f=am.exactMatch(e.multiaddr);return d&&!f?-1:!d&&f?1:0}function x7(r,e){let t=bm(r.multiaddr),s=bm(e.multiaddr);return t&&!s?1:!t&&s?-1:0}function v7(r,e){let t=Rs(r.multiaddr),s=Rs(e.multiaddr);return t&&!s?1:!t&&s?-1:0}function E7(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function S7(r,e){let t=Os.exactMatch(r.multiaddr),s=Os.exactMatch(e.multiaddr);return t&&!s?1:!t&&s?-1:0}function Cw(r){return r.sort(w7).sort(E7).sort(S7).sort(v7).sort(x7)}async function wm(r,e,t){let s=t.depth??0;if(s>(t.maxRecursiveDepth??32))throw new Wh("Max recursive depth reached");let n=!1,o=[];for(let i of Object.values(e))if(i.canResolve(r)){n=!0;let a=await i.resolve(r,t);for(let c of a)o.push(...await wm(c,e,{...t,depth:s+1}))}return n===!1&&o.push(r),o}var zc={maxParallelDials:Jh,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:to}},sd=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??zc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??zc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??zc.dialTimeout,this.connections=t.connections??new Xt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??zc.resolvers,this.shutDownController=new AbortController,Y(1/0,this.shutDownController.signal),this.queue=new rd({concurrency:t.maxParallelDials??zc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",s=>{s.detail?.error.name!==Bt.name&&this.log.error("error in dial queue - %e",s.detail)})}start(){this.shutDownController=new AbortController,Y(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:s,multiaddrs:n}=Zh(e),o=Array.from(this.connections.values()).flat().find(a=>t.force===!0||a.limits!=null?!1:a.remotePeer.equals(s)?!0:n.find(c=>c.equals(a.remoteAddr)));if(o?.status==="open")return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new ke("dial-queue:already-connected")),o;let i=this.queue.queue.find(a=>{if(s?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of n)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",s);for(let a of n)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new ke("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Is("Dial queue is full");return this.log("creating dial target for %p",s,n.map(a=>a.toString())),t.onProgress?.(new ke("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new ke("dial-queue:start-dial"));let c=cr([this.shutDownController.signal,a.signal]);Y(1/0,c);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:s,priority:t.priority??Sm,multiaddrs:new Set(n.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let s=e.peerId,n=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",s);i||n.size>0;){c++,i=!1;let u=[],h=new Set(e.multiaddrs);n.clear(),this.log("calculating addrs to dial %p from %s",s,[...h]);let d=await this.calculateMultiaddrs(s,h,{...e,signal:t});for(let f of d){if(o.has(f.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",f.multiaddr,s);continue}u.push(f)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",s,u.map(f=>f.multiaddr.toString())),e?.onProgress?.(new ke("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 Is("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(f.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",f.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[_w]:R(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",s,m)}return p}catch(p){if(this.log.error("dial failed to %a",f.multiaddr,p),o.add(f.multiaddr.toString()),s!=null)try{await this.components.peerStore.merge(s,{metadata:{[Iw]:R(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",s,m)}if(t.aborted)throw new Qr(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,s={}){let n=[...t].map(h=>({multiaddr:q(h),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Is("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Kc("The dial request is blocked by gater.allowDialPeer");if(n.length===0){this.log("loading multiaddrs for %p",e);try{let h=await this.components.peerStore.get(e);n.push(...h.addresses),this.log("loaded multiaddrs for %p",e,n.map(({multiaddr:d})=>d.toString()))}catch(h){if(h.name!=="NotFoundError")throw h}}if(n.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let h=await this.components.peerRouting.findPeer(e,s);this.log("found multiaddrs for %p in the peer routing",e,n.map(({multiaddr:d})=>d.toString())),n.push(...h.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(h){h.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,h)}}}let o=(await Promise.all(n.map(async h=>{let d=await wm(h.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...s});return d.length===1&&d[0].equals(h.multiaddr)?h:d.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let h=`/p2p/${e.toString()}`;o=o.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(h),isCertified:d.isCertified}:d)}let i=o.filter(h=>{if(this.components.transportManager.dialTransportForMultiaddr(h.multiaddr)==null)return!1;let d=h.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let h of i){let d=h.multiaddr.toString(),f=a.get(d);if(f!=null){f.isCertified=f.isCertified||h.isCertified||!1;continue}a.set(d,h)}let c=[...a.values()];if(c.length===0)throw new qh("The dial request has no valid addresses");let l=[];for(let h of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(h.multiaddr)||l.push(h);let u=this.addressSorter==null?Cw(l):l.sort(this.addressSorter);if(u.length===0)throw new Kc("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:h})=>h.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:h})=>h.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let s=await this.calculateMultiaddrs(void 0,new Set(e.map(n=>n.toString())),t);return t.runOnLimitedConnection===!1?s.find(n=>!Os.matches(n.multiaddr))!=null:!0}catch(s){this.log.trace("error calculating if multiaddr(s) were dialable",s)}return!1}};X();var hn=class extends Ui{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Lw=xe(Ow(),1);var _7=Object.prototype.toString,A7=r=>_7.call(r)==="[object Error]",T7=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 Im(r){if(!(r&&A7(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:s}=r;return t==="Load failed"?s===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:T7.has(t)}var _m=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}},Rw=(r,e,t)=>{let s=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=s,r};async function Am(r,e){return new Promise((t,s)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let n=Lw.default.operation(e),o=()=>{n.stop(),s(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",o),n.stop()};n.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof _m)throw c.originalError;if(c instanceof TypeError&&!Im(c))throw c;if(Rw(c,a,e),await e.shouldRetry(c)||(n.stop(),s(c)),await e.onFailedAttempt(c),!n.retry(c))throw n.mainError()}catch(l){Rw(l,a,e),i(),s(l)}}})})}var nd=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 hn({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",s=>{this.maybeReconnect(s.detail).catch(n=>{this.log.error("failed to maybe reconnect to %p - %e",s.detail,n)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);Nw(t)&&(this.queue.has(e)||this.queue.add(async s=>{await Am(async n=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:s?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,n,this.retries,o),o}},{signal:s?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async s=>{this.log.error("failed to reconnect to %p - %e",e,s);let n={};[...t.tags.keys()].forEach(o=>{o.startsWith(ci)&&(n[o]=void 0)}),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async s=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,s)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>Nw(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(s=>{this.log.error(s)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function Nw(r){for(let e of r.tags.keys())if(e.startsWith(ci))return!0;return!1}var Sm=50,Tm={maxConnections:Aw,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},od=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??Tm.maxConnections,this.maxConnections<1)throw new V("Connection Manager maxConnections must be greater than 0");this.connections=new Xt,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(s=>Hc(s)),this.deny=(t.deny??[]).map(s=>Hc(s)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Tm.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Xh({points:t.inboundConnectionThreshold??Tm.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Qh({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(s=>q(s))}),this.dialQueue=new sd(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Jh,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:to},connections:this.connections}),this.reconnectQueue=new nd({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 s of t)e[s.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let s of t)for(let n of s.streams){let o=`${n.direction} ${n.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 s of this.connections.values())for(let n of s){let o={};for(let i of n.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[s,n]of Object.entries(e)){n=n.sort((i,a)=>i-a);let o=Math.floor(n.length*.9);t[s]=n[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await pu(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 mu(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let s of t)e.push((async()=>{try{await s.close()}catch(n){this.log.error(n)}})());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 V("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(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let s=t.remotePeer,n=!this.connections.has(s),o=this.connections.get(s)??[];o.push(t),this.connections.set(s,o),s.publicKey!=null&&s.type==="RSA"&&await this.peerStore.patch(s,{publicKey:s.publicKey}),n&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,s=t.remotePeer,o=(this.connections.get(s)??[]).filter(i=>i.id!==t.id);this.connections.set(s,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",s),this.connections.delete(s),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let s of this.connections.values())t=t.concat(s);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Lr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:s}=Zh(e);if(this.peerId.equals(s))throw new hi("Can not dial self");if(s!=null&&t.force!==!0){this.log("dial %p",s);let a=this.getConnections(s).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p as %a",s,a.remoteAddr),t.onProgress?.(new ke("dial-queue:already-connected")),a}let n=await this.dialQueue.dial(e,{...t,priority:t.priority??Sm});if(n.status!=="open")throw new ui("Remote closed connection during opening");let o=this.connections.get(n.remotePeer);o==null&&(o=[],this.connections.set(n.remotePeer,o));let i=!1;for(let a of o)if(a.id===n.id&&(i=!0),t.force!==!0&&a.id!==n.id&&a.remoteAddr.equals(n.remoteAddr))return n.abort(new sn("Duplicate multiaddr connection")),a;return i||o.push(n),n}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let s=this.connections.get(e)??[];await Promise.all(s.map(async n=>{try{await n.close(t)}catch(o){n.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(n=>n.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(n=>n.contains(e.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let n=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(n,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,n),!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(s=>q(s))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};X();Oe();var Ki=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 s=this.alpha(t,this.previousTime),n=e-this.movingAverage,o=s*n;this.movingAverage=s*e+(1-s)*this.movingAverage,this.variance=(1-s)*(this.variance+n*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+s*n}else this.movingAverage=e;this.previousTime=t}};var k7=1.2,D7=2,M7=5e3,O7=6e4,R7=5e3,id=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??R7;this.success=new Ki(t),this.failure=new Ki(t),this.next=new Ki(t),this.failureMultiplier=e.failureMultiplier??D7,this.timeoutMultiplier=e.timeoutMultiplier??k7,this.minTimeout=e.minTimeout??M7,this.maxTimeout=e.maxTimeout??O7,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 s=AbortSignal.timeout(t),n=cr([e.signal,s]);return Y(1/0,n,s),n.start=Date.now(),n.timeout=t,n}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}))}};at();var ad=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function _o(r,e){let t=xl();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let s=r.source;r.source[Symbol.iterator]!=null?s=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(s=r.source[Symbol.asyncIterator]());let n=new W;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await Me(s.next(),i?.signal);return c===!0?null:l}for(;n.byteLength<i.bytes;){let{value:c,done:l}=await Me(s.next(),i?.signal);if(l===!0)throw new ad("unexpected end of input");n.append(c)}let a=n.sublist(0,i.bytes);return n.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(n.byteLength>0){let i=r.source;r.source=(async function*(){e?.yieldBytes===!1?yield n:yield*n,yield*i})()}return r}}}Oe();var L7=1e4,N7="1.0.0",B7="ping",F7="ipfs",Bw=32,U7=!0,cd=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??F7}/${B7}/${N7}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??L7,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??U7,this.timeout=new id({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ye]=["@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 s=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=await e.newStream(this.protocol,{signal:s,runOnLimitedConnection:!0}),o=_o(n);t=Date.now(),await Promise.all([o.write(Zr(Bw),{signal:s}),o.read({bytes:Bw,signal:s})]),e.rtt=Date.now()-t,await o.unwrap().close({signal:s})}catch(s){if(s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",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)}};X();Pe();var ld=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:([s],n)=>({...n,cid:s.toString()}),getAttributesFromYieldedValue:(s,n)=>({...n,providers:[...Array.isArray(n.providers)?n.providers:[],s.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,cid:s.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,cid:s.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([s])=>({key:U(s,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([s])=>({key:U(s,"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 Fi("No content routers available");let s=this,n=new no;for await(let o of En(...s.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),!n.has(o.id)&&(n.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new Fi("No content routers available");await Promise.all(this.routers.filter(s=>s.provide instanceof Function).map(async s=>{await s.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Fi("No content routers available");await Promise.all(this.routers.filter(s=>s.cancelReprovide instanceof Function).map(async s=>{await s.cancelReprovide(e,t)}))}async put(e,t,s){if(!this.isStarted())throw new Lr;await Promise.all(this.routers.filter(n=>n.put instanceof Function).map(async n=>{await n.put(e,t,s)}))}async get(e,t){if(!this.isStarted())throw new Lr;return Promise.any(this.routers.filter(s=>s.get instanceof Function).map(async s=>s.get(e,t)))}};X();var ud=globalThis.CustomEvent??Event;async function*Cm(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let s=e.ordered??!1,n=new EventTarget,o=[],i=me(),a=me(),c=!1,l,u=!1;n.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(i=me(),await i.promise),u)break;let m={done:!1};o.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,n.dispatchEvent(new ud("task-complete"))},g=>{m.done=!0,m.err=g,n.dispatchEvent(new ud("task-complete"))})}c=!0,n.dispatchEvent(new ud("task-complete"))}catch(p){l=p,n.dispatchEvent(new ud("task-complete"))}});function h(){return s?o[0]?.done:!!o.find(p=>p.done)}function*d(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*f(){for(;h();)for(let p=0;p<o.length;p++)if(o[p].done){let m=o[p];if(o.splice(p,1),p--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(h()||(a=me(),await a.promise),l!=null||(s?yield*d():yield*f(),l!=null))throw l;if(c&&o.length===0)break}}Pe();var hd=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:([s],n)=>({...n,peer:s.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,key:U(s,"base36")}),getAttributesFromYieldedValue:(s,n)=>({...n,peers:[...Array.isArray(n.peers)?n.peers:[],s.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Uc("No peer routers available");if(e.toString()===this.peerId.toString())throw new Fh("Should not try to find self");let s=this,n=En(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(i){s.log.error(i)}})()));for await(let o of n)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new Bn}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Uc("No peer routers available");let s=this,n=os(1024);for await(let o of Cm((async function*(){let i=En(...s.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 s.findPeer(a.id,{...t,useCache:!1})}catch(c){s.log.error("could not find peer multiaddrs",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!n.has(o.id.toMultihash().bytes)&&(n.add(o.id.toMultihash().bytes),yield o))}};Oe();var dd=class extends Ae{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=cr([this.shutdownController.signal,e?.signal]);Y(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=me(),yield(await ar(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,Y(1/0,this.walkController.signal);let e=cr([this.walkController.signal,this.shutdownController.signal]);Y(1/0,e);let t=Date.now(),s=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let n=Zr(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(n,{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),s++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Me(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",n,this.walkers,s)}catch(n){this.log.error("random walk errored",n),this.safeDispatchEvent("walk:error",{detail:n})}this.log("no walkers left, ended walk")}).catch(n=>{this.log.error("random walk errored",n)}).finally(()=>{this.log("finished walk, found %d peers after %dms",s,Date.now()-t),this.walking=!1})}};X();var Pm=32,km=64,fd=class{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[s,n]of this.topologies)t[s]=n.size;return t}}),this.handlers=Tt({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 Uh(`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,s){if(this.handlers.has(e)&&s?.force!==!0)throw new Kh(`Handler already registered for protocol ${e}`);let n=Wu.bind({ignoreUndefined:!0})({maxInboundStreams:Pm,maxOutboundStreams:km},s);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},s)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new V("invalid topology");let s=`${(Math.random()*1e9).toString(36)}${Date.now()}`,n=this.topologies.get(e);return n==null&&(n=new Map,this.topologies.set(e,n)),n.set(s,t),s}unregister(e){for(let[t,s]of this.topologies.entries())s.has(e)&&(s.delete(e),s.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail,s={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,s).then(n=>{for(let o of n.protocols){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())a.filter?.has(t)!==!1&&(a.filter?.remove(t),a.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:s}=e.detail,n=(s?.protocols??[]).filter(o=>!t.protocols.includes(o));for(let o of n){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,s=e.detail.connection,n=e.detail.peerId;for(let o of t){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())s.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(n)!==!0&&(a.filter?.add(n),a.onConnect?.(n,s))}}};X();var pd=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=Tt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Tt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Nn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new V("Transport must have a valid tag");if(this.transports.has(t))throw new V(`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,s]of this.listeners)for(this.log("closing listeners for %s",t);s.length>0;){let n=s.pop();n!=null&&e.push(n.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 s=this.dialTransportForMultiaddr(e);if(s==null)throw new Vh(`No transport available for address ${String(e)}`);return t?.onProgress?.(new ke("transport-manager:selected-transport",s[Symbol.toStringTag])),s.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let s of t)e=[...e,...s.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 Lr("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 Hh)});let s=[];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 h=u.findIndex(d=>d===l);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),rm.matches(c)?t.ipv4.attempts++:sm.matches(c)&&t.ipv6.attempts++,s.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),rm.matches(c)&&t.ipv4.success++,sm.matches(c)&&t.ipv6.success++},h=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,h),t.errors.set(c.toString(),h),h}))}}let n=await Promise.allSettled(s);if(!(n.length>0&&n.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Nn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new zh(`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:
11
11
  ${[...t.errors.entries()].map(([o,i])=>`
12
12
  ${o}: ${`${i.stack??i}`.split(`
13
13
  `).join(`
14
14
  `)}
15
- `).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,s=e.ipv6.success===0;return t&&s}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let s=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let n=t.pop();n!=null&&s.push(n.close())}await Promise.all(s),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)}};X();var mt="/multistream/1.0.0";X();wr();ot();var G1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},V1=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},W1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Jr(r,e={}){let t=ho(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Le(e.maxDataLength));let s=e?.lengthDecoder??as,n=e?.lengthEncoder??rr;return{read:async i=>{let a=-1,c=new W;for(;;){c.append(await t.read({...i,bytes:1}));try{a=s(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new G1("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new W1("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new V1("message length too long");return t.read({...i,bytes:a})},write:async(i,a)=>{await t.write(new W(n(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new W(...i.flatMap(l=>[n(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}wr();ot();ge();X();ge();Se();var k7=L(`
16
- `);async function fo(r,e,t){await r.write(e,t)}async function Vb(r,e,t){await r.writeV(e,t)}async function D7(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==k7[0])throw e.log.error("Invalid mss message - missing newline",t),new Yt("Missing newline");return t.sublist(0,-1)}async function tn(r,e){let t=await D7(r,e);return K(t.subarray())}async function Ti(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return M7(r,e[0],t);let s=Jr(r,{...t,maxDataLength:1024}),n=e.shift();if(n==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',mt,n);let o=L(`${mt}
17
- `),i=L(`${n}
18
- `);await Vb(s,[o,i],t),t.log.trace("select: reading multistream-select header");let a=await tn(s,t);if(t.log.trace('select: read "%s"',a),a===mt&&(t.log.trace("select: reading protocol response"),a=await tn(s,t),t.log.trace('select: read "%s"',a)),a===n)return{stream:s.unwrap(),protocol:n};for(let c of e){t.log.trace('select: write "%s"',c),await fo(s,L(`${c}
19
- `),t),t.log.trace("select: reading protocol response");let l=await tn(s,t);if(t.log.trace('select: read "%s" for "%s"',l,c),l===c)return{stream:s.unwrap(),protocol:c}}throw new Cn("protocol selection failed")}function M7(r,e,t){let s=r.sink.bind(r),n=r.source,o=!1,i=!1,a=fe(),c=!1,l=!1,u=fe(),h=!1,d=!1,f=fe(),p=Jr({sink:s,source:n},{...t,maxDataLength:1024});r.sink=async w=>{let{sink:b}=p.unwrap();await b((async function*(){let x=!1;for await(let E of w){if(l&&await u.promise,c)yield E;else{l=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',mt,e,E.byteLength);let P=`${e}
20
- `;yield new W(Uint8Array.from([19]),L(`${mt}
21
- `),rr(P.length),L(P),E).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',mt,e,E.byteLength),c=!0,l=!1,u.resolve(),m().catch(T=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,T)})}x=!0}x||await m()})())};async function m(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await g()),h||(t.log.trace("optimistic: doing read protocol for %s stream",e),await y())}finally{i=!1,o=!0,a.resolve()}}async function g(){if(l){await u.promise;return}l=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',mt,e),await p.writeV([L(`${mt}
22
- `),L(`${e}
23
- `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',mt,e)}finally{c=!0,l=!1,u.resolve()}}async function y(){if(d){await f.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let w=await tn(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',w),w===mt&&(w=await tn(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',w,e),w!==e)throw new Cn("protocol selection failed")}finally{h=!0,d=!1,f.resolve()}}if(r.source=(async function*(){await m(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*p.unwrap().source})(),r.closeRead!=null){let w=r.closeRead.bind(r);r.closeRead=async b=>{o||await m().catch(x=>{t.log.error("could not negotiate protocol before close read",x)}),await w(b)}}if(r.closeWrite!=null){let w=r.closeWrite.bind(r);r.closeWrite=async b=>{o||await m().catch(x=>{t.log.error("could not negotiate protocol before close write",x)}),await w(b)}}if(r.close!=null){let w=r.close.bind(r);r.close=async b=>{let x=[];l&&x.push(u.promise),d&&x.push(f.promise),x.length>0?await Ce(Promise.all(x),b?.signal):(o=!0,i=!1,a.resolve()),await w(b)}}return{stream:r,protocol:e}}ot();ge();async function Pi(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let s=Jr(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let n=await tn(s,t);if(t.log.trace('handle: read "%s"',n),n===mt){t.log.trace('handle: respond with "%s" for "%s"',mt,n),await fo(s,L(`${mt}
24
- `),t),t.log.trace('handle: responded with "%s" for "%s"',mt,n);continue}if(e.includes(n))return t.log.trace('handle: respond with "%s" for "%s"',n,n),await fo(s,L(`${n}
25
- `),t),t.log.trace('handle: responded with "%s" for "%s"',n,n),{stream:s.unwrap(),protocol:n};if(n==="ls"){let o=new W(...e.map(i=>sr.single(L(`${i}
26
- `))),L(`
27
- `));t.log.trace('handle: respond with "%s" for %s',e,n),await fo(s,o,t),t.log.trace('handle: responded with "%s" for %s',e,n);continue}t.log.trace('handle: respond with "na" for "%s"',n),await fo(s,L(`na
28
- `),t),t.log('handle: responded with "na" for "%s"',n)}}ce();Ze();X();Ze();var O7=500,X2=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;constructor(e,t){this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.status="open",this.timeline=t.maConn.timeline,this.encryption=t.encryption,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this.tags=[],t.muxerFactory!=null&&(this.multiplexer=t.muxerFactory.protocol,this.muxer=t.muxerFactory.createStreamMuxer({direction:this.direction,log:this.log,onIncomingStream:s=>{this.onIncomingStream(s)}}),Promise.all([this.muxer.sink(this.maConn.source),this.maConn.sink(this.muxer.source)]).catch(s=>{this.log.error("error piping data through muxer - %e",s)}))}[Symbol.toStringTag]="Connection";[yy]=!0;get streams(){return this.muxer?.streams??[]}newStream=async(e,t={})=>{if(this.status==="closing")throw new Nl("the connection is being closed");if(this.status==="closed")throw new Yo("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Pa("Cannot open protocol stream on limited connection");if(this.muxer==null)throw new co("Connection is not multiplexed");this.log.trace("starting new stream for protocols %s",e);let s=await this.muxer.newStream();this.log.trace("started new stream %s for protocols %s",s.id,e);try{if(t.signal==null){s.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);J(1/0,c),t={...t,signal:c}}s.log.trace("selecting protocol from protocols %s",e);let{stream:n,protocol:o}=await Ti(s,e,{...t,log:s.log,yieldBytes:!0});s.log("selected protocol %s",o);let i=R7(o,this.components.registrar,t),a=Yb(o,"outbound",this);if(a>=i){let c=new Qo(`Too many outbound protocol streams for protocol "${o}" - ${a}/${i}`);throw s.abort(c),c}return await this.components.peerStore.merge(this.remotePeer,{protocols:[o]}),s.source=n.source,s.sink=n.sink,s.protocol=o,n.closeWrite!=null&&(s.closeWrite=n.closeWrite),n.closeRead!=null&&(s.closeRead=n.closeRead),n.close!=null&&(s.close=n.close),this.components.metrics?.trackProtocolStream(s,this),s.direction="outbound",s}catch(n){throw 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,n),s.timeline.close==null&&s.abort(n),n}};onIncomingStream(e){let t=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);J(1/0,t),Promise.resolve().then(async()=>{let s=this.components.registrar.getProtocols(),{stream:n,protocol:o}=await Pi(e,s,{signal:t,log:e.log,yieldBytes:!1});this.log("incoming %s stream opened",o);let i=L7(o,this.components.registrar);if(Yb(o,"inbound",this)===i){let u=new ql(`Too many inbound protocol streams for protocol "${o}" - limit ${i}`);throw e.abort(u),u}e.source=n.source,e.sink=n.sink,e.protocol=o,n.closeWrite!=null&&(e.closeWrite=n.closeWrite),n.closeRead!=null&&(e.closeRead=n.closeRead),n.close!=null&&(e.close=n.close),await this.components.peerStore.merge(this.remotePeer,{protocols:[o]},{signal:t}),this.components.metrics?.trackProtocolStream(e,this);let{handler:c,options:l}=this.components.registrar.getHandler(o);if(this.limits!=null&&l.runOnLimitedConnection!==!0)throw new Pa("Cannot open protocol stream on limited connection");await c({connection:this,stream:e})}).catch(async s=>{this.log.error("error handling incoming stream id %s - %e",e.id,s),e.abort(s)})}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(O7);J(1/0,t),e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this.muxer?.close(e),await this.maConn.close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.muxer?.abort(e),this.maConn.abort(e),this.status="closed",this.timeline.close=Date.now())}};function Xb(r,e){return new X2(r,e)}function L7(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return V2}function R7(r,e,t={}){try{let{options:s}=e.getHandler(r);if(s.maxOutboundStreams!=null)return s.maxOutboundStreams}catch(s){if(s.name!=="UnhandledProtocolError")throw s}return t.maxOutboundStreams??W2}function Yb(r,e,t){let s=0;return t.streams.forEach(n=>{n.direction===e&&n.protocol===r&&s++}),s}var j1=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=It({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(s=>{this.connectionEncrypters.set(s.protocol,s)}),this.streamMuxers=It({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(s=>{this.streamMuxers.set(s.protocol,s)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,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 s=this.components.connectionGater[e];if(s==null)return;if(await s.apply(this.components.connectionGater,t)===!0)throw new w1(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Is([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return J(1/0,t),t}async upgradeInbound(e,t){let s=!1,n=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),s=await Ce(this.components.connectionManager.acceptIncomingConnection(e),n),!s)throw new x1("Connection denied");await Ce(this.shouldBlockConnection("denyInboundConnection",e),n),await this._performUpgrade(e,"inbound",{...t,signal:n})}catch(o){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[o.name??"Error"]:!0}),o}finally{n.clear(),s&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let s=e.remoteAddr.getPeerId(),n;s!=null&&(n=$(s),await Ce(this.shouldBlockConnection("denyOutboundConnection",n,e),t.signal));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(s){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[s.name??"Error"]:!0}),s}}async _performUpgrade(e,t,s){let n,o,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let u=e;if(s?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),u=await d.protect(e,s))}try{if(n=u,s?.skipEncryption!==!0){s?.onProgress?.(new We(`upgrader:encrypt-${t}-connection`)),{conn:n,remotePeer:o,protocol:c,streamMuxer:a}=await(t==="inbound"?this._encryptInbound(u,s):this._encryptOutbound(u,s));let d={...u,...n};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,d)}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new js(`${t} connection that skipped encryption must have a peer id`);let f=$(d);c="native",o=f}if(o.equals(this.components.peerId)){let d=new Xo("Can not dial self");throw e.abort(d),d}if(i=n,s?.muxerFactory!=null)a=s.muxerFactory;else if(a==null&&this.streamMuxers.size>0){s?.onProgress?.(new We(`upgrader:multiplex-${t}-connection`));let d=await(t==="inbound"?this._multiplexInbound({...u,...n},this.streamMuxers,s):this._multiplexOutbound({...u,...n},this.streamMuxers,s));a=d.muxerFactory,i=d.stream}}catch(d){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e);let h=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:o,limits:s?.limits});return h.log("successfully upgraded %s connection",t),h}_createConnection(e){let{id:t,cryptoProtocol:s,direction:n,maConn:o,upgradedConn:i,remotePeer:a,muxerFactory:c,limits:l}=e,u,h=o.timeline;return o.timeline=new Proxy(h,{set:(...d)=>(d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(f){u.log.error("error closing connection after timeline close %e",f)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(f=>{u.log.error("error thrown while dispatching connection:close event %e",f)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now(),u=Xb(this.components,{id:t,maConn:i,remotePeer:a,direction:n,muxerFactory:c,encryption:s,limits:l,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout}),this.events.safeDispatchEvent("connection:open",{detail:u}),u}async _encryptInbound(e,t){let s=Array.from(this.connectionEncrypters.keys());try{let{stream:n,protocol:o}=await Pi(e,s,{...t,log:e.log}),i=this.connectionEncrypters.get(o);if(i==null)throw new lo(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await i.secureInbound(n,t),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,n),new lo(n.message)}}async _encryptOutbound(e,t){let s=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",s);let{stream:n,protocol:o}=await Ti(e,s,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(o);if(i==null)throw new lo(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await i.secureOutbound(n,t),protocol:o}}catch(n){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,n),new lo(n.message)}}async _multiplexOutbound(e,t,s){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:i}=await Ti(e,n,{...s,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new co(String(o))}}async _multiplexInbound(e,t,s){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:i}=await Pi(e,n,{...s,log:e.log}),a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new co(String(o))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var rn=we(re("node:process"),1);var Y1="2.10.0",X1="js-libp2p";function Qb(r,e){let t="node",s=rn.default.versions.node;return rn.default.versions.deno!=null&&(t="deno",s=rn.default.versions.deno),rn.default.versions.bun!=null&&(t="bun",s=rn.default.versions.bun),rn.default.versions.electron!=null&&(t="electron",s=rn.default.versions.electron),`${r??X1}/${e??Y1} ${t}/${s.replaceAll("v","")}`}var Z1=class extends Xe{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Xe,s=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=s(l),h=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||h},J(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ou(),this.log=this.logger.forComponent("libp2p"),this.services={};let n=e.nodeInfo?.name??X1,o=e.nodeInfo?.version??Y1,i=this.components=Ab({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:n,version:o,userAgent:e.nodeInfo?.userAgent??Qb(n,o)},logger:this.logger,events:t,datastore:e.datastore??new Ju,connectionGater:Tb(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",lb(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(h=>h.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new j1(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??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new $1(this.components,e.transportManager)),this.configureComponent("connectionManager",new R1(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new F1(this.components,e.connectionMonitor)),this.configureComponent("registrar",new q1(this.components)),this.configureComponent("addressManager",new u1(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 H1(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 U1(this.components,{routers:c})),this.configureComponent("randomWalk",new z1(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),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],h=u(this.components);if(h==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=h,this.configureComponent(l,h),h[bp]!=null&&(this.log("registering service %s for content routing",l),c.push(h[bp])),h[wp]!=null&&(this.log("registering service %s for peer routing",l),a.push(h[wp])),h[Ta]!=null&&(this.log("registering service %s for peer discovery",l),h[Ta].addEventListener?.("peer",d=>{this.#e(d)}))}Cb(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")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Gn;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,s={}){if(t==null)throw new V("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new V("no protocols were provided to open a stream");return(await this.dial(e,s)).newStream(t,s)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Js(e)&&(e=$(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let s=Ye([L("/pk/"),e.toMultihash().bytes]),n=await this.contentRouting.get(s,t),o=Je(n);return await this.peerStore.patch(e,{publicKey:o},t),o}async handle(e,t,s){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.handle(n,t,s)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.unhandle(s,t)}))}async register(e,t,s){return this.components.registrar.register(e,t,s)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(s=>{this.log.error(s)})}};async function Jb(r={}){r.privateKey??=await my("Ed25519");let e=new Z1({...await M4(r),peerId:vp(r.privateKey)});return r.start!==!1&&await e.start(),e}var hw=we(re("net"),1);X();var uw=we(re("net"),1);X();var tw=we(re("node:os"),1);function ew(r){return!!(r.startsWith("169.254.")||r.toLowerCase().startsWith("fe80"))}var N7={4:"IPv4",6:"IPv6"};function B7(r){return["0.0.0.0","::"].includes(r)}function F7(r){let e=[],t=tw.default.networkInterfaces();for(let[,s]of Object.entries(t))if(s!=null)for(let n of s)ew(n.address)||n.family===N7[r]&&e.push(n.address);return e}function rw(r,e){if(r==null)return[];let t=r.toOptions();if(B7(t.host)){let s=[];for(let n of F7(t.family))s.push(G(`/ip${t.family}/${n}/${t.transport}/${e??t.port}`));return s}return[G(`/ip${t.family}/${t.host}/${t.transport}/${e??t.port}`)]}Ze();var Z2=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Q2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},sw=r=>globalThis.DOMException===void 0?new Q2(r):new DOMException(r),nw=r=>{let e=r.reason===void 0?sw("This operation was aborted."):r.reason;return e instanceof Error?e:sw(e)};function J2(r,e){let{milliseconds:t,fallback:s,message:n,customTimers:o={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:f}=e;f.aborted&&h(nw(f)),a=()=>{h(nw(f))},f.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,h);return}let d=new Z2;i=o.setTimeout.call(void 0,()=>{if(s){try{u(s())}catch(f){h(f)}return}typeof r.cancel=="function"&&r.cancel(),n===!1?u():n instanceof Error?h(n):(d.message=n??`Promise timed out after ${t} milliseconds`,h(d))},t),(async()=>{try{u(await r)}catch(f){h(f)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},l}var U7=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 K7(r,e,t){let s,n=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!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}=U7(r),h=(...f)=>{let p=t.multiArgs?f:f[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(s(),o(c)))},d=f=>{s(),i(f)};s=()=>{for(let f of a)u(f,h);for(let f of t.rejectionEvents)u(f,d)};for(let f of a)l(f,h);for(let f of t.rejectionEvents)l(f,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(n.cancel=s,typeof t.timeout=="number"){let o=J2(n,{milliseconds:t.timeout});return o.cancel=s,o}return n}function em(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let s=K7(r,e,t),n=s.then(o=>o[0]);return n.cancel=s.cancel,n}X();X();function ow(r,e){if(typeof r!="string")throw new V(`invalid ip provided: ${r}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new V(`invalid port provided: ${e}`);if((0,Fe.isIPv4)(r))return G(`/ip4/${r}/tcp/${e}`);if((0,Fe.isIPv6)(r))return G(`/ip6/${r}/tcp/${e}`);throw new V(`invalid ip:port for creating a multiaddr: ${r}:${e}`)}function iw(r){if(z7(r))return(async function*(){let e=r.getReader();try{for(;;){let{done:t,value:s}=await e.read();if(t)return;yield s}}finally{e.releaseLock()}})();if(H7(r))return r;throw new Error("unknown stream")}function H7(r){return r[Symbol.asyncIterator]!=null}function z7(r){return typeof r?.getReader=="function"}function aw(r){return async e=>{let t=async()=>{q7(e)&&await e.return(void 0)},s,n,o=y=>{s=y,t().catch(w=>{w=new AggregateError([s,w],"The Writable emitted an error, additionally an error occurred while ending the Source")}).finally(()=>{n?.(y)})},i,a=!1,c=()=>{a=!0,i?.()},l,u=!1,h=()=>{u=!0,l?.()},d,f=()=>{d?.()},p=async()=>new Promise((y,w)=>{i=d=y,n=w,r.once("drain",f)}),m=async()=>(await t(),new Promise((y,w)=>{if(a||u||s!=null){y();return}l=i=y,n=w})),g=()=>{r.removeListener("error",o),r.removeListener("close",c),r.removeListener("finish",h),r.removeListener("drain",f)};r.once("error",o),r.once("close",c),r.once("finish",h);try{for await(let y of e){if(!r.writable||r.destroyed||s!=null)break;r.write(y)||await p()}}catch(y){s==null&&r.destroy(y),s=y}try{if(r.writable&&r.end(),await m(),s!=null)throw s}finally{g()}}}function q7(r){return r.return!=null}function tm(r){return{sink:aw(r),source:iw(r)}}var cw=we(re("os"),1),lw=we(re("path"),1);function ki(r,e={}){let t=r.getPath();if(t!=null)return cw.default.platform()==="win32"?{path:lw.default.join("\\\\.\\pipe\\",t)}:{path:t};let s=r.toOptions();return{...e,...s,ipv6Only:s.family===6}}var Q1=(r,e)=>{let t,s=e.direction,n=e.metrics,o=e.metricPrefix??"",i=e.socketInactivityTimeout??12e4,a=e.socketCloseTimeout??500,c=!1,l=!1;e.listeningAddr?.getPath()!=null&&(e.remoteAddr=e.listeningAddr),e.remoteAddr?.getPath()!=null&&(e.localAddr=e.remoteAddr),r.on("error",g=>{l=!0,c||(m.log.error("%s socket error - %e",s,g),n?.increment({[`${o}error`]:!0})),r.destroy(),m.timeline.close=Date.now()});let u;if(e.remoteAddr!=null)u=e.remoteAddr;else{if(r.remoteAddress==null||r.remotePort==null)throw new V("Could not determine remote address or port");u=ow(r.remoteAddress,r.remotePort)}let h=ki(u),d=h.path??`${h.host??""}:${h.port??""}`,{sink:f,source:p}=tm(r);r.setTimeout(i),r.once("timeout",()=>{c=!0,m.log("%s %s socket read timeout",s,d),n?.increment({[`${o}timeout`]:!0}),r.destroy(new Vr),m.timeline.close=Date.now()}),r.once("close",()=>{!c&&!l&&(m.log("%s %s socket close",s,d),n?.increment({[`${o}close`]:!0})),r.destroy(),m.timeline.close=Date.now()}),r.once("end",()=>{m.log("%s %s socket end",s,d),n?.increment({[`${o}end`]:!0})});let m={async sink(g){try{await f((async function*(){for await(let y of g)y instanceof Uint8Array?yield y:yield y.subarray()})())}catch(y){y.type!=="aborted"&&m.log.error("%s %s error in sink - %e",s,d,y)}r.end()},source:p,remoteAddr:u,timeline:{open:Date.now()},async close(g={}){if(r.closed){m.log("the %s %s socket is already closed",s,d);return}if(r.destroyed){m.log("the %s %s socket is already destroyed",s,d);return}if(t!=null)return t.promise;try{t=fe(),r.end();let y=$7(r),w=g.signal??AbortSignal.timeout(a);r.writableLength>0&&(m.log("%s %s draining socket",s,d),await er(y,"drain",w,{errorEvent:"error"}),m.log("%s %s socket drained",s,d)),await Promise.all([er(y,"close",w,{errorEvent:"error"}),r.destroy()])}catch(y){this.abort(y)}finally{t.resolve()}},abort:g=>{m.log("%s %s socket abort due to error - %e",s,d,g),r.destroy(),m.timeline.close=Date.now()},log:e.logger.forComponent("libp2p:tcp:connection")};return m};function $7(r){return{addEventListener:(t,s)=>{r.addListener(t,s)},removeEventListener:(t,s)=>{r.removeListener(t,s)}}}var ut;(function(r){r[r.INACTIVE=0]="INACTIVE",r[r.ACTIVE=1]="ACTIVE",r[r.PAUSED=2]="PAUSED"})(ut||(ut={}));var J1=class extends Xe{context;server;sockets=new Set;status={code:ut.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,this.shutdownController=new AbortController,J(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=uw.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 V("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]:ut.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!==ut.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!==ut.ACTIVE)throw e.destroy(),new Tr("Server is not listening yet");let t;try{t=Q1(e,{listeningAddr:this.status.listeningAddr,socketInactivityTimeout:this.context.socketInactivityTimeout,socketCloseTimeout:this.context.socketCloseTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,logger:this.context.logger,direction:"inbound"})}catch(s){this.log.error("inbound connection failed",s),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(s=>{this.log.error("error attempting to listen server once connection count under limit",s),this.context.closeServerOnMaxConnections?.onListenError?.(s)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&this.pause()}).catch(async s=>{this.log.error("inbound connection upgrade failed",s),this.metrics.errors?.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),t.abort(s)})}getAddrs(){if(this.status.code===ut.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[G(`/unix/${encodeURIComponent(e)}`)]:rw(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===ut.ACTIVE||this.status.code===ut.PAUSED)throw new zl("server is already listening");try{this.status={code:ut.ACTIVE,listeningAddr:e,netConfig:ki(e,this.context)},await this.resume()}catch(t){throw this.status={code:ut.INACTIVE},t}}async close(){let e=[];this.server.listening&&e.push(em(this.server,"close")),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(t=>{t.readable&&(e.push(em(t,"close")),t.destroy())}),await Promise.all(e)}async resume(){if(this.server.listening||this.status.code===ut.INACTIVE)return;let e=this.status.netConfig;await new Promise((t,s)=>{this.server.once("error",s),this.server.listen(e,t)}),this.status={...this.status,code:ut.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===ut.PAUSED&&e){this.status={code:ut.INACTIVE};return}!this.server.listening||this.status.code!==ut.ACTIVE||(this.log("closing server on %s",this.server.address()),this.status=e?{code:ut.INACTIVE}:{...this.status,code:ut.PAUSED},this.server.close())}};var eh=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"})})}[Ly]=!0;[Symbol.toStringTag]="@libp2p/tcp";[et]=["@libp2p/transport"];async dial(e,t){t.keepAlive=t.keepAlive??!0,t.noDelay=t.noDelay??!0;let s=await this._connect(e,t),n;try{n=Q1(s,{remoteAddr:e,socketInactivityTimeout:this.opts.outboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.metrics?.events,logger:this.components.logger,direction:"outbound"})}catch(o){throw this.metrics?.errors.increment({outbound_to_connection:!0}),s.destroy(o),o}try{return this.log("new outbound connection %s",n.remoteAddr),await t.upgrader.upgradeOutbound(n,t)}catch(o){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection",o),n.abort(o),o}}async _connect(e,t){t.signal.throwIfAborted(),t.onProgress?.(new We("tcp:open-connection"));let s;return new Promise((n,o)=>{let i=Date.now(),a=ki(e,{...this.opts.dialOpts??{},...t});this.log("dialing %a",e),s=hw.default.connect(a);let c=f=>{this.log.error("dial to %a errored - %e",e,f);let p=a.path??`${a.host??""}:${a.port}`;f.message=`connection error ${p}: ${f.message}`,this.metrics?.events.increment({error:!0}),d(f)},l=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let f=new Vr(`Connection timeout after ${Date.now()-i}ms`);s.emit("error",f)},u=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),d()},h=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),d(new Lt)},d=f=>{if(s.removeListener("error",c),s.removeListener("timeout",l),s.removeListener("connect",u),t.signal!=null&&t.signal.removeEventListener("abort",h),f!=null){o(f);return}n(s)};s.on("error",c),s.on("timeout",l),s.on("connect",u),t.signal.addEventListener("abort",h)}).catch(n=>{throw s?.destroy(),n})}createListener(e){return new J1({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,socketInactivityTimeout:this.opts.inboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(t=>Es.exactMatch(t)||t.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function dw(r={}){return e=>new eh(e,r)}ft();X();ce();function rm(){let r=fe(),e=!1;return{sink:async t=>{if(e)throw new Error("already piped");e=!0,r.resolve(t)},source:(async function*(){yield*await r.promise})()}}function fw(){let r=rm(),e=rm();return[{source:r.source,sink:e.sink},{source:e.source,sink:r.sink}]}nt();var Di=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var ns=we(re("node:crypto"),1),Th=we(xw(),1);var cT=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,vw=cT?uT:lT;function lT(r=0){return new Uint8Array(r)}function uT(r=0){let e=Buffer.allocUnsafe(r);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Ew=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 cm=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 Sw={env:{abort:(r,e,t,s)=>{throw Error(`abort: ${r}:${e}:${t}:${s}`)}}};function lm(r){return(r!==void 0?r:WebAssembly.validate(cm))?new WebAssembly.Instance(new WebAssembly.Module(cm),Sw).exports:new WebAssembly.Instance(new WebAssembly.Module(Ew),Sw).exports}var tt,hT,Oi,Tc,Pc,dT,Iw,fT;function pT(r){tt=lm(r),hT=!!tt.HAS_SIMD.valueOf(),Oi=tt.input.value,Tc=tt.output.value,Pc=new Uint8Array(tt.memory.buffer,Oi,tt.INPUT_LENGTH),dT=new Uint8Array(tt.memory.buffer,Tc,tt.PARALLEL_FACTOR*32),Iw=new Uint8Array(tt.memory.buffer,Tc,32),fT=new Uint32Array(tt.memory.buffer,Oi,tt.INPUT_LENGTH)}pT();function _w(r){return r.length===64?mT(r):r.length<=tt.INPUT_LENGTH?(Pc.set(r),tt.digest(r.length),um()):(tt.init(),gT(r),yT())}function mT(r){if(r.length===64)return Pc.set(r),tt.digest64(Oi,Tc),um();throw new Error("InvalidLengthForDigest64")}function gT(r){let e=tt.INPUT_LENGTH;if(r.length>e)for(let t=0;t<r.length;t+=e){let s=r.subarray(t,t+e);Pc.set(s),tt.update(Oi,s.length)}else Pc.set(r),tt.update(Oi,r.length)}function yT(){return tt.final(Tc),um()}function um(){let r=vw(32);return r.set(Iw),r}ot();var Tw=we(Cw(),1),wT=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Pw=(0,Tw.default)();var kw=Pw&&!wT;var ate=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Pw,cte=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,lte=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+"_"+"ENV"]==="test",ute=typeof navigator<"u"&&navigator.product==="ReactNative";function Mw(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ih(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function ah(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function _t(r,...e){if(!Mw(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function hm(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 Ow(r,e){_t(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function As(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Cs(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function xT(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var vT=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ET(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function ch(r){if(typeof r=="string")r=ET(r);else if(Mw(r))r=lh(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function Lw(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function Rw(r,e){if(r.length!==e.length)return!1;let t=0;for(let s=0;s<r.length;s++)t|=r[s]^e[s];return t===0}var dm=(r,e)=>{function t(s,...n){if(_t(s),!vT)throw new Error("Non little-endian hardware is not yet supported");if(r.nonceLength!==void 0){let u=n[0];if(!u)throw new Error("nonce / iv required");r.varSizeNonce?_t(u):_t(u,r.nonceLength)}let o=r.tagLength;o&&n[1]!==void 0&&_t(n[1]);let i=e(s,...n),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");_t(h)}},c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,_t(u),a(i.encrypt.length,h),i.encrypt(u,h)},decrypt(u,h){if(_t(u),o&&u.length<o)throw new Error("invalid ciphertext length: smaller than tagLength="+o);return a(i.decrypt.length,h),i.decrypt(u,h)}}}return Object.assign(t,r),t};function fm(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error("invalid output length, expected "+r+", got: "+e.length);if(t&&!ST(e))throw new Error("invalid output, must be aligned");return e}function Dw(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),o=BigInt(4294967295),i=Number(t>>n&o),a=Number(t&o),c=s?4:0,l=s?0:4;r.setUint32(e+c,i,s),r.setUint32(e+l,a,s)}function Nw(r,e,t){ih(t);let s=new Uint8Array(16),n=xT(s);return Dw(n,0,BigInt(e),t),Dw(n,8,BigInt(r),t),s}function ST(r){return r.byteOffset%4===0}function lh(r){return Uint8Array.from(r)}var Fw=r=>Uint8Array.from(r.split("").map(e=>e.charCodeAt(0))),IT=Fw("expand 16-byte k"),_T=Fw("expand 32-byte k"),AT=As(IT),CT=As(_T);function q(r,e){return r<<e|r>>>32-e}function pm(r){return r.byteOffset%4===0}var uh=64,TT=16,Uw=2**32-1,Bw=new Uint32Array;function PT(r,e,t,s,n,o,i,a){let c=n.length,l=new Uint8Array(uh),u=As(l),h=pm(n)&&pm(o),d=h?As(n):Bw,f=h?As(o):Bw;for(let p=0;p<c;i++){if(r(e,t,s,u,i,a),i>=Uw)throw new Error("arx: counter overflow");let m=Math.min(uh,c-p);if(h&&m===uh){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let y=0,w;y<TT;y++)w=g+y,f[w]=d[w]^u[y];p+=uh;continue}for(let g=0,y;g<m;g++)y=p+g,o[y]=n[y]^l[g];p+=m}}function mm(r,e){let{allowShortKeys:t,extendNonceFn:s,counterLength:n,counterRight:o,rounds:i}=Lw({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return ah(n),ah(i),ih(o),ih(t),(a,c,l,u,h=0)=>{_t(a),_t(c),_t(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),_t(u),ah(h),h<0||h>=Uw)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let f=[],p=a.length,m,g;if(p===32)f.push(m=lh(a)),g=CT;else if(p===16&&t)m=new Uint8Array(32),m.set(a),m.set(a,16),g=AT,f.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);pm(c)||f.push(c=lh(c));let y=As(m);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(g,y,As(c.subarray(0,16)),y),c=c.subarray(16)}let w=16-n;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){let x=new Uint8Array(12);x.set(c,o?0:12-c.length),c=x,f.push(c)}let b=As(c);return PT(r,g,y,b,l,u,h,i),Cs(...f),u}}var gt=(r,e)=>r[e++]&255|(r[e++]&255)<<8,gm=class{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=ch(e),_t(e,32);let t=gt(e,0),s=gt(e,2),n=gt(e,4),o=gt(e,6),i=gt(e,8),a=gt(e,10),c=gt(e,12),l=gt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>10|n<<6)&7939,this.r[3]=(n>>>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]=gt(e,16+2*u)}process(e,t,s=!1){let n=s?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],h=i[4],d=i[5],f=i[6],p=i[7],m=i[8],g=i[9],y=gt(e,t+0),w=gt(e,t+2),b=gt(e,t+4),x=gt(e,t+6),E=gt(e,t+8),P=gt(e,t+10),T=gt(e,t+12),D=gt(e,t+14),v=o[0]+(y&8191),M=o[1]+((y>>>13|w<<3)&8191),F=o[2]+((w>>>10|b<<6)&8191),B=o[3]+((b>>>7|x<<9)&8191),I=o[4]+((x>>>4|E<<12)&8191),S=o[5]+(E>>>1&8191),_=o[6]+((E>>>14|P<<2)&8191),k=o[7]+((P>>>11|T<<5)&8191),O=o[8]+((T>>>8|D<<8)&8191),N=o[9]+(D>>>5|n),C=0,R=C+v*a+M*(5*g)+F*(5*m)+B*(5*p)+I*(5*f);C=R>>>13,R&=8191,R+=S*(5*d)+_*(5*h)+k*(5*u)+O*(5*l)+N*(5*c),C+=R>>>13,R&=8191;let U=C+v*c+M*a+F*(5*g)+B*(5*m)+I*(5*p);C=U>>>13,U&=8191,U+=S*(5*f)+_*(5*d)+k*(5*h)+O*(5*u)+N*(5*l),C+=U>>>13,U&=8191;let z=C+v*l+M*c+F*a+B*(5*g)+I*(5*m);C=z>>>13,z&=8191,z+=S*(5*p)+_*(5*f)+k*(5*d)+O*(5*h)+N*(5*u),C+=z>>>13,z&=8191;let ee=C+v*u+M*l+F*c+B*a+I*(5*g);C=ee>>>13,ee&=8191,ee+=S*(5*m)+_*(5*p)+k*(5*f)+O*(5*d)+N*(5*h),C+=ee>>>13,ee&=8191;let te=C+v*h+M*u+F*l+B*c+I*a;C=te>>>13,te&=8191,te+=S*(5*g)+_*(5*m)+k*(5*p)+O*(5*f)+N*(5*d),C+=te>>>13,te&=8191;let Z=C+v*d+M*h+F*u+B*l+I*c;C=Z>>>13,Z&=8191,Z+=S*a+_*(5*g)+k*(5*m)+O*(5*p)+N*(5*f),C+=Z>>>13,Z&=8191;let se=C+v*f+M*d+F*h+B*u+I*l;C=se>>>13,se&=8191,se+=S*c+_*a+k*(5*g)+O*(5*m)+N*(5*p),C+=se>>>13,se&=8191;let xe=C+v*p+M*f+F*d+B*h+I*u;C=xe>>>13,xe&=8191,xe+=S*l+_*c+k*a+O*(5*g)+N*(5*m),C+=xe>>>13,xe&=8191;let $e=C+v*m+M*p+F*f+B*d+I*h;C=$e>>>13,$e&=8191,$e+=S*u+_*l+k*c+O*a+N*(5*g),C+=$e>>>13,$e&=8191;let oe=C+v*g+M*m+F*p+B*f+I*d;C=oe>>>13,oe&=8191,oe+=S*h+_*u+k*l+O*c+N*a,C+=oe>>>13,oe&=8191,C=(C<<2)+C|0,C=C+R|0,R=C&8191,C=C>>>13,U+=C,o[0]=R,o[1]=U,o[2]=z,o[3]=ee,o[4]=te,o[5]=Z,o[6]=se,o[7]=xe,o[8]=$e,o[9]=oe}finalize(){let{h:e,pad:t}=this,s=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=n,n=e[a]>>>13,e[a]&=8191;e[0]+=n*5,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,s[0]=e[0]+5,n=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+n,n=s[a]>>>13,s[a]&=8191;s[9]-=8192;let o=(n^1)-1;for(let a=0;a<10;a++)s[a]&=o;o=~o;for(let a=0;a<10;a++)e[a]=e[a]&o|s[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;Cs(s)}update(e){hm(this),e=ch(e),_t(e);let{buffer:t,blockLen:s}=this,n=e.length;for(let o=0;o<n;){let i=Math.min(s-this.pos,n-o);if(i===s){for(;s<=n-o;o+=s)this.process(e,o);continue}t.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===s&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Cs(this.h,this.r,this.buffer,this.pad)}digestInto(e){hm(this),Ow(e,this),this.finished=!0;let{buffer:t,h:s}=this,{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)e[o++]=s[i]>>>0,e[o++]=s[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}};function kT(r){let e=(s,n)=>r(n).update(ch(s)).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>r(s),e}var Kw=kT(r=>new gm(r));function qw(r,e,t,s,n,o=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],h=e[1],d=e[2],f=e[3],p=e[4],m=e[5],g=e[6],y=e[7],w=n,b=t[0],x=t[1],E=t[2],P=i,T=a,D=c,v=l,M=u,F=h,B=d,I=f,S=p,_=m,k=g,O=y,N=w,C=b,R=x,U=E;for(let ee=0;ee<o;ee+=2)P=P+M|0,N=q(N^P,16),S=S+N|0,M=q(M^S,12),P=P+M|0,N=q(N^P,8),S=S+N|0,M=q(M^S,7),T=T+F|0,C=q(C^T,16),_=_+C|0,F=q(F^_,12),T=T+F|0,C=q(C^T,8),_=_+C|0,F=q(F^_,7),D=D+B|0,R=q(R^D,16),k=k+R|0,B=q(B^k,12),D=D+B|0,R=q(R^D,8),k=k+R|0,B=q(B^k,7),v=v+I|0,U=q(U^v,16),O=O+U|0,I=q(I^O,12),v=v+I|0,U=q(U^v,8),O=O+U|0,I=q(I^O,7),P=P+F|0,U=q(U^P,16),k=k+U|0,F=q(F^k,12),P=P+F|0,U=q(U^P,8),k=k+U|0,F=q(F^k,7),T=T+B|0,N=q(N^T,16),O=O+N|0,B=q(B^O,12),T=T+B|0,N=q(N^T,8),O=O+N|0,B=q(B^O,7),D=D+I|0,C=q(C^D,16),S=S+C|0,I=q(I^S,12),D=D+I|0,C=q(C^D,8),S=S+C|0,I=q(I^S,7),v=v+M|0,R=q(R^v,16),_=_+R|0,M=q(M^_,12),v=v+M|0,R=q(R^v,8),_=_+R|0,M=q(M^_,7);let z=0;s[z++]=i+P|0,s[z++]=a+T|0,s[z++]=c+D|0,s[z++]=l+v|0,s[z++]=u+M|0,s[z++]=h+F|0,s[z++]=d+B|0,s[z++]=f+I|0,s[z++]=p+S|0,s[z++]=m+_|0,s[z++]=g+k|0,s[z++]=y+O|0,s[z++]=w+N|0,s[z++]=b+C|0,s[z++]=x+R|0,s[z++]=E+U|0}function DT(r,e,t,s){let n=r[0],o=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],h=e[3],d=e[4],f=e[5],p=e[6],m=e[7],g=t[0],y=t[1],w=t[2],b=t[3];for(let E=0;E<20;E+=2)n=n+c|0,g=q(g^n,16),d=d+g|0,c=q(c^d,12),n=n+c|0,g=q(g^n,8),d=d+g|0,c=q(c^d,7),o=o+l|0,y=q(y^o,16),f=f+y|0,l=q(l^f,12),o=o+l|0,y=q(y^o,8),f=f+y|0,l=q(l^f,7),i=i+u|0,w=q(w^i,16),p=p+w|0,u=q(u^p,12),i=i+u|0,w=q(w^i,8),p=p+w|0,u=q(u^p,7),a=a+h|0,b=q(b^a,16),m=m+b|0,h=q(h^m,12),a=a+h|0,b=q(b^a,8),m=m+b|0,h=q(h^m,7),n=n+l|0,b=q(b^n,16),p=p+b|0,l=q(l^p,12),n=n+l|0,b=q(b^n,8),p=p+b|0,l=q(l^p,7),o=o+u|0,g=q(g^o,16),m=m+g|0,u=q(u^m,12),o=o+u|0,g=q(g^o,8),m=m+g|0,u=q(u^m,7),i=i+h|0,y=q(y^i,16),d=d+y|0,h=q(h^d,12),i=i+h|0,y=q(y^i,8),d=d+y|0,h=q(h^d,7),a=a+c|0,w=q(w^a,16),f=f+w|0,c=q(c^f,12),a=a+c|0,w=q(w^a,8),f=f+w|0,c=q(c^f,7);let x=0;s[x++]=n,s[x++]=o,s[x++]=i,s[x++]=a,s[x++]=g,s[x++]=y,s[x++]=w,s[x++]=b}var MT=mm(qw,{counterRight:!1,counterLength:4,allowShortKeys:!1}),OT=mm(qw,{counterRight:!1,counterLength:8,extendNonceFn:DT,allowShortKeys:!1});var LT=new Uint8Array(16),Hw=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(LT.subarray(t))},RT=new Uint8Array(32);function zw(r,e,t,s,n){let o=r(e,t,RT),i=Kw.create(o);n&&Hw(i,n),Hw(i,s);let a=Nw(s.length,n?n.length:0,!0);i.update(a);let c=i.digest();return Cs(o,a),c}var $w=r=>(e,t,s)=>({encrypt(o,i){let a=o.length;i=fm(a+16,i,!1),i.set(o);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=zw(r,e,t,c,s);return i.set(l,a),Cs(l),i},decrypt(o,i){i=fm(o.length-16,i,!1);let a=o.subarray(0,-16),c=o.subarray(-16),l=zw(r,e,t,a,s);if(!Rw(c,l))throw new Error("invalid tag");return i.set(o.subarray(0,-16)),r(e,t,i,i,1),Cs(l),i}}),ym=dm({blockSize:64,nonceLength:12,tagLength:16},$w(MT)),vte=dm({blockSize:64,nonceLength:24,tagLength:16},$w(OT));var Ts=we(re("node:crypto"),1),po=Ts&&typeof Ts=="object"&&"webcrypto"in Ts?Ts.webcrypto:Ts&&typeof Ts=="object"&&"randomBytes"in Ts?Ts:void 0;function go(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function mo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function At(r,...e){if(!go(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function kc(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");mo(r.outputLen),mo(r.blockLen)}function Ri(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 Vw(r,e){At(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Lr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function hh(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Rr(r,e){return r<<32-e|r>>>e}var Ww=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",NT=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function yo(r){if(At(r),Ww)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=NT[r[t]];return e}var Ps={_0:48,_9:57,A:65,F:70,a:97,f:102};function Gw(r){if(r>=Ps._0&&r<=Ps._9)return r-Ps._0;if(r>=Ps.A&&r<=Ps.F)return r-(Ps.A-10);if(r>=Ps.a&&r<=Ps.f)return r-(Ps.a-10)}function dh(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ww)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 s=new Uint8Array(t);for(let n=0,o=0;n<t;n++,o+=2){let i=Gw(r.charCodeAt(o)),a=Gw(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)}s[n]=i*16+a}return s}function bm(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function sn(r){return typeof r=="string"&&(r=bm(r)),At(r),r}function Ni(...r){let e=0;for(let s=0;s<r.length;s++){let n=r[s];At(n),e+=n.length}let t=new Uint8Array(e);for(let s=0,n=0;s<r.length;s++){let o=r[s];t.set(o,n),n+=o.length}return t}var Li=class{};function wm(r){let e=s=>r().update(sn(s)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Dc(r=32){if(po&&typeof po.getRandomValues=="function")return po.getRandomValues(new Uint8Array(r));if(po&&typeof po.randomBytes=="function")return Uint8Array.from(po.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function BT(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),o=BigInt(4294967295),i=Number(t>>n&o),a=Number(t&o),c=s?4:0,l=s?0:4;r.setUint32(e+c,i,s),r.setUint32(e+l,a,s)}function jw(r,e,t){return r&e^~r&t}function Yw(r,e,t){return r&e^r&t^e&t}var Mc=class extends Li{constructor(e,t,s,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=hh(this.buffer)}update(e){Ri(this),e=sn(e),At(e);let{view:t,buffer:s,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(n-this.pos,o-i);if(a===n){let c=hh(e);for(;n<=o-i;i+=n)this.process(c,i);continue}s.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ri(this),Vw(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,Lr(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(s,0),i=0);for(let h=i;h<n;h++)t[h]=0;BT(s,n-8,BigInt(this.length*8),o),this.process(s,0);let a=hh(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should 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 h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:s,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%t&&e.buffer.set(s),e}clone(){return this._cloneInto()}},ks=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var yt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var fh=BigInt(4294967295),Xw=BigInt(32);function FT(r,e=!1){return e?{h:Number(r&fh),l:Number(r>>Xw&fh)}:{h:Number(r>>Xw&fh)|0,l:Number(r&fh)|0}}function Zw(r,e=!1){let t=r.length,s=new Uint32Array(t),n=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=FT(r[o],e);[s[o],n[o]]=[i,a]}return[s,n]}var xm=(r,e,t)=>r>>>t,vm=(r,e,t)=>r<<32-t|e>>>t,bo=(r,e,t)=>r>>>t|e<<32-t,wo=(r,e,t)=>r<<32-t|e>>>t,Oc=(r,e,t)=>r<<64-t|e>>>t-32,Lc=(r,e,t)=>r>>>t-32|e<<64-t;function ss(r,e,t,s){let n=(e>>>0)+(s>>>0);return{h:r+t+(n/2**32|0)|0,l:n|0}}var Qw=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Jw=(r,e,t,s)=>e+t+s+(r/2**32|0)|0,ex=(r,e,t,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0),tx=(r,e,t,s,n)=>e+t+s+n+(r/2**32|0)|0,rx=(r,e,t,s,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0),sx=(r,e,t,s,n,o)=>e+t+s+n+o+(r/2**32|0)|0;var KT=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]),nn=new Uint32Array(64),ph=class extends Mc{constructor(e=32){super(64,e,8,!1),this.A=ks[0]|0,this.B=ks[1]|0,this.C=ks[2]|0,this.D=ks[3]|0,this.E=ks[4]|0,this.F=ks[5]|0,this.G=ks[6]|0,this.H=ks[7]|0}get(){let{A:e,B:t,C:s,D:n,E:o,F:i,G:a,H:c}=this;return[e,t,s,n,o,i,a,c]}set(e,t,s,n,o,i,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)nn[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let d=nn[h-15],f=nn[h-2],p=Rr(d,7)^Rr(d,18)^d>>>3,m=Rr(f,17)^Rr(f,19)^f>>>10;nn[h]=m+nn[h-7]+p+nn[h-16]|0}let{A:s,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let d=Rr(a,6)^Rr(a,11)^Rr(a,25),f=u+d+jw(a,c,l)+KT[h]+nn[h]|0,m=(Rr(s,2)^Rr(s,13)^Rr(s,22))+Yw(s,n,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=n,n=s,s=f+m|0}s=s+this.A|0,n=n+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(s,n,o,i,a,c,l,u)}roundClean(){Lr(nn)}destroy(){this.set(0,0,0,0,0,0,0,0),Lr(this.buffer)}};var nx=Zw(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),HT=nx[0],zT=nx[1],on=new Uint32Array(80),an=new Uint32Array(80),Em=class extends Mc{constructor(e=64){super(128,e,16,!1),this.Ah=yt[0]|0,this.Al=yt[1]|0,this.Bh=yt[2]|0,this.Bl=yt[3]|0,this.Ch=yt[4]|0,this.Cl=yt[5]|0,this.Dh=yt[6]|0,this.Dl=yt[7]|0,this.Eh=yt[8]|0,this.El=yt[9]|0,this.Fh=yt[10]|0,this.Fl=yt[11]|0,this.Gh=yt[12]|0,this.Gl=yt[13]|0,this.Hh=yt[14]|0,this.Hl=yt[15]|0}get(){let{Ah:e,Al:t,Bh:s,Bl:n,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:d,Gh:f,Gl:p,Hh:m,Hl:g}=this;return[e,t,s,n,o,i,a,c,l,u,h,d,f,p,m,g]}set(e,t,s,n,o,i,a,c,l,u,h,d,f,p,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=s|0,this.Bl=n|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let b=0;b<16;b++,t+=4)on[b]=e.getUint32(t),an[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=on[b-15]|0,E=an[b-15]|0,P=bo(x,E,1)^bo(x,E,8)^xm(x,E,7),T=wo(x,E,1)^wo(x,E,8)^vm(x,E,7),D=on[b-2]|0,v=an[b-2]|0,M=bo(D,v,19)^Oc(D,v,61)^xm(D,v,6),F=wo(D,v,19)^Lc(D,v,61)^vm(D,v,6),B=ex(T,F,an[b-7],an[b-16]),I=tx(B,P,M,on[b-7],on[b-16]);on[b]=I|0,an[b]=B|0}let{Ah:s,Al:n,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:d,Fh:f,Fl:p,Gh:m,Gl:g,Hh:y,Hl:w}=this;for(let b=0;b<80;b++){let x=bo(h,d,14)^bo(h,d,18)^Oc(h,d,41),E=wo(h,d,14)^wo(h,d,18)^Lc(h,d,41),P=h&f^~h&m,T=d&p^~d&g,D=rx(w,E,T,zT[b],an[b]),v=sx(D,y,x,P,HT[b],on[b]),M=D|0,F=bo(s,n,28)^Oc(s,n,34)^Oc(s,n,39),B=wo(s,n,28)^Lc(s,n,34)^Lc(s,n,39),I=s&o^s&a^o&a,S=n&i^n&c^i&c;y=m|0,w=g|0,m=f|0,g=p|0,f=h|0,p=d|0,{h,l:d}=ss(l|0,u|0,v|0,M|0),l=a|0,u=c|0,a=o|0,c=i|0,o=s|0,i=n|0;let _=Qw(M,B,S);s=Jw(_,v,F,I),n=_|0}({h:s,l:n}=ss(this.Ah|0,this.Al|0,s|0,n|0)),{h:o,l:i}=ss(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=ss(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ss(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:d}=ss(this.Eh|0,this.El|0,h|0,d|0),{h:f,l:p}=ss(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:g}=ss(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:w}=ss(this.Hh|0,this.Hl|0,y|0,w|0),this.set(s,n,o,i,a,c,l,u,h,d,f,p,m,g,y,w)}roundClean(){Lr(on,an)}destroy(){Lr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var ox=wm(()=>new ph);var ix=wm(()=>new Em);var _m=BigInt(0),Im=BigInt(1);function mh(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Rc(r,e,t=""){let s=go(r),n=r?.length,o=e!==void 0;if(!s||o&&n!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function ax(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?_m:BigInt("0x"+r)}function cx(r){return ax(yo(r))}function Nr(r){return At(r),ax(yo(Uint8Array.from(r).reverse()))}function Am(r,e){return dh(r.toString(16).padStart(e*2,"0"))}function gh(r,e){return Am(r,e).reverse()}function Ct(r,e,t){let s;if(typeof e=="string")try{s=dh(e)}catch(o){throw new Error(r+" must be hex string or Uint8Array, cause: "+o)}else if(go(e))s=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let n=s.length;if(typeof t=="number"&&n!==t)throw new Error(r+" of length "+t+" expected, got "+n);return s}function lx(r,e){if(r.length!==e.length)return!1;let t=0;for(let s=0;s<r.length;s++)t|=r[s]^e[s];return t===0}function Cm(r){return Uint8Array.from(r)}var Sm=r=>typeof r=="bigint"&&_m<=r;function qT(r,e,t){return Sm(r)&&Sm(e)&&Sm(t)&&e<=r&&r<t}function Bi(r,e,t,s){if(!qT(e,t,s))throw new Error("expected valid "+r+": "+t+" <= n < "+s+", got "+e)}function ux(r){let e;for(e=0;r>_m;r>>=Im,e+=1);return e}var Nc=r=>(Im<<BigInt(r))-Im;function xo(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function s(n,o,i){let a=r[n];if(i&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${n}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([n,o])=>s(n,o,!1)),Object.entries(t).forEach(([n,o])=>s(n,o,!0))}var Tm=()=>{throw new Error("not implemented")};function Pm(r){let e=new WeakMap;return(t,...s)=>{let n=e.get(t);if(n!==void 0)return n;let o=r(t,...s);return e.set(t,o),o}}var Nt=BigInt(0),Tt=BigInt(1),vo=BigInt(2),fx=BigInt(3),px=BigInt(4),mx=BigInt(5),$T=BigInt(7),gx=BigInt(8),GT=BigInt(9),yx=BigInt(16);function Me(r,e){let t=r%e;return t>=Nt?t:e+t}function gr(r,e,t){let s=r;for(;e-- >Nt;)s*=s,s%=t;return s}function hx(r,e){if(r===Nt)throw new Error("invert: expected non-zero number");if(e<=Nt)throw new Error("invert: expected positive modulus, got "+e);let t=Me(r,e),s=e,n=Nt,o=Tt,i=Tt,a=Nt;for(;t!==Nt;){let l=s/t,u=s%t,h=n-i*l,d=o-a*l;s=t,t=u,n=i,o=a,i=h,a=d}if(s!==Tt)throw new Error("invert: does not exist");return Me(n,e)}function km(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function bx(r,e){let t=(r.ORDER+Tt)/px,s=r.pow(e,t);return km(r,s,e),s}function VT(r,e){let t=(r.ORDER-mx)/gx,s=r.mul(e,vo),n=r.pow(s,t),o=r.mul(e,n),i=r.mul(r.mul(o,vo),n),a=r.mul(o,r.sub(i,r.ONE));return km(r,a,e),a}function WT(r){let e=Ms(r),t=wx(r),s=t(e,e.neg(e.ONE)),n=t(e,s),o=t(e,e.neg(s)),i=(r+$T)/yx;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,s),h=a.mul(l,n),d=a.mul(l,o),f=a.eql(a.sqr(u),c),p=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(d,h,p);let m=a.eql(a.sqr(u),c),g=a.cmov(l,u,m);return km(a,g,c),g}}function wx(r){if(r<fx)throw new Error("sqrt is not defined for small field");let e=r-Tt,t=0;for(;e%vo===Nt;)e/=vo,t++;let s=vo,n=Ms(r);for(;dx(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return bx;let o=n.pow(s,e),i=(e+Tt)/vo;return function(c,l){if(c.is0(l))return l;if(dx(c,l)!==1)throw new Error("Cannot find square root");let u=t,h=c.mul(c.ONE,o),d=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===u)throw new Error("Cannot find square root");let g=Tt<<BigInt(u-p-1),y=c.pow(h,g);u=p,h=c.sqr(y),d=c.mul(d,h),f=c.mul(f,y)}return f}}function jT(r){return r%px===fx?bx:r%gx===mx?VT:r%yx===GT?WT(r):wx(r)}var Ds=(r,e)=>(Me(r,e)&Tt)===Tt,YT=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xx(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=YT.reduce((s,n)=>(s[n]="function",s),e);return xo(r,t),r}function XT(r,e,t){if(t<Nt)throw new Error("invalid exponent, negatives unsupported");if(t===Nt)return r.ONE;if(t===Tt)return e;let s=r.ONE,n=e;for(;t>Nt;)t&Tt&&(s=r.mul(s,n)),n=r.sqr(n),t>>=Tt;return s}function yh(r,e,t=!1){let s=new Array(e.length).fill(t?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(s[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(s[c]=r.mul(i,s[c]),r.mul(i,a)),o),s}function dx(r,e){let t=(r.ORDER-Tt)/vo,s=r.pow(e,t),n=r.eql(s,r.ONE),o=r.eql(s,r.ZERO),i=r.eql(s,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function vx(r,e){e!==void 0&&mo(e);let t=e!==void 0?e:r.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function Ms(r,e,t=!1,s={}){if(r<=Nt)throw new Error("invalid field: expected ORDER > 0, got "+r);let n,o,i=!1,a;if(typeof e=="object"&&e!=null){if(s.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(n=d.BITS),d.sqrt&&(o=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(n=e),s.sqrt&&(o=s.sqrt);let{nBitLength:c,nByteLength:l}=vx(r,n);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,h=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:l,MASK:Nc(c),ZERO:Nt,ONE:Tt,allowedLengths:a,create:d=>Me(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Nt<=d&&d<r},is0:d=>d===Nt,isValidNot0:d=>!h.is0(d)&&h.isValid(d),isOdd:d=>(d&Tt)===Tt,neg:d=>Me(-d,r),eql:(d,f)=>d===f,sqr:d=>Me(d*d,r),add:(d,f)=>Me(d+f,r),sub:(d,f)=>Me(d-f,r),mul:(d,f)=>Me(d*f,r),pow:(d,f)=>XT(h,d,f),div:(d,f)=>Me(d*hx(f,r),r),sqrN:d=>d*d,addN:(d,f)=>d+f,subN:(d,f)=>d-f,mulN:(d,f)=>d*f,inv:d=>hx(d,r),sqrt:o||(d=>(u||(u=jT(r)),u(h,d))),toBytes:d=>t?gh(d,l):Am(d,l),fromBytes:(d,f=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let m=new Uint8Array(l);m.set(d,t?0:m.length-d.length),d=m}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let p=t?Nr(d):cx(d);if(i&&(p=Me(p,r)),!f&&!h.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>yh(h,d),cmov:(d,f,p)=>p?f:d});return Object.freeze(h)}var bh=BigInt(0),Lm=BigInt(1);function Ex(r,e){let t=e.negate();return r?t:e}function Bc(r,e){let t=yh(r.Fp,e.map(s=>s.Z));return e.map((s,n)=>r.fromAffine(s.toAffine(t[n])))}function Ax(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Dm(r,e){Ax(r,e);let t=Math.ceil(e/r)+1,s=2**(r-1),n=2**r,o=Nc(r),i=BigInt(r);return{windows:t,windowSize:s,mask:o,maxNumber:n,shiftBy:i}}function Sx(r,e,t){let{windowSize:s,mask:n,maxNumber:o,shiftBy:i}=t,a=Number(r&n),c=r>>i;a>s&&(a-=o,c+=Lm);let l=e*s,u=l+Math.abs(a)-1,h=a===0,d=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:d,isNegF:f,offsetF:l}}function ZT(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function QT(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}var Mm=new WeakMap,Cx=new WeakMap;function Om(r){return Cx.get(r)||1}function Ix(r){if(r!==bh)throw new Error("invalid wNAF")}var wh=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,s=this.ZERO){let n=e;for(;t>bh;)t&Lm&&(s=s.add(n)),n=n.double(),t>>=Lm;return s}precomputeWindow(e,t){let{windows:s,windowSize:n}=Dm(t,this.bits),o=[],i=e,a=i;for(let c=0;c<s;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE,i=Dm(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:d,offsetF:f}=Sx(s,a,i);s=c,u?o=o.add(Ex(d,t[f])):n=n.add(Ex(h,t[l]))}return Ix(s),{p:n,f:o}}wNAFUnsafe(e,t,s,n=this.ZERO){let o=Dm(e,this.bits);for(let i=0;i<o.windows&&s!==bh;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Sx(s,i,o);if(s=a,!l){let h=t[c];n=n.add(u?h.negate():h)}}return Ix(s),n}getPrecomputes(e,t,s){let n=Mm.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof s=="function"&&(n=s(n)),Mm.set(t,n))),n}cached(e,t,s){let n=Om(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){let o=Om(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,s),t,n)}createCache(e,t){Ax(t,this.bits),Cx.set(e,t),Mm.delete(e)}hasCache(e){return Om(e)!==1}};function xh(r,e,t,s){ZT(t,r),QT(s,e);let n=t.length,o=s.length;if(n!==o)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=ux(BigInt(n)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Nc(c),u=new Array(Number(l)+1).fill(i),h=Math.floor((e.BITS-1)/c)*c,d=i;for(let f=h;f>=0;f-=c){u.fill(i);for(let m=0;m<o;m++){let g=s[m],y=Number(g>>BigInt(f)&l);u[y]=u[y].add(t[m])}let p=i;for(let m=u.length-1,g=i;m>0;m--)g=g.add(u[m]),p=p.add(g);if(d=d.add(p),f!==0)for(let m=0;m<c;m++)d=d.double()}return d}function _x(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return xx(e),e}else return Ms(r,{isLE:t})}function Tx(r,e,t={},s){if(s===void 0&&(s=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>bh))throw new Error(`CURVE.${c} must be positive bigint`)}let n=_x(e.p,t.Fp,s),o=_x(e.n,t.Fn,s),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!n.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:n,Fn:o}}var cn=BigInt(0),ht=BigInt(1),Rm=BigInt(2),JT=BigInt(8);function eP(r,e,t,s){let n=r.sqr(t),o=r.sqr(s),i=r.add(r.mul(e.a,n),o),a=r.add(r.ONE,r.mul(e.d,r.mul(n,o)));return r.eql(i,a)}function tP(r,e={}){let t=Tx("edwards",r,e,e.FpFnLE),{Fp:s,Fn:n}=t,o=t.CURVE,{h:i}=o;xo(e,{},{uvRatio:"function"});let a=Rm<<BigInt(n.BYTES*8)-ht,c=g=>s.create(g),l=e.uvRatio||((g,y)=>{try{return{isValid:!0,value:s.sqrt(s.div(g,y))}}catch{return{isValid:!1,value:cn}}});if(!eP(s,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(g,y,w=!1){let b=w?ht:cn;return Bi("coordinate "+g,y,b,a),y}function h(g){if(!(g instanceof p))throw new Error("ExtendedPoint expected")}let d=Pm((g,y)=>{let{X:w,Y:b,Z:x}=g,E=g.is0();y==null&&(y=E?JT:s.inv(x));let P=c(w*y),T=c(b*y),D=s.mul(x,y);if(E)return{x:cn,y:ht};if(D!==ht)throw new Error("invZ was invalid");return{x:P,y:T}}),f=Pm(g=>{let{a:y,d:w}=o;if(g.is0())throw new Error("bad point: ZERO");let{X:b,Y:x,Z:E,T:P}=g,T=c(b*b),D=c(x*x),v=c(E*E),M=c(v*v),F=c(T*y),B=c(v*c(F+D)),I=c(M+c(w*c(T*D)));if(B!==I)throw new Error("bad point: equation left != right (1)");let S=c(b*x),_=c(E*P);if(S!==_)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,w,b,x){this.X=u("x",y),this.Y=u("y",w),this.Z=u("z",b,!0),this.T=u("t",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:w,y:b}=y||{};return u("x",w),u("y",b),new p(w,b,ht,c(w*b))}static fromBytes(y,w=!1){let b=s.BYTES,{a:x,d:E}=o;y=Cm(Rc(y,b,"point")),mh(w,"zip215");let P=Cm(y),T=y[b-1];P[b-1]=T&-129;let D=Nr(P),v=w?a:s.ORDER;Bi("point.y",D,cn,v);let M=c(D*D),F=c(M-ht),B=c(E*M-x),{isValid:I,value:S}=l(F,B);if(!I)throw new Error("bad point: invalid y coordinate");let _=(S&ht)===ht,k=(T&128)!==0;if(!w&&S===cn&&k)throw new Error("bad point: x=0 and x_0=1");return k!==_&&(S=c(-S)),p.fromAffine({x:S,y:D})}static fromHex(y,w=!1){return p.fromBytes(Ct("point",y),w)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,w=!0){return m.createCache(this,y),w||this.multiply(Rm),this}assertValidity(){f(this)}equals(y){h(y);let{X:w,Y:b,Z:x}=this,{X:E,Y:P,Z:T}=y,D=c(w*T),v=c(E*x),M=c(b*T),F=c(P*x);return D===v&&M===F}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=o,{X:w,Y:b,Z:x}=this,E=c(w*w),P=c(b*b),T=c(Rm*c(x*x)),D=c(y*E),v=w+b,M=c(c(v*v)-E-P),F=D+P,B=F-T,I=D-P,S=c(M*B),_=c(F*I),k=c(M*I),O=c(B*F);return new p(S,_,O,k)}add(y){h(y);let{a:w,d:b}=o,{X:x,Y:E,Z:P,T}=this,{X:D,Y:v,Z:M,T:F}=y,B=c(x*D),I=c(E*v),S=c(T*b*F),_=c(P*M),k=c((x+E)*(D+v)-B-I),O=_-S,N=_+S,C=c(I-w*B),R=c(k*O),U=c(N*C),z=c(k*C),ee=c(O*N);return new p(R,U,ee,z)}subtract(y){return this.add(y.negate())}multiply(y){if(!n.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:w,f:b}=m.cached(this,y,x=>Bc(p,x));return Bc(p,[w,b])[0]}multiplyUnsafe(y,w=p.ZERO){if(!n.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===cn?p.ZERO:this.is0()||y===ht?this:m.unsafe(this,y,b=>Bc(p,b),w)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,o.n).is0()}toAffine(y){return d(this,y)}clearCofactor(){return i===ht?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:w}=this.toAffine(),b=s.toBytes(w);return b[b.length-1]|=y&ht?128:0,b}toHex(){return yo(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(y){return Bc(p,y)}static msm(y,w){return xh(p,n,y,w)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}p.BASE=new p(o.Gx,o.Gy,ht,c(o.Gx*o.Gy)),p.ZERO=new p(cn,ht,ht,cn),p.Fp=s,p.Fn=n;let m=new wh(p,n.BITS);return p.BASE.precompute(8),p}var vh=class{constructor(e){this.ep=e}static fromBytes(e){Tm()}static fromHex(e){Tm()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return yo(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function rP(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');xo(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:s}=t,{BASE:n,Fp:o,Fn:i}=r,a=t.randomBytes||Dc,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,M,F)=>{if(mh(F,"phflag"),M.length||F)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(Nr(v))}function h(v){let M=b.secretKey;v=Ct("private key",v,M);let F=Ct("hashed private key",e(v),2*M),B=c(F.slice(0,M)),I=F.slice(M,2*M),S=u(B);return{head:B,prefix:I,scalar:S}}function d(v){let{head:M,prefix:F,scalar:B}=h(v),I=n.multiply(B),S=I.toBytes();return{head:M,prefix:F,scalar:B,point:I,pointBytes:S}}function f(v){return d(v).pointBytes}function p(v=Uint8Array.of(),...M){let F=Ni(...M);return u(e(l(F,Ct("context",v),!!s)))}function m(v,M,F={}){v=Ct("message",v),s&&(v=s(v));let{prefix:B,scalar:I,pointBytes:S}=d(M),_=p(F.context,B,v),k=n.multiply(_).toBytes(),O=p(F.context,k,S,v),N=i.create(_+O*I);if(!i.isValid(N))throw new Error("sign failed: invalid s");let C=Ni(k,i.toBytes(N));return Rc(C,b.signature,"result")}let g={zip215:!0};function y(v,M,F,B=g){let{context:I,zip215:S}=B,_=b.signature;v=Ct("signature",v,_),M=Ct("message",M),F=Ct("publicKey",F,b.publicKey),S!==void 0&&mh(S,"zip215"),s&&(M=s(M));let k=_/2,O=v.subarray(0,k),N=Nr(v.subarray(k,_)),C,R,U;try{C=r.fromBytes(F,S),R=r.fromBytes(O,S),U=n.multiplyUnsafe(N)}catch{return!1}if(!S&&C.isSmallOrder())return!1;let z=p(I,R.toBytes(),C.toBytes(),M);return R.add(C.multiplyUnsafe(z)).subtract(U).clearCofactor().is0()}let w=o.BYTES,b={secretKey:w,publicKey:w,signature:2*w,seed:w};function x(v=a(b.seed)){return Rc(v,b.seed,"seed")}function E(v){let M=D.randomSecretKey(v);return{secretKey:M,publicKey:f(M)}}function P(v){return go(v)&&v.length===i.BYTES}function T(v,M){try{return!!r.fromBytes(v,M)}catch{return!1}}let D={getExtendedPublicKey:d,randomSecretKey:x,isValidSecretKey:P,isValidPublicKey:T,toMontgomery(v){let{y:M}=r.fromBytes(v),F=b.publicKey,B=F===32;if(!B&&F!==57)throw new Error("only defined for 25519 and 448");let I=B?o.div(ht+M,ht-M):o.div(M-ht,M+ht);return o.toBytes(I)},toMontgomerySecret(v){let M=b.secretKey;Rc(v,M);let F=e(v.subarray(0,M));return c(F).subarray(0,M)},randomPrivateKey:x,precompute(v=8,M=r.BASE){return M.precompute(v,!1)}};return Object.freeze({keygen:E,getPublicKey:f,sign:m,verify:y,utils:D,Point:r,lengths:b})}function sP(r){let e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,s=Ms(e.n,r.nBitLength,!0),n={Fp:t,Fn:s,uvRatio:r.uvRatio},o={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:n,hash:r.hash,eddsaOpts:o}}function nP(r,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:r,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function Px(r){let{CURVE:e,curveOpts:t,hash:s,eddsaOpts:n}=sP(r),o=tP(e,t),i=rP(o,s,n);return nP(r,i)}var Fc=BigInt(0),Fi=BigInt(1),Eh=BigInt(2);function oP(r){return xo(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function kx(r){let e=oP(r),{P:t,type:s,adjustScalarBytes:n,powPminus2:o,randomBytes:i}=e,a=s==="x25519";if(!a&&s!=="x448")throw new Error("invalid type");let c=i||Dc,l=a?255:448,u=a?32:56,h=BigInt(a?9:5),d=BigInt(a?121665:39081),f=a?Eh**BigInt(254):Eh**BigInt(447),p=a?BigInt(8)*Eh**BigInt(251)-Fi:BigInt(4)*Eh**BigInt(445)-Fi,m=f+p+Fi,g=I=>Me(I,t),y=w(h);function w(I){return gh(g(I),u)}function b(I){let S=Ct("u coordinate",I,u);return a&&(S[31]&=127),g(Nr(S))}function x(I){return Nr(n(Ct("scalar",I,u)))}function E(I,S){let _=D(b(S),x(I));if(_===Fc)throw new Error("invalid private or public key received");return w(_)}function P(I){return E(I,y)}function T(I,S,_){let k=g(I*(S-_));return S=g(S-k),_=g(_+k),{x_2:S,x_3:_}}function D(I,S){Bi("u",I,Fc,t),Bi("scalar",S,f,m);let _=S,k=I,O=Fi,N=Fc,C=I,R=Fi,U=Fc;for(let ee=BigInt(l-1);ee>=Fc;ee--){let te=_>>ee&Fi;U^=te,{x_2:O,x_3:C}=T(U,O,C),{x_2:N,x_3:R}=T(U,N,R),U=te;let Z=O+N,se=g(Z*Z),xe=O-N,$e=g(xe*xe),oe=se-$e,rt=C+R,To=C-R,ea=g(To*Z),ta=g(rt*xe),pg=ea+ta,mg=ea-ta;C=g(pg*pg),R=g(k*g(mg*mg)),O=g(se*$e),N=g(oe*(se+g(d*oe)))}({x_2:O,x_3:C}=T(U,O,C)),{x_2:N,x_3:R}=T(U,N,R);let z=o(N);return g(O*z)}let v={secretKey:u,publicKey:u,seed:u},M=(I=c(u))=>(At(I,v.seed),I);function F(I){let S=M(I);return{secretKey:S,publicKey:P(S)}}return{keygen:F,getSharedSecret:(I,S)=>E(I,S),getPublicKey:I=>P(I),scalarMult:E,scalarMultBase:P,utils:{randomSecretKey:M,randomPrivateKey:M},GuBytes:y.slice(),lengths:v}}var iP=BigInt(0),Ls=BigInt(1),Dx=BigInt(2),aP=BigInt(3),cP=BigInt(5),lP=BigInt(8),Ui=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Uc={p:Ui,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:lP,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Lx(r){let e=BigInt(10),t=BigInt(20),s=BigInt(40),n=BigInt(80),o=Ui,a=r*r%o*r%o,c=gr(a,Dx,o)*a%o,l=gr(c,Ls,o)*r%o,u=gr(l,cP,o)*l%o,h=gr(u,e,o)*u%o,d=gr(h,t,o)*h%o,f=gr(d,s,o)*d%o,p=gr(f,n,o)*f%o,m=gr(p,n,o)*f%o,g=gr(m,e,o)*u%o;return{pow_p_5_8:gr(g,Dx,o)*r%o,b2:a}}function Rx(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Nm=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Um(r,e){let t=Ui,s=Me(e*e*e,t),n=Me(s*s*e,t),o=Lx(r*n).pow_p_5_8,i=Me(r*s*o,t),a=Me(e*i*i,t),c=i,l=Me(i*Nm,t),u=a===r,h=a===Me(-r,t),d=a===Me(-r*Nm,t);return u&&(i=c),(h||d)&&(i=l),Ds(i,t)&&(i=Me(-i,t)),{isValid:u||h,value:i}}var Os=Ms(Uc.p,{isLE:!0}),uP=Ms(Uc.n,{isLE:!0}),hP={...Uc,Fp:Os,hash:ix,adjustScalarBytes:Rx,uvRatio:Um},Eo=Px(hP);var Kc=(()=>{let r=Os.ORDER;return kx({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:s}=Lx(e);return Me(gr(t,aP,r)*s,r)},adjustScalarBytes:Rx})})();var Bm=Nm,dP=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),fP=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),pP=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),mP=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Mx=r=>Um(Ls,r),gP=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Fm=r=>Eo.Point.Fp.create(Nr(r)&gP);function Ox(r){let{d:e}=Uc,t=Ui,s=y=>Os.create(y),n=s(Bm*r*r),o=s((n+Ls)*pP),i=BigInt(-1),a=s((i-e*n)*s(n+e)),{isValid:c,value:l}=Um(o,a),u=s(l*r);Ds(u,t)||(u=s(-u)),c||(l=u),c||(i=n);let h=s(i*(n-Ls)*mP-a),d=l*l,f=s((l+l)*a),p=s(h*dP),m=s(Ls-d),g=s(Ls+d);return new Eo.Point(s(f*g),s(m*p),s(p*g),s(f*m))}function yP(r){At(r,64);let e=Fm(r.subarray(0,32)),t=Ox(e),s=Fm(r.subarray(32,64)),n=Ox(s);return new Rs(t.add(n))}var Rs=class r extends vh{constructor(e){super(e)}static fromAffine(e){return new r(Eo.Point.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static hashToCurve(e){return yP(Ct("ristrettoHash",e,64))}static fromBytes(e){At(e,32);let{a:t,d:s}=Uc,n=Ui,o=x=>Os.create(x),i=Fm(e);if(!lx(Os.toBytes(i),e)||Ds(i,n))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o(Ls+t*a),l=o(Ls-t*a),u=o(c*c),h=o(l*l),d=o(t*s*u-h),{isValid:f,value:p}=Mx(o(d*h)),m=o(p*l),g=o(p*m*d),y=o((i+i)*m);Ds(y,n)&&(y=o(-y));let w=o(c*g),b=o(y*w);if(!f||Ds(b,n)||w===iP)throw new Error("invalid ristretto255 encoding 2");return new r(new Eo.Point(y,w,Ls,b))}static fromHex(e){return r.fromBytes(Ct("ristrettoHex",e,32))}static msm(e,t){return xh(r,Eo.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:s,T:n}=this.ep,o=Ui,i=g=>Os.create(g),a=i(i(s+t)*i(s-t)),c=i(e*t),l=i(c*c),{value:u}=Mx(i(a*l)),h=i(u*a),d=i(u*c),f=i(h*d*n),p;if(Ds(n*f,o)){let g=i(t*Bm),y=i(e*Bm);e=g,t=y,p=i(h*fP)}else p=d;Ds(e*f,o)&&(t=i(-t));let m=i((s-t)*p);return Ds(m,o)&&(m=i(-m)),Os.toBytes(m)}equals(e){this.assertSame(e);let{X:t,Y:s}=this.ep,{X:n,Y:o}=e.ep,i=l=>Os.create(l),a=i(t*o)===i(s*n),c=i(s*o)===i(t*n);return a||c}is0(){return this.equals(r.ZERO)}};Rs.BASE=new Rs(Eo.Point.BASE);Rs.ZERO=new Rs(Eo.Point.ZERO);Rs.Fp=Os;Rs.Fn=uP;var Sh=class extends Li{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,kc(e);let s=sn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(s.length>n?e.create().update(s).digest():s);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Lr(o)}update(e){return Ri(this),this.iHash.update(e),this}digestInto(e){Ri(this),At(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:s,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ih=(r,e,t)=>new Sh(r,e).update(t).digest();Ih.create=(r,e)=>new Sh(r,e);function Bx(r,e,t){return kc(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Ih(r,sn(t),sn(e))}var Km=Uint8Array.from([0]),Nx=Uint8Array.of();function Fx(r,e,t,s=32){kc(r),mo(s);let n=r.outputLen;if(s>255*n)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(s/n);t===void 0&&(t=Nx);let i=new Uint8Array(o*n),a=Ih.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)Km[0]=u+1,c.update(u===0?Nx:l).update(t).update(Km).digestInto(l),i.set(l,n*u),a._cloneInto(c);return a.destroy(),c.destroy(),Lr(l,Km),i.slice(0,s)}var _h=ox;var Hm={hashSHA256(r){return _h(r.subarray())},getHKDF(r,e){let t=Bx(_h,e,r),n=Fx(_h,t,void 0,96),o=n.subarray(0,32),i=n.subarray(32,64),a=n.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){let r=Kc.utils.randomPrivateKey();return{publicKey:Kc.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Kc.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return Kc.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,s){return ym(s,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,s,n){return ym(s,e,t).decrypt(r.subarray(),n)}};var bP=(0,Th.newInstance)(),Ux=new Th.ChaCha20Poly1305(bP),Kx="chacha20-poly1305",Ki=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Hc=Buffer.from([48,42,48,5,6,3,43,101,110,3,33,0]);var zm={hashSHA256(r){let e=ns.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,s){let n=ns.default.createCipheriv(Kx,s,e,{authTagLength:16});if(n.setAAD(t,{plaintextLength:r.byteLength}),r instanceof Uint8Array){let a=n.update(r),c=n.final(),l=n.getAuthTag();return Buffer.concat([a,c,l],a.byteLength+c.byteLength+l.byteLength)}let o=new W;for(let a of r)o.append(n.update(a));let i=n.final();return i.byteLength>0&&o.append(i),o.append(n.getAuthTag()),o},chaCha20Poly1305Decrypt(r,e,t,s,n){let o=r.subarray(r.length-16),i=ns.default.createDecipheriv(Kx,s,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),h=i.final();return h.byteLength>0?Buffer.concat([u,h],u.byteLength+h.byteLength):u}let c=new W;for(let u of a)c.append(i.update(u));let l=i.final();return l.byteLength>0&&c.append(l),c}},Ah={hashSHA256(r){return _w(r.subarray())},chaCha20Poly1305Encrypt(r,e,t,s){return Ux.seal(s,e,r.subarray(),t)},chaCha20Poly1305Decrypt(r,e,t,s,n){let o=Ux.open(s,e,r.subarray(),t,n);if(!o)throw new Error("Invalid chacha20poly1305 decryption");return o}},Ch={...Hm,hashSHA256(r){return zm.hashSHA256(r)},chaCha20Poly1305Encrypt(r,e,t,s){return r.byteLength<1200?Ah.chaCha20Poly1305Encrypt(r,e,t,s):zm.chaCha20Poly1305Encrypt(r,e,t,s)},chaCha20Poly1305Decrypt(r,e,t,s,n){return r.byteLength<1200?Ah.chaCha20Poly1305Decrypt(r,e,t,s,n):zm.chaCha20Poly1305Decrypt(r,e,t,s,n)},generateX25519KeyPair(){let{publicKey:r,privateKey:e}=ns.default.generateKeyPairSync("x25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return{publicKey:r.subarray(Hc.length),privateKey:e.subarray(Ki.length)}},generateX25519KeyPairFromSeed(r){let e=ns.default.createPrivateKey({key:Buffer.concat([Ki,r],Ki.byteLength+r.byteLength),type:"pkcs8",format:"der"});return{publicKey:ns.default.createPublicKey(e).export({type:"spki",format:"der"}).subarray(Hc.length),privateKey:r}},generateX25519SharedKey(r,e){return e instanceof Uint8Array?e=Buffer.concat([Hc,e],Hc.byteLength+e.byteLength):e=new W(Hc,e).subarray(),r instanceof Uint8Array?r=Buffer.concat([Ki,r],Ki.byteLength+r.byteLength):r=new W(Ki,r).subarray(),ns.default.diffieHellman({publicKey:ns.default.createPublicKey({key:Buffer.from(e.buffer,e.byteOffset,e.byteLength),type:"spki",format:"der"}),privateKey:ns.default.createPrivateKey({key:Buffer.from(r.buffer,r.byteOffset,r.byteLength),type:"pkcs8",format:"der"})})}};kw&&(Ch.chaCha20Poly1305Encrypt=Ah.chaCha20Poly1305Encrypt,Ch.chaCha20Poly1305Decrypt=Ah.chaCha20Poly1305Decrypt);function Hx(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}}nt();var Hi=r=>{let e=je(2);return e[0]=r>>8,e[1]=r,e};Hi.bytes=2;var zc=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)};zc.bytes=2;function zx(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"})}}Se();function qm(r,e){!e.enabled||!Di||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${K(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${K(r.privateKey,"hex")}`)):e("Missing local static keys."))}function $m(r,e){!e.enabled||!Di||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${K(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${K(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function qx(r,e){!e.enabled||!Di||e(r?`REMOTE_STATIC_PUBLIC_KEY ${K(r.subarray(),"hex")}`:"Missing remote static public key.")}function Gm(r,e){!e.enabled||!Di||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${K(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Vm(r,e,t){!t.enabled||!Di||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&K(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&K(e.k,"hex")}`))}ot();Kt();nt();ra();Kr();ge();Se();nt();var zi=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};nt();var wP=0,xP=4294967295,vP="Cipherstate has reached maximum n, a new handshake must be performed",Ph=class{n;bytes;view;constructor(e=wP){this.n=e,this.bytes=ie(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>xP)throw new Error(vP)}};var So=ie(0),qi=class{k;n;crypto;constructor(e,t=void 0,s=0){this.crypto=e,this.k=t,this.n=new Ph(s)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let s=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),s}decryptWithAd(e,t,s){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,s);return this.n.increment(),n}},Wm=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let s=L(t,"utf-8");this.h=EP(e,s),this.ck=this.h,this.cs=new qi(e)}mixKey(e){let[t,s]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new qi(this.crypto,s)}mixHash(e){this.h=this.crypto.hash(new W(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,So);return[new qi(this.crypto,e),new qi(this.crypto,t)]}},jm=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:s,prologue:n,initiator:o,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new Wm(t,s),this.ss.mixHash(n),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 s=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+s)throw new Error("message is not long enough");let n=e.sublist(t,t+s);return this.rs=this.ss.decryptAndHash(n),s}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},qc=class extends jm{writeMessageA(e){return new W(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let s=this.writeS();return this.writeES(),new W(t,s,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new W(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new zi(`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 zi(`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 zi(`handshake stage 2 validation fail: ${t.message}`)}}};function EP(r,e){if(e.length<=32){let t=ie(32);return t.set(e),t}else return r.hash(e)}ft();X();Kr();ge();zs();nt();var kh;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{if(n.lengthDelimited!==!1&&s.fork(),t.webtransportCerthashes!=null)for(let o of t.webtransportCerthashes)s.uint32(10),s.bytes(o);if(t.streamMuxers!=null)for(let o of t.streamMuxers)s.uint32(18),s.string(o);n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={webtransportCerthashes:[],streamMuxers:[]},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(n.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===n.limits.webtransportCerthashes)throw new Ie('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(t.bytes());break}case 2:{if(n.limits?.streamMuxers!=null&&o.streamMuxers.length===n.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=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(kh||(kh={}));var $c;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(s.uint32(10),s.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(s.uint32(18),s.bytes(t.identitySig)),t.extensions!=null&&(s.uint32(34),kh.codec().encode(t.extensions,s)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={identityKey:ie(0),identitySig:ie(0)},i=s==null?t.len:t.pos+s;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=kh.codec().decode(t,t.uint32(),{limits:n.limits?.extensions});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})($c||($c={}));async function Ym(r,e,t){let s=await r.sign($x(e));return $c.encode({identityKey:Ve(r.publicKey),identitySig:s,extensions:t})}async function Xm(r,e,t){try{let s=$c.decode(r),n=Je(s.identityKey);if(t?.equals(n)===!1)throw new Error(`Payload identity key ${n} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let o=$x(e);if(!await n.verify(o,s.identitySig))throw new Error("Invalid payload signature");return s}catch(s){throw new Ll(s.message)}}function $x(r){let e=L("noise-libp2p-static-key:");return r instanceof Uint8Array?Ye([e,r],e.length+r.length):(r.prepend(e),r)}async function Gx(r,e){let{log:t,connection:s,crypto:n,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ym(o,a.publicKey,l),h=new qc({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});qm(h.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await s.write(h.writeMessageA(So),e),t.trace("Stage 0 - Initiator finished sending first message."),$m(h.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=h.readMessageB(await s.read(e));t.trace("Stage 1 - Initiator received the message."),Gm(h.re,t),qx(h.rs,t),t.trace("Initiator going to check remote's signature...");let f=await Xm(d,h.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await s.write(h.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[p,m]=h.ss.split();return Vm(p,m,t),{payload:f,encrypt:g=>p.encryptWithAd(So,g),decrypt:(g,y)=>m.decryptWithAd(So,g,y)}}async function Vx(r,e){let{log:t,connection:s,crypto:n,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ym(o,a.publicKey,l),h=new qc({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});qm(h.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await s.read(e)),t.trace("Stage 0 - Responder received first message."),Gm(h.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await s.write(h.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),$m(h.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let d=h.readMessageC(await s.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let f=await Xm(d,h.rs,c),[p,m]=h.ss.split();return Vm(p,m,t),{payload:f,encrypt:g=>m.encryptWithAd(So,g),decrypt:(g,y)=>p.decryptWithAd(So,g,y)}}ot();var jx=16;function Yx(r,e){return async function*(t){for await(let s of t)for(let n=0;n<s.length;n+=65519){let o=n+65519;o>s.length&&(o=s.length);let i;s instanceof Uint8Array?i=r.encrypt(s.subarray(n,o)):i=r.encrypt(s.sublist(n,o)),e?.encryptedPackets.increment(),yield new W(Hi(i.byteLength),i)}}}function Xx(r,e){return async function*(t){for await(let s of t)for(let n=0;n<s.length;n+=65535){let o=n+65535;if(o>s.length&&(o=s.length),o-jx<n)throw new Error("Invalid chunk");let i=s.sublist(n,o),a=s.subarray(n,o-jx);try{let c=r.decrypt(i,a);e?.decryptedPackets.increment(),yield c}catch(c){throw e?.decryptErrors.increment(),c}}}}var Dh=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){let{staticNoiseKey:s,extensions:n,crypto:o,prologueBytes:i}=t,{metrics:a}=e;this.components=e;let c=o??Ch;this.crypto=Hx(c),this.extensions={webtransportCerthashes:[],...n},this.metrics=a?zx(a):void 0,s?this.staticKey=c.generateX25519KeyPairFromSeed(s):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ie(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[et]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let s=Jr(e,{lengthEncoder:Hi,lengthDecoder:zc,maxDataLength:65535}),n=await this.performHandshakeInitiator(s,this.components.privateKey,t?.remotePeer?.publicKey,t),o=await this.createSecureConnection(s,n);e.source=o.source,e.sink=o.sink;let i=Je(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:gs(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let s of e){let n=t.get(s);if(n!=null)return n}if(e.length)throw new Rl("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let s=Jr(e,{lengthEncoder:Hi,lengthDecoder:zc,maxDataLength:65535}),n=await this.performHandshakeResponder(s,this.components.privateKey,t?.remotePeer?.publicKey,t),o=await this.createSecureConnection(s,n);e.source=o.source,e.sink=o.sink;let i=Je(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:gs(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,s,n){let o,i=n?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{o=await Gx({connection:e,privateKey:t,remoteIdentityKey:s,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){throw this.metrics?.xxHandshakeErrors.increment(),a}return o}async performHandshakeResponder(e,t,s,n){let o,i=n?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{o=await Vx({connection:e,privateKey:t,remoteIdentityKey:s,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){throw this.metrics?.xxHandshakeErrors.increment(),a}return o}async createSecureConnection(e,t){let[s,n]=fw(),o=e.unwrap();return await st(s,Yx(t,this.metrics),o,i=>Gt(i,{lengthDecoder:zc}),Xx(t,this.metrics),s),n}};function Zx(r={}){return e=>new Dh(e,r)}X();function Mh(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}ot();X();var Br=class extends Error{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e),this.name="InvalidFrameError"}},$i=class extends Error{static name="UnrequestedPingError";constructor(e="Unrequested ping error"){super(e),this.name="UnrequestedPingError"}},Gi=class extends Error{static name="NotMatchingPingError";constructor(e="Unrequested ping error"){super(e),this.name="NotMatchingPingError"}},Oh=class extends Error{static name="InvalidStateError";constructor(e="Invalid state"){super(e),this.name="InvalidStateError"}},Lh=class extends Error{static name="StreamAlreadyExistsError";constructor(e="Strean already exists"){super(e),this.name="StreamAlreadyExistsError"}},Rh=class extends Error{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e),this.name="DecodeInvalidVersionError"}},Nh=class extends Error{static name="BothClientsError";constructor(e="Both clients"){super(e),this.name="BothClientsError"}},Vi=class extends Error{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e),this.name="ReceiveWindowExceededError"}};var Qx=new Set([Br.name,$i.name,Gi.name,Lh.name,Rh.name,Nh.name,Vi.name]),Vc=256*1024,Jx=16*1024*1024;var ev={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:Vc,maxStreamWindowSize:Jx,maxMessageSize:64*1024};function tv(r){if(r.keepAliveInterval<=0)throw new V("keep-alive interval must be positive");if(r.maxInboundStreams<0)throw new V("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams<0)throw new V("max outbound streams must be larger or equal 0");if(r.initialStreamWindowSize<Vc)throw new V("InitialStreamWindowSize must be larger or equal 256 kB");if(r.maxStreamWindowSize<r.initialStreamWindowSize)throw new V("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.maxStreamWindowSize>2**32-1)throw new V("MaxStreamWindowSize must be less than equal MAX_UINT32");if(r.maxMessageSize<1024)throw new V("MaxMessageSize must be greater than a kilobyte")}ot();var Ke;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Ke||(Ke={}));var ke;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(ke||(ke={}));var zse=Object.values(ke).filter(r=>typeof r!="string"),rv=0,yr;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(yr||(yr={}));var ln=12;var sv=2**24;function SP(r){if(r[0]!==rv)throw new Br("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*sv+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*sv+(r[9]<<16)+(r[10]<<8)+r[11]}}var Bh=class{source;buffer;frameInProgress;constructor(e){this.source=IP(e),this.buffer=new W,this.frameInProgress=!1}async*emitFrames(){for await(let e of this.source)for(this.buffer.append(e);;){let t=this.readHeader();if(t===void 0)break;let{type:s,length:n}=t;s===Ke.Data?(this.frameInProgress=!0,yield{header:t,readData:this.readBytes.bind(this,n)}):yield{header:t}}}readHeader(){if(this.frameInProgress)throw new Oh("decoding frame already in progress");if(this.buffer.length<ln)return;let e=SP(this.buffer.subarray(0,ln));return this.buffer.consume(ln),e}async readBytes(e){if(this.buffer.length<e){for await(let s of this.source)if(this.buffer.append(s),this.buffer.length>=e)break}let t=this.buffer.sublist(0,e);return this.buffer.consume(e),this.frameInProgress=!1,t}};function IP(r){if(r[Symbol.iterator]!==void 0){let e=r[Symbol.iterator]();return e.return=void 0,{[Symbol.iterator](){return e}}}else if(r[Symbol.asyncIterator]!==void 0){let e=r[Symbol.asyncIterator]();return e.return=void 0,{[Symbol.asyncIterator](){return e}}}else throw new Error("a source must be either an iterable or an async iterable")}function Zm(r){let e=new Uint8Array(ln);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}X();X();ot();function nv(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function ov(r,e){let t=Mh(r).return?.();nv(t)&&t.catch(s=>{e.error("could not cause iterator to return",s)})}var _P=5e3;function Qm(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Fh=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=fe(),this.closed=fe(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??_P,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=dt({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new Fl(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let n=this.sendNewStream(t);Qm(n)&&await n}let s=()=>{ov(e,this.log)};try{this.sinkController.signal.addEventListener("abort",s),this.log.trace("sink reading from source");for await(let n of e){n=n instanceof Uint8Array?new W(n):n;let o=this.sendData(n,t);Qm(o)&&(this.sendingData=fe(),await o,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",s)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await Ce(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await Ce(this.sink([]),e.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Ce(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Ce(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();Qm(t)&&t.catch(s=>{this.log.error("error sending reset message",s)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new Bl("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};function AP(r){return r[Symbol.asyncIterator]!=null}function iv(r){return r?.then!=null}function CP(r,e){let t=0;if(AP(r))return(async function*(){for await(let c of r){let l=e(c,t++);iv(l)&&await l,yield c}})();let s=Zu(r),{value:n,done:o}=s.next();if(o===!0)return(function*(){})();if(typeof e(n,t++)?.then=="function")return(async function*(){yield n;for(let c of s){let l=e(c,t++);iv(l)&&await l,yield c}})();let a=e;return(function*(){yield n;for(let c of s)a(c,t++),yield c})()}var av=CP;var br;(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"})(br||(br={}));var Uh=class extends Fh{name;state;config;_id;sendWindowCapacity;sendWindowCapacityUpdate;recvWindow;recvWindowCapacity;epochStart;getRTT;sendFrame;constructor(e){super({...e,onEnd:t=>{this.state=br.Finished,e.onEnd?.(t)}}),this.config=e.config,this._id=parseInt(e.id,10),this.name=e.name,this.state=e.state,this.sendWindowCapacity=Vc,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame,this.source=av(this.source,()=>{this.sendWindowUpdate()})}async sendNewStream(){}async sendData(e,t={}){for(e=e.sublist();e.byteLength!==0;){if(this.sendWindowCapacity===0&&(this.log?.trace("wait for send window capacity, status %s",this.status),await this.waitForSendWindowCapacity(t),this.status==="closed"||this.status==="aborted"||this.status==="reset")){this.log?.trace("%s while waiting for send window capacity",this.status);return}let s=Math.min(this.sendWindowCapacity,this.config.maxMessageSize-ln,e.length),n=this.getSendFlags();this.sendFrame({type:Ke.Data,flag:n,streamID:this._id,length:s},e.sublist(0,s)),this.sendWindowCapacity-=s,e.consume(s)}}async sendReset(){this.sendFrame({type:Ke.WindowUpdate,flag:ke.RST,streamID:this._id,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|ke.FIN;this.sendFrame({type:Ke.WindowUpdate,flag:e,streamID:this._id,length:0})}async sendCloseRead(){}async waitForSendWindowCapacity(e={}){if(this.sendWindowCapacity>0)return;let t,s,n=()=>{this.status==="open"||this.status==="closing"?s(new Lt("Stream aborted")):t()};e.signal?.addEventListener("abort",n);try{await new Promise((o,i)=>{this.sendWindowCapacityUpdate=()=>{o()},s=i,t=o})}finally{e.signal?.removeEventListener("abort",n)}}handleWindowUpdate(e){this.log?.trace("stream received window update id=%s",this._id),this.processFlags(e.flag);let t=this.sendWindowCapacity;this.sendWindowCapacity+=e.length,t===0&&e.length>0&&this.sendWindowCapacityUpdate?.()}async handleData(e,t){if(this.log?.trace("stream received data id=%s",this._id),this.processFlags(e.flag),this.recvWindowCapacity<e.length)throw new Vi("Receive window exceeded");let s=await t();this.recvWindowCapacity-=e.length,this.sourcePush(s)}processFlags(e){(e&ke.ACK)===ke.ACK&&this.state===br.SYNSent&&(this.state=br.Established),(e&ke.FIN)===ke.FIN&&this.remoteCloseWrite(),(e&ke.RST)===ke.RST&&this.reset()}getSendFlags(){switch(this.state){case br.Init:return this.state=br.SYNSent,ke.SYN;case br.SYNReceived:return this.state=br.Established,ke.ACK;default:return 0}}sendWindowUpdate(){let e=this.getSendFlags(),t=Date.now(),s=this.getRTT();if(e===0&&s>-1&&t-this.epochStart<s*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.config.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let n=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Ke.WindowUpdate,flag:e,streamID:this._id,length:n})}};var cv="/yamux/1.0.0",TP=500,Kh=class{protocol=cv;_components;_init;constructor(e,t={}){this._components=e,this._init=t}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[et]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new Jm(this._components,{...this._init,...e})}},Jm=class{protocol=cv;source;sink;config;log;logger;closeController;nextStreamID;_streams;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;onIncomingStream;onStreamEnd;constructor(e,t){this.client=t.direction==="outbound",this.config={...ev,...t},this.logger=e.logger,this.log=this.logger.forComponent("libp2p:yamux"),tv(this.config),this.closeController=new AbortController,J(1/0,this.closeController.signal),this.onIncomingStream=t.onIncomingStream,this.onStreamEnd=t.onStreamEnd,this._streams=new Map,this.source=dt({onEnd:()=>{this.log?.trace("muxer source ended"),this._streams.forEach(s=>{s.destroy()})}}),this.sink=async s=>{let n=()=>{let a=Mh(s);if(a.return!=null){let c=a.return();PP(c)&&c.catch(l=>{this.log?.("could not cause sink source to return",l)})}},o,i;try{let a=new Bh(s);try{this.closeController.signal.addEventListener("abort",n);for await(let c of a.emitFrames())await this.handleFrame(c.header,c.readData)}finally{this.closeController.signal.removeEventListener("abort",n)}o=yr.NormalTermination}catch(a){Qx.has(a.name)?(this.log?.error("protocol error in sink",a),o=yr.ProtocolError):(this.log?.error("internal error in sink",a),o=yr.InternalError),i=a}this.log?.trace("muxer sink ended"),i!=null?this.abort(i,o):await this.close({reason:o})},this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log?.trace("muxer created"),this.config.enableKeepAlive&&this.keepAliveLoop().catch(s=>this.log?.error("keepalive error: %s",s)),this.ping().catch(s=>this.log?.error("ping error: %s",s))}get streams(){return Array.from(this._streams.values())}newStream(e){if(this.remoteGoAway!==void 0)throw new Ws("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Ws("Muxer closed locally");let t=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new Qo("max outbound streams exceeded");this.log?.trace("new outgoing stream id=%s",t);let s=this._newStream(t,e,br.Init,"outbound");return this._streams.set(t,s),this.numOutboundStreams++,s.sendWindowUpdate(),s}async ping(){if(this.remoteGoAway!==void 0)throw new Ws("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Ws("Muxer closed locally");if(this.activePing===void 0){let e=()=>{};this.activePing={id:this.nextPingID++,promise:new Promise((n,o)=>{let i=()=>{o(new Ws("Muxer closed locally"))};this.closeController.signal.addEventListener("abort",i,{once:!0}),e=()=>{this.closeController.signal.removeEventListener("abort",i),n()}}),resolve:e};let t=Date.now();this.sendPing(this.activePing.id);try{await this.activePing.promise}finally{delete this.activePing}let s=Date.now();this.rtt=s-t}else await this.activePing.promise;return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.closeController.signal.aborted)return;let t=e?.reason??yr.NormalTermination;if(this.log?.trace("muxer close reason=%s",t),e.signal==null){let s=AbortSignal.timeout(TP);J(1/0,s),e={...e,signal:s}}try{await Promise.all([...this._streams.values()].map(async s=>s.close(e))),this.sendGoAway(t),this._closeMuxer()}catch(s){this.abort(s)}}abort(e,t){if(!this.closeController.signal.aborted){t=t??yr.InternalError,this.log?.error("muxer abort reason=%s error=%s",t,e);for(let s of this._streams.values())s.abort(e);this.sendGoAway(t),this._closeMuxer()}}isClosed(){return this.closeController.signal.aborted}_closeMuxer(){this.closeController.abort(),this.source.end()}_newStream(e,t,s,n){if(this._streams.get(e)!=null)throw new V("Stream already exists with that id");let o=new Uh({id:e.toString(),name:t,state:s,direction:n,sendFrame:this.sendFrame.bind(this),onEnd:()=>{this.closeStream(e),this.onStreamEnd?.(o)},log:this.logger.forComponent(`libp2p:yamux:${n}:${e}`),config:this.config,getRTT:this.getRTT.bind(this)});return o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--,this._streams.delete(e)}async keepAliveLoop(){for(this.log?.trace("muxer keepalive enabled interval=%s",this.config.keepAliveInterval);;){let e;try{await Ce(new Promise(t=>{e=setTimeout(t,this.config.keepAliveInterval)}),this.closeController.signal),this.ping().catch(t=>this.log?.error("ping error: %s",t))}catch{clearInterval(e);return}}}async handleFrame(e,t){let{streamID:s,type:n,length:o}=e;if(this.log?.trace("received frame %o",e),s===0)switch(n){case Ke.Ping:{this.handlePing(e);return}case Ke.GoAway:{this.handleGoAway(o);return}default:throw new Br("Invalid frame type")}else switch(e.type){case Ke.Data:case Ke.WindowUpdate:{await this.handleStreamMessage(e,t);return}default:throw new Br("Invalid frame type")}}handlePing(e){if(e.flag===ke.SYN)this.log?.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,ke.ACK);else if(e.flag===ke.ACK)this.log?.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new Br("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new $i("ping not requested");if(this.activePing.id!==e)throw new Gi("ping doesn't match our id");this.activePing.resolve()}handleGoAway(e){this.log?.trace("received GoAway reason=%s",yr[e]??"unknown"),this.remoteGoAway=e;for(let t of this._streams.values())t.reset();this._closeMuxer()}async handleStreamMessage(e,t){let{streamID:s,flag:n,type:o}=e;(n&ke.SYN)===ke.SYN&&this.incomingStream(s);let i=this._streams.get(s);if(i===void 0){if(o===Ke.Data){if(this.log?.("discarding data for stream id=%s",s),t===void 0)throw new Error("unreachable");await t()}else this.log?.trace("frame for missing stream id=%s",s);return}switch(o){case Ke.WindowUpdate:{i.handleWindowUpdate(e);return}case Ke.Data:{if(t===void 0)throw new Error("unreachable");await i.handleData(e,t);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new V("Both endpoints are clients");if(this._streams.has(e))return;if(this.log?.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Ke.WindowUpdate,flag:ke.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.config.maxInboundStreams){this.log?.("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Ke.WindowUpdate,flag:ke.RST,streamID:e,length:0});return}let t=this._newStream(e,void 0,br.SYNReceived,"inbound");this.numInboundStreams++,this._streams.set(e,t),this.onIncomingStream?.(t)}sendFrame(e,t){if(this.log?.trace("sending frame %o",e),e.type===Ke.Data){if(t===void 0)throw new Br("Invalid frame");this.source.push(new W(Zm(e),t))}else this.source.push(Zm(e))}sendPing(e,t=ke.SYN){t===ke.SYN?this.log?.trace("sending ping request pingId=%s",e):this.log?.trace("sending ping response pingId=%s",e),this.sendFrame({type:Ke.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=yr.NormalTermination){this.log?.("sending GoAway reason=%s",yr[e]),this.localGoAway=e,this.sendFrame({type:Ke.GoAway,flag:0,streamID:0,length:e})}};function PP(r){return r!=null&&typeof r.then=="function"}function lv(r={}){return e=>new Kh(e,r)}function eg(r,e){let t=Jr(r,e),s={read:async(n,o)=>{let i=await t.read(o);return n.decode(i)},write:async(n,o,i)=>{await t.write(o.encode(n),i)},writeV:async(n,o,i)=>{await t.writeV(n.map(a=>o.encode(a)),i)},pb:n=>({read:async o=>s.read(n,o),write:async(o,i)=>s.write(o,n,i),writeV:async(o,i)=>s.writeV(o,n,i),unwrap:()=>s}),unwrap:()=>t.unwrap()};return s}var uv="0.1.0";var hv="1.0.0";zs();var Wc;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{if(n.lengthDelimited!==!1&&s.fork(),t.protocolVersion!=null&&(s.uint32(42),s.string(t.protocolVersion)),t.agentVersion!=null&&(s.uint32(50),s.string(t.agentVersion)),t.publicKey!=null&&(s.uint32(10),s.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)s.uint32(18),s.bytes(o);if(t.observedAddr!=null&&(s.uint32(34),s.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)s.uint32(26),s.string(o);t.signedPeerRecord!=null&&(s.uint32(66),s.bytes(t.signedPeerRecord)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={listenAddrs:[],protocols:[]},i=s==null?t.len:t.pos+s;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(n.limits?.listenAddrs!=null&&o.listenAddrs.length===n.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(n.limits?.protocols!=null&&o.protocols.length===n.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=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(Wc||(Wc={}));ft();X();ce();ge();var os={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function dv(r){if(r!=null&&r.length>0)try{return G(r)}catch{}}function MP(r,e){return e??r.userAgent}async function fv(r,e,t,s,n){if(t("received identify from %p",s.remotePeer),n==null)throw new Yt("message was null or undefined");let o={};if(n.listenAddrs.length>0&&(o.addresses=n.listenAddrs.map(c=>({isCertified:!1,multiaddr:G(c)}))),n.protocols.length>0&&(o.protocols=n.protocols),n.publicKey!=null){let c=Je(n.publicKey);if(!gs(c).equals(s.remotePeer))throw new Yt("public key did not match remote PeerId");o.publicKey=c}let i;if(n.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",s.remotePeer);let c=n.signedPeerRecord,l=await Or.openAndCertify(c,Qt.DOMAIN),u=Qt.createFromProtobuf(l.payload),h=Wr(l.publicKey.toCID());if(!u.peerId.equals(h))throw new Yt("signing key does not match PeerId in the PeerRecord");if(!s.remotePeer.equals(u.peerId))throw new Yt("signing key does not match remote PeerId");let d;try{d=await r.get(u.peerId)}catch(f){if(f.name!=="NotFoundError")throw f}if(d!=null&&(o.metadata=d.metadata,d.peerRecordEnvelope!=null)){let f=Or.createFromProtobuf(d.peerRecordEnvelope),p=Qt.createFromProtobuf(f.payload);p.seqNumber>=u.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",p.seqNumber,u.seqNumber),u=p,c=d.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",s.remotePeer);if(t.trace("patching %p with",s.remotePeer,o),await r.patch(s.remotePeer,o),n.agentVersion!=null||n.protocolVersion!=null){let c={};n.agentVersion!=null&&(c.AgentVersion=L(n.agentVersion)),n.protocolVersion!=null&&(c.ProtocolVersion=L(n.protocolVersion)),t.trace("merging %p metadata",s.remotePeer,c),await r.merge(s.remotePeer,{metadata:c})}let a={peerId:s.remotePeer,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(c=>G(c)),observedAddr:n.observedAddr==null?void 0:G(n.observedAddr),protocols:n.protocols,signedPeerRecord:i,connection:s};return e.safeDispatchEvent("peer:identify",{detail:a}),a}var Hh=class{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??os.timeout,this.maxInboundStreams=t.maxInboundStreams??os.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??os.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??os.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??os.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??os.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??os.protocolPrefix}/${uv}`,agentVersion:MP(e.nodeInfo,t.agentVersion)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:L(this.host.agentVersion),ProtocolVersion:L(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,e=>{this.handleProtocol(e).catch(t=>{this.log.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}};ft();X();ce();function pv(r){try{for(let{code:e,value:t}of r.getComponents())if(t!=null&&e===41)return u4("2000::/3",t)}catch{}return!1}Ze();var zh=class extends Hh{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??os.protocolPrefix}/${"id"}/${hv}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??os.runOnConnectionOpen)&&e.events.addEventListener("connection:open",s=>{let n=s.detail;this.identify(n).catch(o=>{o.name!==Cn.name&&this.log.error("error during identify trigged by connection:open",o)})})}[et]=["@libp2p/identify"];async _identify(e,t={}){let s;if(t.signal==null){let n=AbortSignal.timeout(this.timeout);J(1/0,n),t={...t,signal:n}}try{s=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});let o=await eg(s,{maxDataLength:this.maxMessageSize}).pb(Wc).read(t);return await s.close(t),o}catch(n){throw s?.abort(n),n}}async identify(e,t={}){let s=await this._identify(e,t),{publicKey:n,protocols:o,observedAddr:i}=s;if(n==null)throw new Yt("Public key was missing from identify message");let a=Je(n),c=Wr(a.toCID()),l=e.log.newScope("identify");if(!e.remotePeer.equals(c))throw new Yt("Identified peer does not match the expected peer");if(this.peerId.equals(c))throw new Yt("Identified peer is our own peer id?");return this.maybeAddObservedAddress(i,l),l("completed for peer %p and protocols %o",c,o),fv(this.peerStore,this.events,l,e,s)}maybeAddObservedAddress(e,t){let s=dv(e);if(s==null)return;if(t.trace("our observed address was %a",s),Ss(s)){this.log.trace("our observed address was private");return}let n=s.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!pv(s)){t.trace("our observed address was IPv6 but not a global unicast address");return}Es.exactMatch(s)||(t.trace("storing the observed address"),this.addressManager.addObservedAddr(s))}async handleProtocol(e){let{connection:t,stream:s}=e,n=t.log.newScope("identify"),o=AbortSignal.timeout(this.timeout);J(1/0,o);try{let i=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(h=>h.decapsulateCode(yi("p2p").code)),c=i.peerRecordEnvelope;if(a.length>0&&c==null){let h=new Qt({peerId:this.peerId,multiaddrs:a});c=(await Or.seal(h,this.privateKey)).marshal().subarray()}let l=t.remoteAddr.bytes;mb.matches(t.remoteAddr)||(l=void 0),await eg(s).pb(Wc).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Ve(this.privateKey.publicKey),listenAddrs:a.map(h=>h.bytes),signedPeerRecord:c,observedAddr:l,protocols:i.protocols},{signal:o}),await s.close({signal:o})}catch(i){n.error("could not respond to identify request",i),s.abort(i)}}};function mv(r={}){return e=>new zh(e,r)}X();Ze();Kt();var gv="1.0.0",yv="ping",bv="ipfs";var qh=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??bv}/${yv}/${gv}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[et]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{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}handleMessage(e){let t=e.connection.log.newScope("ping");t.trace("ping from %p",e.connection.remotePeer);let{stream:s}=e,n=Date.now(),o=ho(s),i=!1;Promise.resolve().then(async()=>{for(;;){let a=AbortSignal.timeout(this.timeout);J(1/0,a),a.addEventListener("abort",()=>{s?.abort(new Vr("ping timeout"))});let c=await o.read({bytes:32,signal:a});await o.write(c,{signal:a}),i=!0}}).catch(a=>{i&&a.name==="UnexpectedEOFError"&&s.readStatus!=="ready"||(t.error("ping from %p failed with error - %e",e.connection.remotePeer,a),s?.abort(a))}).finally(()=>{let a=Date.now()-n;t("ping from %p complete in %dms",e.connection.remotePeer,a);let c=AbortSignal.timeout(this.timeout);J(1/0,c),s.close({signal:c}).catch(l=>{t.error("error closing ping stream from %p - %e",e.connection.remotePeer,l),s?.abort(l)})})}async ping(e,t={}){let s=Date.now(),n=Gr(32),o=await this.components.connectionManager.openConnection(e,t),i=o.log.newScope("ping"),a;if(t.signal==null){let c=AbortSignal.timeout(this.timeout);t={...t,signal:c}}try{a=await o.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});let c=ho(a),[,l]=await Promise.all([c.write(n,t),c.read({...t,bytes:32})]),u=Date.now()-s;if(!ae(n,l.subarray()))throw new Hl(`Received wrong ping ack after ${u}ms`);return i("ping %p complete in %dms",o.remotePeer,u),u}catch(c){throw i.error("error while pinging %p",o.remotePeer,c),a?.abort(c),c}finally{a!=null&&await a.close(t)}}};function wv(r={}){return e=>new qh(e,r)}X();ce();wr();ot();nt();function $h(r){return r[Symbol.asyncIterator]!=null}var Gh=r=>{let e=Le(r),t=je(e);return rr(r,t),Gh.bytes=e,t};Gh.bytes=0;function Wi(r,e){e=e??{};let t=e.lengthEncoder??Gh;function*s(n){let o=t(n.byteLength);o instanceof Uint8Array?yield o:yield*o,n instanceof Uint8Array?yield n:yield*n}return $h(r)?(async function*(){for await(let n of r)yield*s(n)})():(function*(){for(let n of r)yield*s(n)})()}Wi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Gh;return new W(t(r.byteLength),r)};wr();ot();var Vh=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Wh=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},jh=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},jc=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var BP=8,FP=1024*1024*4,Io;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Io||(Io={}));var rg=r=>{let e=as(r);return rg.bytes=Le(e),e};rg.bytes=0;function Yc(r,e){let t=new W,s=Io.LENGTH,n=-1,o=e?.lengthDecoder??rg,i=e?.maxLengthLength??BP,a=e?.maxDataLength??FP;function*c(){for(;t.byteLength>0;){if(s===Io.LENGTH)try{if(n=o(t),n<0)throw new Vh("Invalid message length");if(n>a)throw new Wh("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(n),s=Io.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new jh("Message length length too long");break}throw l}if(s===Io.DATA){if(t.byteLength<n)break;let l=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(l),yield l,s=Io.LENGTH}}}return $h(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new jc("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new jc("Unexpected end of input")})()}Yc.fromReader=(r,e)=>{let t=1,s=(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 Yc(s,{...e??{},onLength:o=>{t=o}})};ir();var sg="/floodsub/1.0.0",ng="/meshsub/1.0.0",xv="/meshsub/1.1.0",Yh="/meshsub/1.2.0";var vv="ERR_TOPIC_VALIDATOR_REJECT",Ev="ERR_TOPIC_VALIDATOR_IGNORE";var Sv={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};zs();var Ns;(function(r){let e;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.subscribe!=null&&(p.uint32(8),p.bool(f.subscribe)),f.topic!=null&&(p.uint32(18),p.string(f.topic)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{g.subscribe=f.bool();break}case 2:{g.topic=f.string();break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(e=r.SubOpts||(r.SubOpts={}));let t;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.from!=null&&(p.uint32(10),p.bytes(f.from)),f.data!=null&&(p.uint32(18),p.bytes(f.data)),f.seqno!=null&&(p.uint32(26),p.bytes(f.seqno)),f.topic!=null&&f.topic!==""&&(p.uint32(34),p.string(f.topic)),f.signature!=null&&(p.uint32(42),p.bytes(f.signature)),f.key!=null&&(p.uint32(50),p.bytes(f.key)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={topic:""},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>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(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(t=r.Message||(r.Message={}));let s;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.ihave!=null)for(let g of f.ihave)p.uint32(10),r.ControlIHave.codec().encode(g,p);if(f.iwant!=null)for(let g of f.iwant)p.uint32(18),r.ControlIWant.codec().encode(g,p);if(f.graft!=null)for(let g of f.graft)p.uint32(26),r.ControlGraft.codec().encode(g,p);if(f.prune!=null)for(let g of f.prune)p.uint32(34),r.ControlPrune.codec().encode(g,p);if(f.idontwant!=null)for(let g of f.idontwant)p.uint32(42),r.ControlIDontWant.codec().encode(g,p);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>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(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(s=r.ControlMessage||(r.ControlMessage={}));let n;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.topicID!=null&&(p.uint32(10),p.string(f.topicID)),f.messageIDs!=null)for(let g of f.messageIDs)p.uint32(18),p.bytes(g);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={messageIDs:[]},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>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(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(n=r.ControlIHave||(r.ControlIHave={}));let o;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.messageIDs!=null)for(let g of f.messageIDs)p.uint32(10),p.bytes(g);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={messageIDs:[]},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>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(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(o=r.ControlIWant||(r.ControlIWant={}));let i;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.topicID!=null&&(p.uint32(10),p.string(f.topicID)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{g.topicID=f.string();break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(i=r.ControlGraft||(r.ControlGraft={}));let a;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.topicID!=null&&(p.uint32(10),p.string(f.topicID)),f.peers!=null)for(let g of f.peers)p.uint32(18),r.PeerInfo.codec().encode(g,p);f.backoff!=null&&(p.uint32(24),p.uint64Number(f.backoff)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={peers:[]},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>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(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(a=r.ControlPrune||(r.ControlPrune={}));let c;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.peerID!=null&&(p.uint32(10),p.bytes(f.peerID)),f.signedPeerRecord!=null&&(p.uint32(18),p.bytes(f.signedPeerRecord)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{g.peerID=f.bytes();break}case 2:{g.signedPeerRecord=f.bytes();break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(c=r.PeerInfo||(r.PeerInfo={}));let l;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.messageIDs!=null)for(let g of f.messageIDs)p.uint32(10),p.bytes(g);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={messageIDs:[]},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>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(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(l=r.ControlIDontWant||(r.ControlIDontWant={}));let u;r.codec=()=>(u==null&&(u=he((h,d,f={})=>{if(f.lengthDelimited!==!1&&d.fork(),h.subscriptions!=null)for(let p of h.subscriptions)d.uint32(10),r.SubOpts.codec().encode(p,d);if(h.messages!=null)for(let p of h.messages)d.uint32(18),r.Message.codec().encode(p,d);h.control!=null&&(d.uint32(26),r.ControlMessage.codec().encode(h.control,d)),f.lengthDelimited!==!1&&d.ldelim()},(h,d,f={})=>{let p={subscriptions:[],messages:[]},m=d==null?h.len:h.pos+d;for(;h.pos<m;){let g=h.uint32();switch(g>>>3){case 1:{if(f.limits?.subscriptions!=null&&p.subscriptions.length===f.limits.subscriptions)throw new Ie('Decode error - map field "subscriptions" had too many elements');p.subscriptions.push(r.SubOpts.codec().decode(h,h.uint32(),{limits:f.limits?.subscriptions$}));break}case 2:{if(f.limits?.messages!=null&&p.messages.length===f.limits.messages)throw new Ie('Decode error - map field "messages" had too many elements');p.messages.push(r.Message.codec().decode(h,h.uint32(),{limits:f.limits?.messages$}));break}case 3:{p.control=r.ControlMessage.codec().decode(h,h.uint32(),{limits:f.limits?.control});break}default:{h.skipType(g&7);break}}}return p})),u),r.encode=h=>ue(h,r.codec()),r.decode=(h,d)=>le(h,r.codec(),d)})(Ns||(Ns={}));var Xh=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,s){this.gossip=e,this.msgIdToStrFn=s;for(let n=0;n<t;n++)this.history[n]=[]}get size(){return this.msgs.size}put(e,t,s=!1){let{msgIdStr:n}=e;return this.msgs.has(n)?!1:(this.msgs.set(n,{message:t,validated:s,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),s||this.notValidatedCount++,!0)}observeDuplicate(e,t){let s=this.msgs.get(e);s!=null&&!s.validated&&s.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let s=this.msgs.get(e);if(s==null)return null;let n=(s.iwantCounts.get(t)??0)+1;return s.iwantCounts.set(t,n),{msg:s.message,count:n}}getGossipIDs(e){let t=new Map;for(let s=0;s<this.gossip;s++)this.history[s].forEach(n=>{if((this.msgs.get(n.msgIdStr)?.validated??!1)&&e.has(n.topic)){let i=t.get(n.topic);i==null&&(i=[],t.set(n.topic,i)),i.push(n.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:s,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:s,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach(t=>{let s=this.msgs.get(t.msgIdStr);s!=null&&(this.msgs.delete(t.msgIdStr),s.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)}};X();X();var Iv;(function(r){r.StrictSign="StrictSign",r.StrictNoSign="StrictNoSign"})(Iv||(Iv={}));var un;(function(r){r[r.Signing=0]="Signing",r[r.Anonymous=1]="Anonymous"})(un||(un={}));var Bt;(function(r){r.Error="error",r.Ignore="ignore",r.Reject="reject",r.Blacklisted="blacklisted"})(Bt||(Bt={}));var Pt;(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"})(Pt||(Pt={}));var kt;(function(r){r.duplicate="duplicate",r.invalid="invalid",r.valid="valid"})(kt||(kt={}));function og(r){switch(r){case Ot.Ignore:return Bt.Ignore;case Ot.Reject:return Bt.Reject;default:throw new Error("Unreachable")}}var _v;(function(r){r.forward="forward",r.publish="publish"})(_v||(_v={}));var Ft;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(Ft||(Ft={}));var Fr;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Excess="excess"})(Fr||(Fr={}));var Yi;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(Yi||(Yi={}));var Xi;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(Xi||(Xi={}));var ji;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(ji||(ji={}));function Av(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(s){return this.topicStrToLabel.get(s)??s},onJoin(s){this.topicSubscriptionStatus.set({topicStr:s},1),this.meshPeerCounts.set({topicStr:s},0)},onLeave(s){this.topicSubscriptionStatus.set({topicStr:s},0),this.meshPeerCounts.set({topicStr:s},0)},onAddToMesh(s,n,o){let i=this.toTopic(s);switch(n){case Ft.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case Ft.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case Ft.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case Ft.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case Ft.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case Ft.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:i},o);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:i},o);break}},onRemoveFromMesh(s,n,o){let i=this.toTopic(s);switch(n){case Fr.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:i},o);break;case Fr.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:i},o);break;case Fr.Prune:this.meshPeerChurnEventsPrune.inc({topic:i},o);break;case Fr.Excess:this.meshPeerChurnEventsExcess.inc({topic:i},o);break;default:this.meshPeerChurnEventsUnknown.inc({topic:i},o);break}},onReportValidation(s,n,o){if(this.asyncValidationMcacheHit.inc({hit:s!=null?"hit":"miss"}),s!=null){let i=this.toTopic(s.message.topic);switch(n){case Ot.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case Ot.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case Ot.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(s){this.scoringPenalties.inc({penalty:s},1)},onIhaveRcv(s,n,o){let i=this.toTopic(s);this.ihaveRcvMsgids.inc({topic:i},n),this.ihaveRcvNotSeenMsgids.inc({topic:i},o)},onIwantRcv(s,n){for(let[o,i]of s){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},i)}this.iwantRcvDonthaveMsgids.inc(n)},onIdontwantRcv(s,n){this.idontwantRcvMsgids.inc(s),this.idontwantRcvDonthaveMsgids.inc(n)},onForwardMsg(s,n){let o=this.toTopic(s);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},n)},onPublishMsg(s,n,o,i,a){let c=this.toTopic(s);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},o*i),this.msgPublishPeersByTopic.inc({topic:c},o),this.directPeersPublishedTotal.inc({topic:c},n.direct),this.floodsubPeersPublishedTotal.inc({topic:c},n.floodsub),this.meshPeersPublishedTotal.inc({topic:c},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},n.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(s){let n=this.toTopic(s);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(s){let n=this.toTopic(s);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(s,n){let o=this.toTopic(s);switch(n){case kt.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case kt.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case kt.valid:this.prevalidationValidTotal.inc({topic:o});break;default:this.prevalidationUnknownTotal.inc({topic:o});break}},onMsgRecvInvalid(s,n){let o=this.toTopic(s),i=n.reason===Bt.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:i},1),this.msgReceivedInvalidByTopic.inc({topic:o},1)},onDuplicateMsgDelivery(s,n,o){let i=this.toTopic(s);this.duplicateMsgDeliveryDelay.observe({topic:i},n/1e3),o&&this.duplicateMsgLateDelivery.inc({topic:i},1)},onPublishDuplicateMsg(s){let n=this.toTopic(s);this.duplicateMsgIgnored.inc({topic:n},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(s,n){this.rpcRecvBytes.inc(n),this.rpcRecvCount.inc(1),s.subscriptions!=null&&this.rpcRecvSubscription.inc(s.subscriptions.length),s.messages!=null&&this.rpcRecvMessage.inc(s.messages.length),s.control!=null&&(this.rpcRecvControl.inc(1),s.control.ihave!=null&&this.rpcRecvIHave.inc(s.control.ihave.length),s.control.iwant!=null&&this.rpcRecvIWant.inc(s.control.iwant.length),s.control.graft!=null&&this.rpcRecvGraft.inc(s.control.graft.length),s.control.prune!=null&&this.rpcRecvPrune.inc(s.control.prune.length))},onRpcSent(s,n){if(this.rpcSentBytes.inc(n),this.rpcSentCount.inc(1),s.subscriptions!=null&&this.rpcSentSubscription.inc(s.subscriptions.length),s.messages!=null&&this.rpcSentMessage.inc(s.messages.length),s.control!=null){let o=s.control.ihave?.length??0,i=s.control.iwant?.length??0,a=s.control.graft?.length??0,c=s.control.prune?.length??0,l=s.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(s,n){let o=0,i=0,a=0,c=0;for(let l of s)l>=n.graylistThreshold&&o++,l>=n.publishThreshold&&i++,l>=n.gossipThreshold&&a++,l>=0&&c++;this.peersByScoreThreshold.set({threshold:ji.graylist},o),this.peersByScoreThreshold.set({threshold:ji.publish},i),this.peersByScoreThreshold.set({threshold:ji.gossip},a),this.peersByScoreThreshold.set({threshold:ji.mesh},c),this.score.set(s)},registerScoreWeights(s){for(let[n,o]of s.byTopic)this.scoreWeights.set({topic:n,p:"p1"},o.p1w),this.scoreWeights.set({topic:n,p:"p2"},o.p2w),this.scoreWeights.set({topic:n,p:"p3"},o.p3w),this.scoreWeights.set({topic:n,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:n,p:"p4"},o.p4w);this.scoreWeights.set({p:"p5"},s.p5w),this.scoreWeights.set({p:"p6"},s.p6w),this.scoreWeights.set({p:"p7"},s.p7w)},registerScorePerMesh(s,n){let o=new Map;s.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(n.get(l)??0)}),this.scorePerMesh.set({topic:i},c)}}}}var be=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var KP={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},HP={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 Cv(r={}){return{...KP,...r,topics:r.topics!=null?Object.entries(r.topics).reduce((e,[t,s])=>(e[t]=zP(s),e),{}):{}}}function zP(r={}){return{...HP,...r}}function Tv(r){for(let[e,t]of Object.entries(r.topics))try{qP(t)}catch(s){throw new be(`invalid score parameters for topic ${e}: ${s.message}`)}if(r.topicScoreCap<0)throw new be("invalid topic score cap; must be positive (or 0 for no cap)");if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new be("missing application specific score function");if(r.IPColocationFactorWeight>0)throw new be("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new be("invalid IPColocationFactorThreshold; must be at least 1");if(r.behaviourPenaltyWeight>0)throw new be("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new be("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(r.decayInterval<1e3)throw new be("invalid DecayInterval; must be at least 1s");if(r.decayToZero<=0||r.decayToZero>=1)throw new be("invalid DecayToZero; must be between 0 and 1")}function qP(r){if(r.topicWeight<0)throw new be("invalid topic weight; must be >= 0");if(r.timeInMeshQuantum===0)throw new be("invalid TimeInMeshQuantum; must be non zero");if(r.timeInMeshWeight<0)throw new be("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new be("invalid TimeInMeshQuantum; must be positive");if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new be("invalid TimeInMeshCap; must be positive");if(r.firstMessageDeliveriesWeight<0)throw new be("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new be("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new be("invalid FirstMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight>0)throw new be("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new be("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new be("invalid MeshMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new be("invalid MeshMessageDeliveriesThreshold; must be positive");if(r.meshMessageDeliveriesWindow<0)throw new be("invalid MeshMessageDeliveriesWindow; must be non-negative");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new be("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(r.meshFailurePenaltyWeight>0)throw new be("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new be("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(r.invalidMessageDeliveriesWeight>0)throw new be("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new be("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var $P={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function Pv(r={}){return{...$P,...r}}function Qh(r,e,t=()=>!0){let s=new Set;if(e<=0)return s;for(let n of r){if(s.size>=e)break;t(n)&&(s.add(n),r.delete(n))}return s}function kv(r,e){return Qh(r,e,()=>!0)}var Zh=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 Dv(r,e,t,s){let n=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,p=f*f;l+=p*c.meshMessageDeliveriesWeight}let h=a.meshFailurePenalty;l+=h*c.meshFailurePenaltyWeight;let d=a.invalidMessageDeliveries*a.invalidMessageDeliveries;l+=d*c.invalidMessageDeliveriesWeight,n+=l*c.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let o=t.appSpecificScore(r);if(n+=o*t.appSpecificWeight,e.knownIPs.forEach(i=>{if(t.IPColocationFactorWhitelist.has(i))return;let a=s.get(i),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let l=c-t.IPColocationFactorThreshold,u=l*l;n+=u*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let i=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=i*i;n+=a*t.behaviourPenaltyWeight}return n}var Lv=we(Ov(),1);var Ut;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(Ut||(Ut={}));var Jh=class{records;queue;constructor(){this.records=new Map,this.queue=new Lv.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Ut.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let s={msgId:e,expire:Date.now()+12e4};return this.queue.push(s),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 ed=class{params;metrics;peerStats=new Map;peerIPs=new Zh(()=>new Set);scoreCache=new Map;deliveryRecords=new Jh;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,s,n){this.params=e,this.metrics=t,Tv(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??Dv,this.log=s.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((s,n)=>{if(!s.connected){e>s.expire&&(this.removeIPsForPeer(n,s.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n));return}Object.entries(s.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)))}),s.behaviourPenalty*=this.params.behaviourPenaltyDecay,s.behaviourPenalty<t&&(s.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let s=Date.now(),n=this.scoreCache.get(e);if(n!=null&&n.cacheUntil>s)return n.score;this.metrics?.scoreFnRuns.inc();let o=this.computeScore(e,t,this.params,this.peerIPs),i=s+this.scoreCacheValidityMs;return n!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(o-n.score)),n.score=o,n.cacheUntil=i):this.scoreCache.set(e,{score:o,cacheUntil:i}),o}addPenalty(e,t,s){let n=this.peerStats.get(e);n!=null&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(s))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let s=this.peerStats.get(e);s?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let s=this.peerStats.get(e);s?.knownIPs.delete(t);let n=this.peerIPs.get(t);n!=null&&(n.delete(e),n.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(([s,n])=>{n.firstMessageDeliveries=0;let o=this.params.topics[s].meshMessageDeliveriesThreshold;if(n.inMesh&&n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<o){let i=o-n.meshMessageDeliveries;n.meshFailurePenalty+=i*i}n.inMesh=!1,n.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);n!=null&&(n.inMesh=!0,n.graftTime=Date.now(),n.meshTime=0,n.meshMessageDeliveriesActive=!1)}}prune(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);if(n!=null){let o=this.params.topics[t].meshMessageDeliveriesThreshold;if(n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<o){let i=o-n.meshMessageDeliveries;n.meshFailurePenalty+=i*i}n.meshMessageDeliveriesActive=!1,n.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,s){this.markFirstMessageDelivery(e,s);let n=this.deliveryRecords.ensureRecord(t),o=Date.now();if(n.status!==Ut.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-n.firstSeenTsMs,Ut[n.status]);return}n.status=Ut.valid,n.validated=o,n.peers.forEach(i=>{i!==e.toString()&&this.markDuplicateMessageDelivery(i,s)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,s,n){switch(n){case Bt.Error:this.markInvalidMessageDelivery(e,s);return;case Bt.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==Ut.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,Ut[o.status]);return}if(n===Bt.Ignore){o.status=Ut.ignored,o.peers.clear();return}o.status=Ut.invalid,this.markInvalidMessageDelivery(e,s),o.peers.forEach(i=>{this.markInvalidMessageDelivery(i,s)}),o.peers.clear()}duplicateMessage(e,t,s){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case Ut.unknown:n.peers.add(e);break;case Ut.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,s,n.validated);break;case Ut.invalid:this.markInvalidMessageDelivery(e,s);break;case Ut.ignored:break}}markInvalidMessageDelivery(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);n!=null&&(n.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);if(n!=null){let o=this.params.topics[t].firstMessageDeliveriesCap;n.firstMessageDeliveries=Math.min(o,n.firstMessageDeliveries+1),n.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,n.meshMessageDeliveries=Math.min(o,n.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,s){let n=this.peerStats.get(e);if(n!=null){let o=s!==void 0?Date.now():0,i=this.getPtopicStats(n,t);if(i!=null&&i.inMesh){let a=this.params.topics[t];if(s!==void 0){let l=o-s,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 s of t){let n=this.peerIPs.get(s);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(s))}}getPtopicStats(e,t){let s=e.topics[t];return s!==void 0?s:this.params.topics[t]!==void 0?(s={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=s,s):null}};function GP(r,e,t,s,n){let o=0,i=new Map;if(Object.entries(e.topics).forEach(([d,f])=>{let p=n.get(d)??"unknown",m=t.topics[d];if(m===void 0)return;let g=i.get(p);g==null&&(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(p,g));let y=0,w=0,b=0,x=0,E=0;if(f.inMesh){let v=Math.max(f.meshTime/m.timeInMeshQuantum,m.timeInMeshCap);y+=v*m.timeInMeshWeight}let P=f.firstMessageDeliveries;if(P>m.firstMessageDeliveriesCap&&(P=m.firstMessageDeliveriesCap),w+=P*m.firstMessageDeliveriesWeight,f.meshMessageDeliveriesActive&&f.meshMessageDeliveries<m.meshMessageDeliveriesThreshold){let v=m.meshMessageDeliveriesThreshold-f.meshMessageDeliveries,M=v*v;b+=M*m.meshMessageDeliveriesWeight}let T=f.meshFailurePenalty;x+=T*m.meshFailurePenaltyWeight;let D=f.invalidMessageDeliveries*f.invalidMessageDeliveries;E+=D*m.invalidMessageDeliveriesWeight,o+=(y+w+b+x+E)*m.topicWeight,g.p1w+=y,g.p2w+=w,g.p3w+=b,g.p3bw+=x,g.p4w+=E}),t.topicScoreCap>0&&o>t.topicScoreCap){o=t.topicScoreCap;let d=t.topicScoreCap/o;for(let f of i.values())f.p1w*=d,f.p2w*=d,f.p3w*=d,f.p3bw*=d,f.p4w*=d}let a=0,c=0,l=0,u=t.appSpecificScore(r);a+=u*t.appSpecificWeight,e.knownIPs.forEach(d=>{if(t.IPColocationFactorWhitelist.has(d))return;let f=s.get(d),p=f!=null?f.size:0;if(p>t.IPColocationFactorThreshold){let m=p-t.IPColocationFactorThreshold,g=m*m;c+=g*t.IPColocationFactorWeight}});let h=e.behaviourPenalty*e.behaviourPenalty;return l+=h*t.behaviourPenaltyWeight,o+=a+c+l,{byTopic:i,p5w:a,p6w:c,p7w:l,score:o}}function Rv(r,e,t,s,n){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let i of r){let a=e.get(i);if(a!=null){let c=GP(i,a,t,s,n);for(let[l,u]of c.byTopic){let h=o.byTopic.get(l);h==null&&(h={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(l,h)),h.p1w.push(u.p1w),h.p2w.push(u.p2w),h.p3w.push(u.p3w),h.p3bw.push(u.p3bw),h.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 td=class{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,s){this.rawStream=e,this.pushable=dt(),this.closeController=new AbortController,this.maxBufferSize=s.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(n=>{e.abort(n)})}),st(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(Wi.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()}},rd=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(s=>{e.abort(s)})}),this.source=st(this.rawStream,s=>Yc(s,t))}async close(){this.closeController.abort()}};var sd=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,s){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=s,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let s=Math.floor(Math.random()*t.length),n=t[s],o=this.msgIdToStrFn(n),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,s=0;return this.promises.forEach((n,o)=>{n.forEach((i,a)=>{i<e&&(t.set(a,(t.get(a)??0)+1),n.delete(a),s++)}),n.size===0&&this.promises.delete(o)}),this.metrics?.iwantPromiseBroken.inc(s),t}deliverMessage(e,t=!1){this.trackMessage(e);let s=this.promises.get(e);s!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(s.size)))}rejectMessage(e,t){switch(this.trackMessage(e),t){case Bt.Error:return;default:break}this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[s,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(s),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))}}};ft();X();ce();ir();Kr();ge();Se();var Nv=L("libp2p-pubsub:");async function Bv(r,e,t,s){switch(r.type){case un.Signing:{let n={from:r.author.toMultihash().bytes,data:s,seqno:Gr(8),topic:e,signature:void 0,key:void 0},o=Ye([Nv,Ns.Message.encode(n)]);n.signature=await r.privateKey.sign(o),n.key=r.key;let i={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${K(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:Je(n.key)};return{raw:n,msg:i}}case un.Anonymous:return{raw:{from:void 0,data:s,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 Fv(r,e){switch(r){case jo:return e.signature!=null?{valid:!1,error:Pt.SignaturePresent}:e.seqno!=null?{valid:!1,error:Pt.SeqnoPresent}:e.from!=null?{valid:!1,error:Pt.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case In:{if(e.seqno==null)return{valid:!1,error:Pt.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:Pt.InvalidSeqno};if(e.signature==null)return{valid:!1,error:Pt.InvalidSignature};if(e.from==null)return{valid:!1,error:Pt.InvalidPeerId};let t;try{t=Pr(Ht(e.from))}catch{return{valid:!1,error:Pt.InvalidPeerId}}let s;if(e.key!=null){if(s=Je(e.key),t.publicKey!==void 0&&!s.equals(t.publicKey))return{valid:!1,error:Pt.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:Pt.InvalidPeerId};s=t.publicKey}let n={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=Ye([Nv,Ns.Message.encode(n)]);return await s.verify(o,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${K(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:s}}:{valid:!1,error:Pt.InvalidSignature}}default:throw new Error("Unreachable")}}function Ur(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 ig(r){return r.control===void 0&&(r.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),r}function is(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 s=e(),n=r[t];r[t]=r[s],r[s]=n}return r}Se();function Uv(r){return K(r,"base64")}ft();X();function Kv(r,e,t){switch(r){case In:return{type:un.Signing,author:e,key:Ve(t.publicKey),privateKey:t};case jo:return{type:un.Anonymous};default:throw new Error(`Unknown signature policy "${r}"`)}}ft();ir();us();ge();Se();var Hv=(r,e)=>{let t=L(e.toString(16).padStart(16,"0"),"base16"),s=Ve(r),n=new Uint8Array(s.byteLength+t.length);return n.set(s,0),n.set(t,s.byteLength),n};us();function zv(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return Hv(r.from.publicKey??r.key,r.sequenceNumber)}async function qv(r){return Qe.encode(r.data)}var nd;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(nd||(nd={}));function $v(r){for(let e of r.tuples())switch(e[0]){case nd.ip4:case nd.ip6:return h4(e[0],e[1]);default:break}return null}var Zi=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,s]of this.entries.entries())if(s.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 tr;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(tr||(tr={}));var ag=class extends Xe{globalSignaturePolicy;multicodecs=[Yh,xv,ng];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=dt({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=Yh;opts;decodeRpcLimits;metrics;status={code:tr.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let s={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:Cv(t.scoreParams),scoreThresholds:Pv(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=s.decodeRpcLimits??Sv,this.globalSignaturePolicy=s.globalSignaturePolicy??In,s.fallbackToFloodsub&&this.multicodecs.push(sg),this.log=e.logger.forComponent(s.debugName??"libp2p:gossipsub"),this.opts=s,this.direct=new Set(s.directPeers.map(n=>n.id.toString())),this.seenCache=new Zi({validityMs:s.seenTTL}),this.publishedMessageIds=new Zi({validityMs:s.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case In:this.msgIdFn=zv;break;case jo:this.msgIdFn=qv;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new Zi({validityMs:s.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Uv,this.mcache=t.messageCache??new Xh(s.mcacheGossip,s.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 n=Math.max(...Object.values(s.scoreParams.topics).map(i=>i.meshMessageDeliveriesWindow),1e3),o=Av(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:s.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:n/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 sd(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new ed(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:s.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=s.allowedTopics!=null?new Set(s.allowedTopics):null}[Symbol.toStringTag]="@chainsafe/libp2p-gossipsub";[et]=["@libp2p/pubsub"];[ka]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===tr.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=Kv(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=dt({objectMode:!0}),st(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},s=await Promise.all(this.multicodecs.map(async o=>e.register(o,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:tr.started,registrarTopologyIds:s,heartbeatTimeout:n,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!==tr.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:tr.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 n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let s=[];for(let n of this.streamsOutbound.values())s.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())s.push(n.close());this.streamsInbound.clear(),await Promise.all(s),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 s=t.remotePeer;this.addPeer(s,t.direction,t.remoteAddr),this.createInboundStream(s,e),this.outboundInflightQueue.push({peerId:s,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 s=e.toString();if(this.peers.has(s)&&!this.streamsOutbound.has(s))try{let n=new td(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(s,n);let o=n.protocol;o===sg&&this.floodsubPeers.add(s),this.metrics?.peersPerProtocol.inc({protocol:o},1),this.subscriptions.size>0&&(this.log("send subscriptions to",s),this.sendSubscriptions(s,Array.from(this.subscriptions),!0))}catch(n){this.log.error("createOutboundStream error",n)}}createInboundStream(e,t){if(!this.isStarted())return;let s=e.toString();if(!this.peers.has(s))return;let n=this.streamsInbound.get(s);n!==void 0&&(this.log("replacing existing inbound steam %s",s),n.close().catch(i=>{this.log.error(i)})),this.log("create inbound stream %s",s);let o=new rd(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(s,o),this.pipePeerReadStream(e,o.source).catch(i=>{this.log(i)})}addPeer(e,t,s){let n=e.toString();if(!this.peers.has(n)){this.log("new peer %p",e),this.peers.set(n,e),this.score.addPeer(n);let o=$v(s);o!==null?this.score.addIP(n,o):this.log("Added peer has no IP in current address %s %s",n,s.toString()),this.outbound.has(n)||this.outbound.set(n,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 s=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);s!=null&&this.metrics?.peersPerProtocol.inc({protocol:s.protocol},-1),s?.close().catch(o=>{this.log.error(o)}),n?.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,Fr.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===tr.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(s=>this.peers.get(s)??$(s))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await st(t,async s=>{for await(let n of s)try{let o=n.subarray(),i=Ns.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(s){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(s,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 s=t.subscriptions!=null?t.subscriptions.length:0,n=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 ${s} messages ${n} ihave ${o} iwant ${i} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let l=[];t.subscriptions.forEach(u=>{let h=u.topic,d=u.subscribe===!0;if(h!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,d),l.push({topic:h,subscribe:d})}}),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(h=>{this.metrics?.onMsgRecvError(l.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await u}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,s){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);n==null&&(n=new Set,this.topics.set(t,n)),s?n.add(e.toString()):n.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let s=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,s.code);let n=s.code;switch(n){case kt.duplicate:this.score.duplicateMessage(e.toString(),s.msgIdStr,t.topic),this.gossipTracer.deliverMessage(s.msgIdStr,!0),this.mcache.observeDuplicate(s.msgIdStr,e.toString());return;case kt.invalid:if(s.msgIdStr!=null){let o=s.msgIdStr;this.score.rejectMessage(e.toString(),o,t.topic,s.reason),this.gossipTracer.rejectMessage(o,s.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,s);return;case kt.valid:this.score.validateMessage(s.messageId.msgIdStr),this.gossipTracer.deliverMessage(s.messageId.msgIdStr),this.mcache.put(s.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:s.messageId.msgIdStr,msg:s.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:s.msg}))),this.opts.asyncValidation||this.forwardMessage(s.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let s=this.fastMsgIdFn?.(t),n=s!==void 0?this.fastMsgIdCache?.get(s):void 0;if(n!=null)return{code:kt.duplicate,msgIdStr:n};let o=await Fv(this.globalSignaturePolicy,t);if(!o.valid)return{code:kt.invalid,reason:Bt.Error,error:o.error};let i=o.message;try{this.dataTransform!=null&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(h){return this.log("Invalid message, transform failed",h),{code:kt.invalid,reason:Bt.Error,error:Pt.TransformFailed}}let a=await this.msgIdFn(i),c=this.msgIdToStrFn(a),l={msgId:a,msgIdStr:c};if(s!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(s,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:kt.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 h;try{h=await u(e,i)}catch(d){let f=d.code;f===Ev&&(h=Ot.Ignore),f===vv?h=Ot.Reject:h=Ot.Ignore}if(h!==Ot.Accept)return{code:kt.invalid,reason:og(h),msgIdStr:c}}return{code:kt.valid,messageId:l,msg:i}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,s){this.sendRpc(e,{subscriptions:t.map(n=>({topic:n,subscribe:s})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let s=t.ihave?.length>0?this.handleIHave(e,t.ihave):[],n=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),s.length===0&&n.length===0&&o.length===0)return;let i=this.sendRpc(e,Ur(n,{iwant:s,prune:o})),a=s[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(),s=this.acceptFromWhitelist.get(e);if(s!=null&&s.messagesAccepted<128&&s.acceptUntil>=t)return s.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),n>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let s=this.score.score(e);if(s<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:Xi.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:Xi.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:Xi.MaxIasked}),[];let i=new Map;if(t.forEach(({topicID:l,messageIDs:u})=>{if(l==null||u==null||!this.mesh.has(l))return;let h=0;u.forEach(d=>{let f=this.msgIdToStrFn(d);this.seenCache.has(f)||(i.set(f,d),h++)}),this.metrics?.onIhaveRcv(l,u.length,h)}),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 is(c),c=c.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:c}]}handleIWant(e,t){if(t.length===0)return[];let s=this.score.score(e);if(s<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,s),[];let n=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}n.set(l,u.msg)})}),this.metrics?.onIwantRcv(o,i),n.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",n.size,e),Array.from(n.values()))}async handleGraft(e,t){let s=[],n=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),s.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,Yi.GraftBackoff),i=!1;let h=u+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<h&&this.score.addPenalty(e,1,Yi.GraftBackoff),this.addBackoff(e,c),s.push(c)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,c),s.push(c),i=!1,this.addBackoff(e,c)):l.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(s.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,Ft.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),s.length===0)return[];let a=!1;return Promise.all(s.map(async c=>this.makePrune(e,c,i,a)))}async handlePrune(e,t){let s=this.score.score(e);for(let{topicID:n,backoff:o,peers:i}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,Fr.Prune,1)),typeof o=="number"&&o>0?this.doAddBackoff(e,n,o*1e3):this.addBackoff(e,n),i!=null&&i.length>0&&(s<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,s,n):await this.pxConnect(i)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n,direction:"inbound"}})}}handleIdontwant(e,t){let s=this.idontwantCounts.get(e)??0;if(s>=this.opts.idontwantMaxMessages)return;let n=s,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(s>=this.opts.idontwantMaxMessages)break e;s++;let u=this.msgIdToStrFn(l);o.set(u,this.heartbeatTicks),this.mcache.msgs.has(u)||i++}this.idontwantCounts.set(e,s);let a=s-n;this.metrics?.onIdontwantRcv(a,i)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,s){let n=this.backoff.get(t);n==null&&(n=new Map,this.backoff.set(t,n));let o=Date.now()+s;(n.get(e)??0)<o&&n.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,Yi.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,s)=>{t.forEach((n,o)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(o)}),t.size===0&&this.backoff.delete(s)})}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&&(is(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async s=>{if(s.peerID==null)return;let n=Pr(Ht(s.peerID)),o=n.toString();if(!this.peers.has(o)){if(s.signedPeerRecord==null){t.push(o);return}try{if(!await this.components.peerStore.consumePeerRecord(s.signedPeerRecord,n)){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 s=>this.connect(s)))}async connect(e){this.log("Initiating connection with %s",e);let t=$(e),s=await this.components.connectionManager.openConnection(t);for(let n of this.multicodecs)for(let o of this.components.registrar.getTopologies(n))o.onConnect?.(t,s)}subscribe(e){if(this.status.code!==tr.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!==tr.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 s of this.peers.keys())this.sendSubscriptions(s,[e],!1);this.leave(e)}join(e){if(this.status.code!==tr.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,s=this.backoff.get(e),n=this.fanout.get(e);if(n!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(o=>{!this.direct.has(o)&&this.score.score(o)>=0&&s?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,Ft.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&&s?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,Ft.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!==tr.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 s=>{this.log("LEAVE: Remove mesh link to %s in %s",s,e),await this.sendPrune(s,e)})).catch(s=>{this.log("Error sending prunes to mesh peers",s)}),this.mesh.delete(e))}selectPeersToForward(e,t,s){let n=new Set,o=this.topics.get(e);o!=null&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(s?.has(a)??!1)&&n.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(s?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&n.add(a)}));let i=this.mesh.get(e);return i!=null&&i.size>0&&i.forEach(a=>{t!==a&&!(s?.has(a)??!1)&&n.add(a)}),n}selectPeersToPublish(e){let t=new Set,s={direct:0,floodsub:0,mesh:0,fanout:0},n=this.topics.get(e);if(n!=null)if(this.opts.floodPublish)n.forEach(o=>{this.direct.has(o)?(t.add(o),s.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),s.floodsub++)});else{this.direct.forEach(i=>{n.has(i)&&(t.add(i),s.direct++)}),this.floodsubPeers.forEach(i=>{n.has(i)&&this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),s.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(i=>{t.add(i),s.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),s.mesh++});else{let i=this.fanout.get(e);if(i!=null&&i.size>0)i.forEach(a=>{t.add(a),s.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),s.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:s}}forwardMessage(e,t,s,n){s!=null&&this.score.deliverMessage(s,e,t.topic);let o=this.selectPeersToForward(t.topic,s,n);o.forEach(i=>{this.sendRpc(i,Ur([t]))}),this.metrics?.onForwardMsg(t.topic,o.size)}async publish(e,t,s){let n=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 Bv(this.publishConfig,e,t,o),c=await this.msgIdFn(a),l=this.msgIdToStrFn(c),u=s?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(l)){if(u)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:h,tosendCount:d}=this.selectPeersToPublish(e),f=this.opts.emitSelf&&this.subscriptions.has(e),p=s?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(h.size===0&&!p&&!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=s?.batchPublish??this.opts.batchPublish,g=Ur([i]);if(m)this.sendRpcInBatch(h,g);else for(let w of h)this.sendRpc(w,g)||h.delete(w);let y=Date.now()-n;return this.metrics?.onPublishMsg(e,d,h.size,i.data!=null?i.data.length:0,y),f&&(h.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(h.values()).map(w=>this.peers.get(w)??$(w))}}sendRpcInBatch(e,t){let s=Ns.encode(t),n=Wi.single(s);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(n)}catch(a){e.delete(o),this.log.error(`Cannot send rpc to ${o}`,a)}this.metrics?.onRpcSent(t,s.length)}}reportMessageValidationResult(e,t,s){let n;if(s===Ot.Accept){if(n=this.mcache.validate(e),n!=null){let{message:i,originatingPeers:a}=n;this.score.deliverMessage(t,e,i.topic),this.forwardMessage(e,n.message,t,a)}}else if(n=this.mcache.remove(e),n!=null){let i=og(s),{message:a,originatingPeers:c}=n;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(n,s,o)}sendGraft(e,t){let n=Ur([],{graft:[{topicID:t}]});this.sendRpc(e,n)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],o=Ur([],{prune:n});this.sendRpc(e,o)}sendIDontWants(e,t,s){let n=this.mesh.get(t);if(n==null)return;let o=new Set(n);o.delete(s);for(let a of o)this.streamsOutbound.get(a)?.protocol!==Yh&&o.delete(a);let i=Ur([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(o,i)}sendRpc(e,t){let s=this.streamsOutbound.get(e);if(s==null)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let n=this.control.get(e);n!=null&&(this.piggybackControl(e,t,n),this.control.delete(e));let o=this.gossip.get(e);o!=null&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let i=Ns.encode(t);try{s.push(i)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),n!=null&&this.control.set(e,n),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,s){let n=ig(t);for(let o of s.graft)o.topicID!=null&&(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.graft.push(o);for(let o of s.prune)o.topicID!=null&&!(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.prune.push(o)}piggybackGossip(e,t,s){let n=ig(t);n.control.ihave=s}async sendGraftPrune(e,t,s){let n=this.opts.doPX,o=!1;for(let[i,a]of e){let c=a.map(h=>({topicID:h})),l=[],u=t.get(i);u!=null&&(l=await Promise.all(u.map(async h=>this.makePrune(i,h,n&&!(s.get(i)??!1),o))),t.delete(i)),this.sendRpc(i,Ur([],{graft:c,prune:l}))}for(let[i,a]of t){let c=await Promise.all(a.map(async l=>this.makePrune(i,l,n&&!(s.get(i)??!1),o)));this.sendRpc(i,Ur([],{prune:c}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[s,n]of e)this.doEmitGossip(s,n,t.get(s)??[])}doEmitGossip(e,t,s){if(s.length===0||(is(s),s.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",s.length),t.size===0))return;let n=this.opts.Dlazy,i=this.opts.gossipFactor*t.size,a=t;i>n&&(n=i),n>a.size?n=a.size:a=is(Array.from(a)).slice(0,n),a.forEach(c=>{let l=s;s.length>5e3&&(l=is(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,Ur([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let s=Ur([],{graft:t.graft,prune:t.prune});this.sendRpc(e,s)}}pushGossip(e,t){this.log("Add gossip to %s",e);let s=this.gossip.get(e)??[];this.gossip.set(e,s.concat(t))}async makePrune(e,t,s,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===ng)return{topicID:t,peers:[]};let o=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=o/1e3;if(this.doAddBackoff(e,t,o),!s)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)??$(l),h;try{h=await this.components.peerStore.get(u)}catch(d){if(d.name!=="NotFoundError")throw d}return{peerID:u.toMultihash().bytes,signedPeerRecord:h?.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===tr.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:s,Dscore:n,Dout:o,fanoutTTL:i}=this.opts;this.heartbeatTicks++;let a=new Map,c=p=>{let m=a.get(p);return m===void 0&&(m=this.score.score(p),a.set(p,m)),m},l=new Map,u=new Map,h=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 p of this.idontwants.values())for(let[m,g]of p)this.heartbeatTicks-g>=this.opts.mcacheLength&&p.delete(m);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let d=new Map;this.mesh.forEach((p,m)=>{let g=this.topics.get(m),y=new Set,w=new Set;if(d.set(m,w),g!=null){let E=is(Array.from(g)),P=this.backoff.get(m);for(let T of E){let D=this.streamsOutbound.get(T);if(D!=null&&this.multicodecs.includes(D.protocol)&&!p.has(T)&&!this.direct.has(T)){let v=c(T);P?.has(T)!==!0&&v>=0&&y.add(T),v>=this.opts.scoreThresholds.gossipThreshold&&w.add(T)}}}let b=(E,P)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",E,m),this.addBackoff(E,m),p.delete(E),c(E)>=this.opts.scoreThresholds.gossipThreshold&&w.add(E),this.metrics?.onRemoveFromMesh(m,P,1);let T=u.get(E);T==null?u.set(E,[m]):T.push(m)},x=(E,P)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",E,m),this.score.graft(E,m),p.add(E),w.delete(E),this.metrics?.onAddToMesh(m,P,1);let T=l.get(E);T==null?l.set(E,[m]):T.push(m)};if(p.forEach(E=>{let P=c(E);P<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",E,P,m),b(E,Fr.BadScore),h.set(E,!0))}),p.size<t){let E=e-p.size;kv(y,E).forEach(T=>{x(T,Ft.NotEnough)})}if(p.size>s){let E=Array.from(p);E.sort((T,D)=>c(D)-c(T)),E=E.slice(0,n).concat(is(E.slice(n)));let P=0;if(E.slice(0,e).forEach(T=>{(this.outbound.get(T)??!1)&&P++}),P<o){let T=v=>{let M=E[v];for(let F=v;F>0;F--)E[F]=E[F-1];E[0]=M};if(P>0){let v=P;for(let M=1;M<e&&v>0;M++)(this.outbound.get(E[M])??!1)&&(T(M),v--)}let D=e-P;for(let v=e;v<E.length&&D>0;v++)(this.outbound.get(E[v])??!1)&&(T(v),D--)}E.slice(e).forEach(T=>{b(T,Fr.Excess)})}if(p.size>=t){let E=0;if(p.forEach(P=>{(this.outbound.get(P)??!1)&&E++}),E<o){let P=o-E;Qh(y,P,D=>this.outbound.get(D)===!0).forEach(D=>{x(D,Ft.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&p.size>1){let E=Array.from(p).sort((D,v)=>c(D)-c(v)),P=Math.floor(p.size/2),T=c(E[P]);if(T<this.opts.scoreThresholds.opportunisticGraftThreshold){let D=this.opts.opportunisticGraftPeers,v=Qh(y,D,M=>c(M)>T);for(let M of v)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",M,m),x(M,Ft.Opportunistic)}}});let f=Date.now();this.fanoutLastpub.forEach((p,m)=>{p+i<f&&(this.fanout.delete(m),this.fanoutLastpub.delete(m))}),this.fanout.forEach((p,m)=>{let g=this.topics.get(m);p.forEach(x=>{(!(g?.has(x)??!1)||c(x)<this.opts.scoreThresholds.publishThreshold)&&p.delete(x)});let y=this.topics.get(m),w=[],b=new Set;if(d.set(m,b),y!=null){let x=is(Array.from(y));for(let E of x){let P=this.streamsOutbound.get(E);if(P!=null&&this.multicodecs.includes(P.protocol)&&!p.has(E)&&!this.direct.has(E)){let T=c(E);T>=this.opts.scoreThresholds.publishThreshold&&w.push(E),T>=this.opts.scoreThresholds.gossipThreshold&&b.add(E)}}}if(p.size<e){let x=e-p.size;w.slice(0,x).forEach(E=>{p.add(E),b?.delete(E)})}}),this.emitGossip(d),await this.sendGraftPrune(l,u,h),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,s=()=>!0){let n=this.topics.get(e);if(n==null)return new Set;let o=[];return n.forEach(i=>{let a=this.streamsOutbound.get(i);a!=null&&this.multicodecs.includes(a.protocol)&&s(i)&&o.push(i)}),o=is(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,s=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-s)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let c of this.idontwants.values())n+=c.size;e.cacheSize.set({cache:"idontwants"},n);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=Rv(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:s}=e.detail;this.components.peerStore.merge(this.peers.get(t)??$(t),{tags:{[s]:{value:100}}}).catch(n=>{this.log.error("Error tagging peer %s with topic %s",t,s,n)})};untagMeshPeer=e=>{let{peerId:t,topic:s}=e.detail;this.components.peerStore.merge(this.peers.get(t)??$(t),{tags:{[s]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,s,n)})}};function Vv(r={}){return e=>new ag(e,r)}X();ce();var wk=H("dns4"),xk=H("dns6"),vk=H("dnsaddr"),Ao=qe(H("dns"),vk,wk,xk),ad=qe(H("ip4"),H("ip6")),Ji=qe(j(ad,H("tcp")),j(Ao,H("tcp"))),cd=j(ad,H("udp")),Ek=j(cd,H("utp")),Sk=j(cd,H("quic")),Ik=j(cd,H("quic-v1")),cg=qe(j(Ji,H("ws")),j(Ao,H("ws"))),od=qe(j(cg,H("p2p")),cg),lg=qe(j(Ji,H("wss")),j(Ao,H("wss")),j(Ji,H("tls"),H("ws")),j(Ao,H("tls"),H("ws"))),id=qe(j(lg,H("p2p")),lg),ug=qe(j(Ji,H("http")),j(ad,H("http")),j(Ao,H("http"))),hg=qe(j(Ji,H("https")),j(ad,H("https")),j(Ao,H("https"))),Wv=j(cd,H("webrtc-direct"),H("certhash")),Xv=qe(j(Wv,H("p2p")),Wv),jv=j(Ik,H("webtransport"),H("certhash"),H("certhash")),Zv=qe(j(jv,H("p2p")),jv),Qv=qe(j(od,H("p2p-webrtc-star"),H("p2p")),j(id,H("p2p-webrtc-star"),H("p2p")),j(od,H("p2p-webrtc-star")),j(id,H("p2p-webrtc-star"))),fae=qe(j(od,H("p2p-websocket-star"),H("p2p")),j(id,H("p2p-websocket-star"),H("p2p")),j(od,H("p2p-websocket-star")),j(id,H("p2p-websocket-star"))),Jv=qe(j(ug,H("p2p-webrtc-direct"),H("p2p")),j(hg,H("p2p-webrtc-direct"),H("p2p")),j(ug,H("p2p-webrtc-direct")),j(hg,H("p2p-webrtc-direct"))),Co=qe(cg,lg,ug,hg,Qv,Jv,Ji,Ek,Sk,Ao,Xv,Zv),pae=qe(j(Co,H("p2p-stardust"),H("p2p")),j(Co,H("p2p-stardust"))),hn=qe(j(Co,H("p2p")),Qv,Jv,Xv,Zv,H("p2p")),Yv=qe(j(hn,H("p2p-circuit"),hn),j(hn,H("p2p-circuit")),j(H("p2p-circuit"),hn),j(Co,H("p2p-circuit")),j(H("p2p-circuit"),Co),H("p2p-circuit")),eE=()=>qe(j(Yv,eE),Yv),_o=eE(),tE=qe(j(_o,hn,_o),j(hn,_o),j(_o,hn),_o,hn);var mae=qe(j(_o,H("webrtc"),H("p2p")),j(_o,H("webrtc")),j(Co,H("webrtc"),H("p2p")),j(Co,H("webrtc")),H("webrtc"));function rE(r){function e(t){let s;try{s=G(t)}catch{return!1}let n=r(s.protoNames());return n===null?!1:n===!0||n===!1?n:n.length===0}return e}function j(...r){function e(t){if(t.length<r.length)return null;let s=t;return r.some(n=>(s=typeof n=="function"?n().partialMatch(t):n.partialMatch(t),Array.isArray(s)&&(t=s),s===null)),s}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:rE(e),partialMatch:e}}function qe(...r){function e(s){let n=null;return r.some(o=>{let i=typeof o=="function"?o().partialMatch(s):o.partialMatch(s);return i!=null?(n=i,!0):!1}),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:rE(e),partialMatch:e}}function H(r){let e=r;function t(n){let o;try{o=G(n)}catch{return!1}let i=o.protoNames();return i.length===1&&i[0]===e}function s(n){return n.length===0?null:n[0]===e?n.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:s}}Ze();var _k="bootstrap",Ak=50,Ck=1e3,dg=class extends Xe{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??Ck,this.list=[];for(let s of t.list){if(!tE.matches(s)){this.log.error("Invalid multiaddr");continue}let n=G(s),o=n.getPeerId();if(o==null){this.log.error("Invalid bootstrap multiaddr without peer id");continue}let i={id:$(o),multiaddrs:[n]};this.list.push(i)}this._init=t}[Ta]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[et]=["@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(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??_k]:{value:this._init.tagValue??Ak,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.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function sE(r){return e=>new dg(e,r)}ce();var ld=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(s=>this.seedKey(s)))).filter(s=>s.status==="rejected");t.length>0&&this.log("Failed to seed %d keys",t.length),await new Promise(s=>setTimeout(s,50))})(),this.readyPromise)}async seedKey(e){let t=this.getFret();if(!t)throw new Error("FRET service not available for seeding keys");let s=await Xt(e),n=t.getNeighbors(s,"both",1)}toCacheKey(e){return Buffer.from(e).toString("base64url")}getKnownPeers(){let e=this.getLibp2p();if(!e)return[];let t=e.peerId,s=e.peerStore?.getPeers?.()??[],n=(e.getConnections?.()??[]).map(a=>a.remotePeer),o=[...s.map(a=>a.id),...n];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 s=(e.peerStore?.getPeers?.()??[]).filter(n=>n.id.toString()!==e.peerId.toString()).length;return s===0?{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0}:{mode:"healthy",connections:s}}async awaitHealthy(e,t){let s=Date.now();for(;Date.now()-s<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 n=this.getLibp2p();if(n){let o=n.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,s=10*6e4){let n=e.toString(),i=(this.blacklist.get(n)?.score??0)+Math.max(1,t);this.blacklist.set(n,{score:i,expires:Date.now()+s})}isBlacklisted(e){let t=e.toString(),s=this.blacklist.get(t);return s?s.expires<=Date.now()?(this.blacklist.delete(t),!1):s.score>=3:!1}recordCoordinator(e,t){let s=this.toCacheKey(e);this.coordinatorCache.set(s,{id:t,expires:Date.now()+this.cfg.cacheTTLs.coordinatorMs})}async findNearestPeerToKey(e){let t=this.getFret(),s=this.getLibp2p();if(!s)throw new Error("Libp2p not initialized");if(t){let a=await Xt(e),c=t.getNeighbors(a,"both",1);if(c.length>0){let l=c[0];if(l){let{peerIdFromString:u}=await Promise.resolve().then(()=>(ce(),Ep)),h=u(l);if(!this.isBlacklisted(h))return h}}}let n=(s.getConnections?.()??[]).map(a=>a.remotePeer),o=[s.peerId,...n,...this.getKnownPeers()].filter((a,c,l)=>l.findIndex(u=>u.toString()===a.toString())===c).filter(a=>!this.isBlacklisted(a));return o.length===0?s.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),s=this.clusterCache.get(t);if(s&&s.expires>Date.now())return s.ids;let n=this.getFret(),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");if(n){let f=await Xt(e),p=n.getDiagnostics?.()??{},m=typeof p.estimate=="number"?p.estimate:typeof p.n=="number"?p.n:void 0,g=Math.max(1,Math.min(this.cfg.clusterSize,Number.isFinite(m)?m:this.cfg.clusterSize)),y=n.assembleCohort(f,g),{peerIdFromString:w}=await Promise.resolve().then(()=>(ce(),Ep)),b=y.map(x=>{try{return w(x)}catch(E){return this.log("Invalid peer ID in cohort: %s, %o",x,E),null}}).filter(x=>x!==null&&!this.isBlacklisted(x));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:p.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,p,m)=>!this.isBlacklisted(f)&&m.findIndex(g=>g.toString()===f.toString())===p).sort((f,p)=>this.lexLess(this.xor(f.toMultihash().bytes,a),this.xor(p.toMultihash().bytes,a))?-1:1),h=Math.min(this.cfg.clusterSize,u.length),d=u.slice(0,h);return this.clusterCache.set(t,{ids:d,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),d}async getCoordinator(e){let t=this.toCacheKey(e),s=this.coordinatorCache.get(t);if(s){if(s.expires>Date.now())return s.id;this.coordinatorCache.delete(t)}let n=await this.getCluster(e),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");let i=n.find(a=>!this.isBlacklisted(a))??o.peerId;return this.recordCoordinator(e,i),i}xor(e,t){let s=Math.max(e.length,t.length),n=new Uint8Array(s);for(let o=0;o<s;o++){let i=e[e.length-1-o]??0,a=t[t.length-1-o]??0;n[s-1-o]=i^a}return n}lexLess(e,t){let s=Math.max(e.length,t.length);for(let n=0;n<s;n++){let o=e[n]??0,i=t[n]??0;if(o<i)return!0;if(o>i)return!1}return!1}};function fg(r={}){return e=>new ld(e,r)}var ud=class{peerStatuses=new Map;unreachableThreshold=3;rapidChurnThreshold=5;rapidChurnWindow=1e4;peerTimeoutMs=6e4;recordSuccess(e){let t=Date.now(),s=this.peerStatuses.get(e);s?(s.lastSeen=t,s.consecutiveFailures=0):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:0}),this.cleanupOldPeers()}recordFailure(e){let t=Date.now(),s=this.peerStatuses.get(e);s?(s.consecutiveFailures++,s.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:1})}recordGoodbye(e){let t=Date.now(),s=this.peerStatuses.get(e);s?(s.lastGoodbye=t,s.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,lastGoodbye:t,consecutiveFailures:0})}detectPartition(){let e=Date.now(),t=this.getRecentGoodbyes(this.rapidChurnWindow),s=Array.from(this.peerStatuses.values()).filter(o=>o.consecutiveFailures>=this.unreachableThreshold&&!o.lastGoodbye);return t.length+s.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(s=>s.lastGoodbye&&s.lastGoodbye>t)}cleanupOldPeers(){let e=Date.now()-this.peerTimeoutMs;for(let[t,s]of this.peerStatuses.entries())s.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()}};async function Tk(r){let e=r.storageType??"memory",t;if(e==="file"){if(!r.storagePath)throw new Error('storagePath is required when storageType is "file"');t=new qa(r.storagePath)}else t=new $a;let s=async(b,x)=>{},n=new Ga(b=>new ci(b,t,s)),o,i,a={async update(b){if(!o)throw new Error("ClusterMember not initialized");return await o.update(b)}},c={async get(b,x){return await(i??n).get(b,x)},async pend(b,x){return await(i??n).pend(b,x)},async cancel(b,x){return await(i??n).cancel(b,x)},async commit(b,x){return await(i??n).commit(b,x)}},l=r.id?await $(r.id):void 0,u={start:!1,...l?{peerId:l}:{},addresses:{listen:[`/ip4/0.0.0.0/tcp/${r.port}`]},connectionManager:{autoDial:!0,minConnections:1,maxConnections:16,inboundConnectionUpgradeTimeout:1e4,dialQueue:{concurrency:2,attempts:2}},transports:[dw()],connectionEncrypters:[Zx()],streamMuxers:[lv()],services:{identify:mv({protocolPrefix:`/optimystic/${r.networkName}`}),ping:wv(),pubsub:Vv({allowPublishToZeroTopicPeers:!0,heartbeatInterval:7e3}),cluster:b=>o0({protocolPrefix:`/optimystic/${r.networkName}`,configuredClusterSize:r.clusterSize??10,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})({logger:b.logger,registrar:b.registrar,cluster:a}),repo:b=>c0({protocolPrefix:`/optimystic/${r.networkName}`})({logger:b.logger,registrar:b.registrar,repo:c}),sync:b=>$0({protocolPrefix:`/optimystic/${r.networkName}`})({logger:b.logger,registrar:b.registrar,repo:c}),networkManager:b=>{let E=fg({clusterSize:r.clusterSize??10,expectedRemotes:(r.bootstrapNodes?.length??0)>0,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})(b);try{E.setLibp2p?.(b.libp2p)}catch{}return E},fret:b=>{let E=q0({k:15,m:8,capacity:2048,profile:r.fretProfile??((r.bootstrapNodes?.length??0)>0?"core":"edge"),networkName:r.networkName,bootstraps:r.bootstrapNodes??[]})(b);try{E.setLibp2p(b.libp2p)}catch{}return E}},peerDiscovery:[...r.bootstrapNodes?.length?[sE({list:r.bootstrapNodes})]:[]]},h=await Jb(u);try{h.services?.fret?.setLibp2p?.(h)}catch{}try{h.services?.networkManager?.setLibp2p?.(h)}catch{}await h.start();let d=new ic(h),f=`/optimystic/${r.networkName}`,p=b=>Tn.create(b,d,f),m=new ud,g=h.services?.fret;if(o=n0({storageRepo:n,peerNetwork:d,peerId:h.peerId,protocolPrefix:f,partitionDetector:m,fretService:g,validator:r.validator}),i=a0(d,p,{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},g)({storageRepo:n,localCluster:o,localPeerId:h.peerId}),r.arachnode?.enableRingZulu??!0){let b=h.logger?.forComponent?.("db-p2p:arachnode"),x=h.services?.fret;if(x){let E=new oc(x),P=new nc(t,r.arachnode?.storage??{}),T=new sc(E,P,{minCapacity:100*1024*1024,thresholds:{moveOut:.85,moveIn:.4}}),D=h.peerId.toString(),v=await T.createArachnodeInfo(D);E.setArachnodeInfo(v),b?.("Announced Arachnode membership: Ring %d",v.ringDepth);let M=new rc(E,{connect:(S,_)=>h.dialProtocol(S,[_])},`/optimystic/${r.networkName}`),F=async(S,_)=>await M.restore(S,_);n.createBlockStorage=S=>new ci(S,t,F);let B=setInterval(async()=>{let S=await T.shouldTransition();if(S.shouldMove){b?.("Ring transition needed: moving %s to Ring %d",S.direction,S.newRingDepth);let _=await T.createArachnodeInfo(D);E.setArachnodeInfo(_)}},6e4),I=h.stop.bind(h);h.stop=async()=>{clearInterval(B),await I()}}else b?.("FRET service not available, Arachnode disabled")}return h.coordinatedRepo=i,h.storageRepo=n,h.keyNetwork=d,h}function nE(r,e){let t=Math.max(r.length,e.length),s=new Uint8Array(t);for(let n=0;n<t;n++){let o=r[r.length-1-n]??0,i=e[e.length-1-n]??0;s[t-1-n]=o^i}return s}function oE(r,e){let t=Math.max(r.length,e.length);for(let s=0;s<t;s++){let n=r[s]??0,o=e[s]??0;if(n<o)return!0;if(n>o)return!1}return!1}function iE(r,e){return r.map(t=>({p:t,d:nE(t.id.toMultihash().bytes,e)})).sort((t,s)=>oE(t.d,s.d)?-1:1).map(t=>t.p)}function Pk(r,e,t,s){let n=[e,...t],o=iE(n,r);if(n.length<=3)return{inCluster:o[0].id.equals(e.id),nearest:o};let i=Math.min(s,Math.max(1,Math.floor(n.length/2))),a=o.slice(0,i);return{inCluster:a.some(l=>l.id.equals(e.id)),nearest:a}}function kk(r){let e={id:r.peerId,addrs:r.getMultiaddrs().map(o=>o.toString())},t=r.getConnections(),s={};for(let o of t){let i=o.remotePeer,a=i.toString(),c=s[a]??(s[a]={id:i,addrs:new Set}),l=o.remoteAddr?.toString?.();l&&c.addrs.add(l)}let n=Object.values(s).map(o=>({id:o.id,addrs:Array.from(o.addrs)}));return[e,...n]}var Dk=lr("network:get-manager");function Mk(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){Dk("getNetworkManager setLibp2p failed - %o",t)}return e}return dE(Ok);})();
15
+ `).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,s=e.ipv6.success===0;return t&&s}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let s=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let n=t.pop();n!=null&&s.push(n.close())}await Promise.all(s),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)}};X();var bt="/multistream/1.0.0";X();Ar();at();var md=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},gd=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},yd=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function is(r,e={}){let t=_o(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ue(e.maxDataLength));let s=e?.lengthDecoder??ms,n=e?.lengthEncoder??hr;return{read:async i=>{let a=-1,c=new W;for(;;){c.append(await t.read({...i,bytes:1}));try{a=s(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new md("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new yd("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new gd("message length too long");return t.read({...i,bytes:a})},write:async(i,a)=>{await t.write(new W(n(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new W(...i.flatMap(l=>[n(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}Ar();at();be();X();be();Pe();var K7=R(`
16
+ `);async function Ao(r,e,t){await r.write(e,t)}async function Fw(r,e,t){await r.writeV(e,t)}async function H7(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==K7[0])throw e.log.error("Invalid mss message - missing newline",t),new Ft("Missing newline");return t.sublist(0,-1)}async function dn(r,e){let t=await H7(r,e);return U(t.subarray())}async function Hi(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return z7(r,e[0],t);let s=is(r,{...t,maxDataLength:1024}),n=e.shift();if(n==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',bt,n);let o=R(`${bt}
17
+ `),i=R(`${n}
18
+ `);await Fw(s,[o,i],t),t.log.trace("select: reading multistream-select header");let a=await dn(s,t);if(t.log.trace('select: read "%s"',a),a===bt&&(t.log.trace("select: reading protocol response"),a=await dn(s,t),t.log.trace('select: read "%s"',a)),a===n)return{stream:s.unwrap(),protocol:n};for(let c of e){t.log.trace('select: write "%s"',c),await Ao(s,R(`${c}
19
+ `),t),t.log.trace("select: reading protocol response");let l=await dn(s,t);if(t.log.trace('select: read "%s" for "%s"',l,c),l===c)return{stream:s.unwrap(),protocol:c}}throw new Fn("protocol selection failed")}function z7(r,e,t){let s=r.sink.bind(r),n=r.source,o=!1,i=!1,a=me(),c=!1,l=!1,u=me(),h=!1,d=!1,f=me(),p=is({sink:s,source:n},{...t,maxDataLength:1024});r.sink=async b=>{let{sink:w}=p.unwrap();await w((async function*(){let x=!1;for await(let E of b){if(l&&await u.promise,c)yield E;else{l=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',bt,e,E.byteLength);let P=`${e}
20
+ `;yield new W(Uint8Array.from([19]),R(`${bt}
21
+ `),hr(P.length),R(P),E).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',bt,e,E.byteLength),c=!0,l=!1,u.resolve(),m().catch(C=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,C)})}x=!0}x||await m()})())};async function m(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await g()),h||(t.log.trace("optimistic: doing read protocol for %s stream",e),await y())}finally{i=!1,o=!0,a.resolve()}}async function g(){if(l){await u.promise;return}l=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',bt,e),await p.writeV([R(`${bt}
22
+ `),R(`${e}
23
+ `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',bt,e)}finally{c=!0,l=!1,u.resolve()}}async function y(){if(d){await f.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let b=await dn(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',b),b===bt&&(b=await dn(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',b,e),b!==e)throw new Fn("protocol selection failed")}finally{h=!0,d=!1,f.resolve()}}if(r.source=(async function*(){await m(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*p.unwrap().source})(),r.closeRead!=null){let b=r.closeRead.bind(r);r.closeRead=async w=>{o||await m().catch(x=>{t.log.error("could not negotiate protocol before close read",x)}),await b(w)}}if(r.closeWrite!=null){let b=r.closeWrite.bind(r);r.closeWrite=async w=>{o||await m().catch(x=>{t.log.error("could not negotiate protocol before close write",x)}),await b(w)}}if(r.close!=null){let b=r.close.bind(r);r.close=async w=>{let x=[];l&&x.push(u.promise),d&&x.push(f.promise),x.length>0?await Me(Promise.all(x),w?.signal):(o=!0,i=!1,a.resolve()),await b(w)}}return{stream:r,protocol:e}}at();be();async function zi(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let s=is(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let n=await dn(s,t);if(t.log.trace('handle: read "%s"',n),n===bt){t.log.trace('handle: respond with "%s" for "%s"',bt,n),await Ao(s,R(`${bt}
24
+ `),t),t.log.trace('handle: responded with "%s" for "%s"',bt,n);continue}if(e.includes(n))return t.log.trace('handle: respond with "%s" for "%s"',n,n),await Ao(s,R(`${n}
25
+ `),t),t.log.trace('handle: responded with "%s" for "%s"',n,n),{stream:s.unwrap(),protocol:n};if(n==="ls"){let o=new W(...e.map(i=>dr.single(R(`${i}
26
+ `))),R(`
27
+ `));t.log.trace('handle: respond with "%s" for %s',e,n),await Ao(s,o,t),t.log.trace('handle: responded with "%s" for %s',e,n);continue}t.log.trace('handle: respond with "na" for "%s"',n),await Ao(s,R(`na
28
+ `),t),t.log('handle: responded with "na" for "%s"',n)}}ce();Oe();X();Oe();var q7=500,Om=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;constructor(e,t){this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.status="open",this.timeline=t.maConn.timeline,this.encryption=t.encryption,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this.tags=[],t.muxerFactory!=null&&(this.multiplexer=t.muxerFactory.protocol,this.muxer=t.muxerFactory.createStreamMuxer({direction:this.direction,log:this.log,onIncomingStream:s=>{this.onIncomingStream(s)}}),Promise.all([this.muxer.sink(this.maConn.source),this.maConn.sink(this.muxer.source)]).catch(s=>{this.log.error("error piping data through muxer - %e",s)}))}[Symbol.toStringTag]="Connection";[h5]=!0;get streams(){return this.muxer?.streams??[]}newStream=async(e,t={})=>{if(this.status==="closing")throw new nu("the connection is being closed");if(this.status==="closed")throw new ui("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Va("Cannot open protocol stream on limited connection");if(this.muxer==null)throw new Eo("Connection is not multiplexed");this.log.trace("starting new stream for protocols %s",e);let s=await this.muxer.newStream();this.log.trace("started new stream %s for protocols %s",s.id,e);try{if(t.signal==null){s.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);Y(1/0,c),t={...t,signal:c}}s.log.trace("selecting protocol from protocols %s",e);let{stream:n,protocol:o}=await Hi(s,e,{...t,log:s.log,yieldBytes:!0});s.log("selected protocol %s",o);let i=G7(o,this.components.registrar,t),a=Hw(o,"outbound",this);if(a>=i){let c=new di(`Too many outbound protocol streams for protocol "${o}" - ${a}/${i}`);throw s.abort(c),c}return await this.components.peerStore.merge(this.remotePeer,{protocols:[o]}),s.source=n.source,s.sink=n.sink,s.protocol=o,n.closeWrite!=null&&(s.closeWrite=n.closeWrite),n.closeRead!=null&&(s.closeRead=n.closeRead),n.close!=null&&(s.close=n.close),this.components.metrics?.trackProtocolStream(s,this),s.direction="outbound",s}catch(n){throw 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,n),s.timeline.close==null&&s.abort(n),n}};onIncomingStream(e){let t=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Y(1/0,t),Promise.resolve().then(async()=>{let s=this.components.registrar.getProtocols(),{stream:n,protocol:o}=await zi(e,s,{signal:t,log:e.log,yieldBytes:!1});this.log("incoming %s stream opened",o);let i=$7(o,this.components.registrar);if(Hw(o,"inbound",this)===i){let u=new hu(`Too many inbound protocol streams for protocol "${o}" - limit ${i}`);throw e.abort(u),u}e.source=n.source,e.sink=n.sink,e.protocol=o,n.closeWrite!=null&&(e.closeWrite=n.closeWrite),n.closeRead!=null&&(e.closeRead=n.closeRead),n.close!=null&&(e.close=n.close),await this.components.peerStore.merge(this.remotePeer,{protocols:[o]},{signal:t}),this.components.metrics?.trackProtocolStream(e,this);let{handler:c,options:l}=this.components.registrar.getHandler(o);if(this.limits!=null&&l.runOnLimitedConnection!==!0)throw new Va("Cannot open protocol stream on limited connection");await c({connection:this,stream:e})}).catch(async s=>{this.log.error("error handling incoming stream id %s - %e",e.id,s),e.abort(s)})}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(q7);Y(1/0,t),e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this.muxer?.close(e),await this.maConn.close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.muxer?.abort(e),this.maConn.abort(e),this.status="closed",this.timeline.close=Date.now())}};function zw(r,e){return new Om(r,e)}function $7(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Pm}function G7(r,e,t={}){try{let{options:s}=e.getHandler(r);if(s.maxOutboundStreams!=null)return s.maxOutboundStreams}catch(s){if(s.name!=="UnhandledProtocolError")throw s}return t.maxOutboundStreams??km}function Hw(r,e,t){let s=0;return t.streams.forEach(n=>{n.direction===e&&n.protocol===r&&s++}),s}var bd=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=Tt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(s=>{this.connectionEncrypters.set(s.protocol,s)}),this.streamMuxers=Tt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(s=>{this.streamMuxers.set(s.protocol,s)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,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 s=this.components.connectionGater[e];if(s==null)return;if(await s.apply(this.components.connectionGater,t)===!0)throw new $h(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=cr([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return Y(1/0,t),t}async upgradeInbound(e,t){let s=!1,n=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),s=await Me(this.components.connectionManager.acceptIncomingConnection(e),n),!s)throw new Gh("Connection denied");await Me(this.shouldBlockConnection("denyInboundConnection",e),n),await this._performUpgrade(e,"inbound",{...t,signal:n})}catch(o){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[o.name??"Error"]:!0}),o}finally{n.clear(),s&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let s=e.remoteAddr.getPeerId(),n;s!=null&&(n=G(s),await Me(this.shouldBlockConnection("denyOutboundConnection",n,e),t.signal));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(s){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[s.name??"Error"]:!0}),s}}async _performUpgrade(e,t,s){let n,o,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let u=e;if(s?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),u=await d.protect(e,s))}try{if(n=u,s?.skipEncryption!==!0){s?.onProgress?.(new ke(`upgrader:encrypt-${t}-connection`)),{conn:n,remotePeer:o,protocol:c,streamMuxer:a}=await(t==="inbound"?this._encryptInbound(u,s):this._encryptOutbound(u,s));let d={...u,...n};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,d)}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new sn(`${t} connection that skipped encryption must have a peer id`);let f=G(d);c="native",o=f}if(o.equals(this.components.peerId)){let d=new hi("Can not dial self");throw e.abort(d),d}if(i=n,s?.muxerFactory!=null)a=s.muxerFactory;else if(a==null&&this.streamMuxers.size>0){s?.onProgress?.(new ke(`upgrader:multiplex-${t}-connection`));let d=await(t==="inbound"?this._multiplexInbound({...u,...n},this.streamMuxers,s):this._multiplexOutbound({...u,...n},this.streamMuxers,s));a=d.muxerFactory,i=d.stream}}catch(d){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e);let h=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:o,limits:s?.limits});return h.log("successfully upgraded %s connection",t),h}_createConnection(e){let{id:t,cryptoProtocol:s,direction:n,maConn:o,upgradedConn:i,remotePeer:a,muxerFactory:c,limits:l}=e,u,h=o.timeline;return o.timeline=new Proxy(h,{set:(...d)=>(d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(f){u.log.error("error closing connection after timeline close %e",f)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(f=>{u.log.error("error thrown while dispatching connection:close event %e",f)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now(),u=zw(this.components,{id:t,maConn:i,remotePeer:a,direction:n,muxerFactory:c,encryption:s,limits:l,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout}),this.events.safeDispatchEvent("connection:open",{detail:u}),u}async _encryptInbound(e,t){let s=Array.from(this.connectionEncrypters.keys());try{let{stream:n,protocol:o}=await zi(e,s,{...t,log:e.log}),i=this.connectionEncrypters.get(o);if(i==null)throw new So(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await i.secureInbound(n,t),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,n),new So(n.message)}}async _encryptOutbound(e,t){let s=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",s);let{stream:n,protocol:o}=await Hi(e,s,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(o);if(i==null)throw new So(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await i.secureOutbound(n,t),protocol:o}}catch(n){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,n),new So(n.message)}}async _multiplexOutbound(e,t,s){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:i}=await Hi(e,n,{...s,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new Eo(String(o))}}async _multiplexInbound(e,t,s){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:i}=await zi(e,n,{...s,log:e.log}),a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new Eo(String(o))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var fn=xe(oe("node:process"),1);var wd="2.10.0",xd="js-libp2p";function $w(r,e){let t="node",s=fn.default.versions.node;return fn.default.versions.deno!=null&&(t="deno",s=fn.default.versions.deno),fn.default.versions.bun!=null&&(t="bun",s=fn.default.versions.bun),fn.default.versions.electron!=null&&(t="electron",s=fn.default.versions.electron),`${r??xd}/${e??wd} ${t}/${s.replaceAll("v","")}`}var vd=class extends Ae{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Ae,s=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=s(l),h=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||h},Y(1/0,t),this.peerId=e.peerId,this.logger=e.logger??sh(),this.log=this.logger.forComponent("libp2p"),this.services={};let n=e.nodeInfo?.name??xd,o=e.nodeInfo?.version??wd,i=this.components=bw({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:n,version:o,userAgent:e.nodeInfo?.userAgent??$w(n,o)},logger:this.logger,events:t,datastore:e.datastore??new Ih,connectionGater:xw(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",ew(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(h=>h.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new bd(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??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new pd(this.components,e.transportManager)),this.configureComponent("connectionManager",new od(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new cd(this.components,e.connectionMonitor)),this.configureComponent("registrar",new fd(this.components)),this.configureComponent("addressManager",new Lh(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 hd(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 ld(this.components,{routers:c})),this.configureComponent("randomWalk",new dd(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),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],h=u(this.components);if(h==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=h,this.configureComponent(l,h),h[r0]!=null&&(this.log("registering service %s for content routing",l),c.push(h[r0])),h[s0]!=null&&(this.log("registering service %s for peer routing",l),a.push(h[s0])),h[Ga]!=null&&(this.log("registering service %s for peer discovery",l),h[Ga].addEventListener?.("peer",d=>{this.#e(d)}))}ww(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")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new no;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,s={}){if(t==null)throw new V("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new V("no protocols were provided to open a stream");return(await this.dial(e,s)).newStream(t,s)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){ln(e)&&(e=G(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let s=st([R("/pk/"),e.toMultihash().bytes]),n=await this.contentRouting.get(s,t),o=nt(n);return await this.peerStore.patch(e,{publicKey:o},t),o}async handle(e,t,s){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.handle(n,t,s)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.unhandle(s,t)}))}async register(e,t,s){return this.components.registrar.register(e,t,s)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(s=>{this.log.error(s)})}};async function Gw(r={}){r.privateKey??=await l5("Ed25519");let e=new vd({...await S4(r),peerId:n0(r.privateKey)});return r.start!==!1&&await e.start(),e}var sx=xe(oe("net"),1);X();var rx=xe(oe("net"),1);X();var Ww=xe(oe("node:os"),1);function Vw(r){return!!(r.startsWith("169.254.")||r.toLowerCase().startsWith("fe80"))}var V7={4:"IPv4",6:"IPv6"};function W7(r){return["0.0.0.0","::"].includes(r)}function j7(r){let e=[],t=Ww.default.networkInterfaces();for(let[,s]of Object.entries(t))if(s!=null)for(let n of s)Vw(n.address)||n.family===V7[r]&&e.push(n.address);return e}function jw(r,e){if(r==null)return[];let t=r.toOptions();if(W7(t.host)){let s=[];for(let n of j7(t.family))s.push(q(`/ip${t.family}/${n}/${t.transport}/${e??t.port}`));return s}return[q(`/ip${t.family}/${t.host}/${t.transport}/${e??t.port}`)]}Oe();var Rm=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Lm=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Yw=r=>globalThis.DOMException===void 0?new Lm(r):new DOMException(r),Xw=r=>{let e=r.reason===void 0?Yw("This operation was aborted."):r.reason;return e instanceof Error?e:Yw(e)};function Nm(r,e){let{milliseconds:t,fallback:s,message:n,customTimers:o={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:f}=e;f.aborted&&h(Xw(f)),a=()=>{h(Xw(f))},f.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,h);return}let d=new Rm;i=o.setTimeout.call(void 0,()=>{if(s){try{u(s())}catch(f){h(f)}return}typeof r.cancel=="function"&&r.cancel(),n===!1?u():n instanceof Error?h(n):(d.message=n??`Promise timed out after ${t} milliseconds`,h(d))},t),(async()=>{try{u(await r)}catch(f){h(f)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},l}var Y7=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 X7(r,e,t){let s,n=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!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}=Y7(r),h=(...f)=>{let p=t.multiArgs?f:f[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(s(),o(c)))},d=f=>{s(),i(f)};s=()=>{for(let f of a)u(f,h);for(let f of t.rejectionEvents)u(f,d)};for(let f of a)l(f,h);for(let f of t.rejectionEvents)l(f,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(n.cancel=s,typeof t.timeout=="number"){let o=Nm(n,{milliseconds:t.timeout});return o.cancel=s,o}return n}function Bm(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let s=X7(r,e,t),n=s.then(o=>o[0]);return n.cancel=s.cancel,n}X();X();function Zw(r,e){if(typeof r!="string")throw new V(`invalid ip provided: ${r}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new V(`invalid port provided: ${e}`);if((0,$e.isIPv4)(r))return q(`/ip4/${r}/tcp/${e}`);if((0,$e.isIPv6)(r))return q(`/ip6/${r}/tcp/${e}`);throw new V(`invalid ip:port for creating a multiaddr: ${r}:${e}`)}function Qw(r){if(Q7(r))return(async function*(){let e=r.getReader();try{for(;;){let{done:t,value:s}=await e.read();if(t)return;yield s}}finally{e.releaseLock()}})();if(Z7(r))return r;throw new Error("unknown stream")}function Z7(r){return r[Symbol.asyncIterator]!=null}function Q7(r){return typeof r?.getReader=="function"}function Jw(r){return async e=>{let t=async()=>{J7(e)&&await e.return(void 0)},s,n,o=y=>{s=y,t().catch(b=>{b=new AggregateError([s,b],"The Writable emitted an error, additionally an error occurred while ending the Source")}).finally(()=>{n?.(y)})},i,a=!1,c=()=>{a=!0,i?.()},l,u=!1,h=()=>{u=!0,l?.()},d,f=()=>{d?.()},p=async()=>new Promise((y,b)=>{i=d=y,n=b,r.once("drain",f)}),m=async()=>(await t(),new Promise((y,b)=>{if(a||u||s!=null){y();return}l=i=y,n=b})),g=()=>{r.removeListener("error",o),r.removeListener("close",c),r.removeListener("finish",h),r.removeListener("drain",f)};r.once("error",o),r.once("close",c),r.once("finish",h);try{for await(let y of e){if(!r.writable||r.destroyed||s!=null)break;r.write(y)||await p()}}catch(y){s==null&&r.destroy(y),s=y}try{if(r.writable&&r.end(),await m(),s!=null)throw s}finally{g()}}}function J7(r){return r.return!=null}function Fm(r){return{sink:Jw(r),source:Qw(r)}}var ex=xe(oe("os"),1),tx=xe(oe("path"),1);function qi(r,e={}){let t=r.getPath();if(t!=null)return ex.default.platform()==="win32"?{path:tx.default.join("\\\\.\\pipe\\",t)}:{path:t};let s=r.toOptions();return{...e,...s,ipv6Only:s.family===6}}var Ed=(r,e)=>{let t,s=e.direction,n=e.metrics,o=e.metricPrefix??"",i=e.socketInactivityTimeout??12e4,a=e.socketCloseTimeout??500,c=!1,l=!1;e.listeningAddr?.getPath()!=null&&(e.remoteAddr=e.listeningAddr),e.remoteAddr?.getPath()!=null&&(e.localAddr=e.remoteAddr),r.on("error",g=>{l=!0,c||(m.log.error("%s socket error - %e",s,g),n?.increment({[`${o}error`]:!0})),r.destroy(),m.timeline.close=Date.now()});let u;if(e.remoteAddr!=null)u=e.remoteAddr;else{if(r.remoteAddress==null||r.remotePort==null)throw new V("Could not determine remote address or port");u=Zw(r.remoteAddress,r.remotePort)}let h=qi(u),d=h.path??`${h.host??""}:${h.port??""}`,{sink:f,source:p}=Fm(r);r.setTimeout(i),r.once("timeout",()=>{c=!0,m.log("%s %s socket read timeout",s,d),n?.increment({[`${o}timeout`]:!0}),r.destroy(new Qr),m.timeline.close=Date.now()}),r.once("close",()=>{!c&&!l&&(m.log("%s %s socket close",s,d),n?.increment({[`${o}close`]:!0})),r.destroy(),m.timeline.close=Date.now()}),r.once("end",()=>{m.log("%s %s socket end",s,d),n?.increment({[`${o}end`]:!0})});let m={async sink(g){try{await f((async function*(){for await(let y of g)y instanceof Uint8Array?yield y:yield y.subarray()})())}catch(y){y.type!=="aborted"&&m.log.error("%s %s error in sink - %e",s,d,y)}r.end()},source:p,remoteAddr:u,timeline:{open:Date.now()},async close(g={}){if(r.closed){m.log("the %s %s socket is already closed",s,d);return}if(r.destroyed){m.log("the %s %s socket is already destroyed",s,d);return}if(t!=null)return t.promise;try{t=me(),r.end();let y=eP(r),b=g.signal??AbortSignal.timeout(a);r.writableLength>0&&(m.log("%s %s draining socket",s,d),await ar(y,"drain",b,{errorEvent:"error"}),m.log("%s %s socket drained",s,d)),await Promise.all([ar(y,"close",b,{errorEvent:"error"}),r.destroy()])}catch(y){this.abort(y)}finally{t.resolve()}},abort:g=>{m.log("%s %s socket abort due to error - %e",s,d,g),r.destroy(),m.timeline.close=Date.now()},log:e.logger.forComponent("libp2p:tcp:connection")};return m};function eP(r){return{addEventListener:(t,s)=>{r.addListener(t,s)},removeEventListener:(t,s)=>{r.removeListener(t,s)}}}var pt;(function(r){r[r.INACTIVE=0]="INACTIVE",r[r.ACTIVE=1]="ACTIVE",r[r.PAUSED=2]="PAUSED"})(pt||(pt={}));var Sd=class extends Ae{context;server;sockets=new Set;status={code:pt.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,this.shutdownController=new AbortController,Y(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=rx.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 V("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]:pt.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!==pt.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!==pt.ACTIVE)throw e.destroy(),new Lr("Server is not listening yet");let t;try{t=Ed(e,{listeningAddr:this.status.listeningAddr,socketInactivityTimeout:this.context.socketInactivityTimeout,socketCloseTimeout:this.context.socketCloseTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,logger:this.context.logger,direction:"inbound"})}catch(s){this.log.error("inbound connection failed",s),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(s=>{this.log.error("error attempting to listen server once connection count under limit",s),this.context.closeServerOnMaxConnections?.onListenError?.(s)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&this.pause()}).catch(async s=>{this.log.error("inbound connection upgrade failed",s),this.metrics.errors?.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),t.abort(s)})}getAddrs(){if(this.status.code===pt.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[q(`/unix/${encodeURIComponent(e)}`)]:jw(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===pt.ACTIVE||this.status.code===pt.PAUSED)throw new uu("server is already listening");try{this.status={code:pt.ACTIVE,listeningAddr:e,netConfig:qi(e,this.context)},await this.resume()}catch(t){throw this.status={code:pt.INACTIVE},t}}async close(){let e=[];this.server.listening&&e.push(Bm(this.server,"close")),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(t=>{t.readable&&(e.push(Bm(t,"close")),t.destroy())}),await Promise.all(e)}async resume(){if(this.server.listening||this.status.code===pt.INACTIVE)return;let e=this.status.netConfig;await new Promise((t,s)=>{this.server.once("error",s),this.server.listen(e,t)}),this.status={...this.status,code:pt.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===pt.PAUSED&&e){this.status={code:pt.INACTIVE};return}!this.server.listening||this.status.code!==pt.ACTIVE||(this.log("closing server on %s",this.server.address()),this.status=e?{code:pt.INACTIVE}:{...this.status,code:pt.PAUSED},this.server.close())}};var Id=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"})})}[tu]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Ye]=["@libp2p/transport"];async dial(e,t){t.keepAlive=t.keepAlive??!0,t.noDelay=t.noDelay??!0;let s=await this._connect(e,t),n;try{n=Ed(s,{remoteAddr:e,socketInactivityTimeout:this.opts.outboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.metrics?.events,logger:this.components.logger,direction:"outbound"})}catch(o){throw this.metrics?.errors.increment({outbound_to_connection:!0}),s.destroy(o),o}try{return this.log("new outbound connection %s",n.remoteAddr),await t.upgrader.upgradeOutbound(n,t)}catch(o){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection",o),n.abort(o),o}}async _connect(e,t){t.signal.throwIfAborted(),t.onProgress?.(new ke("tcp:open-connection"));let s;return new Promise((n,o)=>{let i=Date.now(),a=qi(e,{...this.opts.dialOpts??{},...t});this.log("dialing %a",e),s=sx.default.connect(a);let c=f=>{this.log.error("dial to %a errored - %e",e,f);let p=a.path??`${a.host??""}:${a.port}`;f.message=`connection error ${p}: ${f.message}`,this.metrics?.events.increment({error:!0}),d(f)},l=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let f=new Qr(`Connection timeout after ${Date.now()-i}ms`);s.emit("error",f)},u=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),d()},h=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),d(new Bt)},d=f=>{if(s.removeListener("error",c),s.removeListener("timeout",l),s.removeListener("connect",u),t.signal!=null&&t.signal.removeEventListener("abort",h),f!=null){o(f);return}n(s)};s.on("error",c),s.on("timeout",l),s.on("connect",u),t.signal.addEventListener("abort",h)}).catch(n=>{throw s?.destroy(),n})}createListener(e){return new Sd({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,socketInactivityTimeout:this.opts.inboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(t=>Ms.exactMatch(t)||t.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function nx(r={}){return e=>new Id(e,r)}lt();X();ce();function Um(){let r=me(),e=!1;return{sink:async t=>{if(e)throw new Error("already piped");e=!0,r.resolve(t)},source:(async function*(){yield*await r.promise})()}}function ox(){let r=Um(),e=Um();return[{source:r.source,sink:e.sink},{source:e.source,sink:r.sink}]}rt();var $i=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var hs=xe(oe("node:crypto"),1),Qd=xe(dx(),1);var bP=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,fx=bP?xP:wP;function wP(r=0){return new Uint8Array(r)}function xP(r=0){let e=Buffer.allocUnsafe(r);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var px=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 Gm=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 mx={env:{abort:(r,e,t,s)=>{throw Error(`abort: ${r}:${e}:${t}:${s}`)}}};function Vm(r){return(r!==void 0?r:WebAssembly.validate(Gm))?new WebAssembly.Instance(new WebAssembly.Module(Gm),mx).exports:new WebAssembly.Instance(new WebAssembly.Module(px),mx).exports}var ot,vP,Vi,qc,$c,EP,gx,SP;function IP(r){ot=Vm(r),vP=!!ot.HAS_SIMD.valueOf(),Vi=ot.input.value,qc=ot.output.value,$c=new Uint8Array(ot.memory.buffer,Vi,ot.INPUT_LENGTH),EP=new Uint8Array(ot.memory.buffer,qc,ot.PARALLEL_FACTOR*32),gx=new Uint8Array(ot.memory.buffer,qc,32),SP=new Uint32Array(ot.memory.buffer,Vi,ot.INPUT_LENGTH)}IP();function yx(r){return r.length===64?_P(r):r.length<=ot.INPUT_LENGTH?($c.set(r),ot.digest(r.length),Wm()):(ot.init(),AP(r),TP())}function _P(r){if(r.length===64)return $c.set(r),ot.digest64(Vi,qc),Wm();throw new Error("InvalidLengthForDigest64")}function AP(r){let e=ot.INPUT_LENGTH;if(r.length>e)for(let t=0;t<r.length;t+=e){let s=r.subarray(t,t+e);$c.set(s),ot.update(Vi,s.length)}else $c.set(r),ot.update(Vi,r.length)}function TP(){return ot.final(qc),Wm()}function Wm(){let r=fx(32);return r.set(gx),r}at();var xx=xe(wx(),1),PP=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,vx=(0,xx.default)();var Ex=vx&&!PP;var Are=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!vx,Tre=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,Cre=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+"_"+"ENV"]==="test",Pre=typeof navigator<"u"&&navigator.product==="ReactNative";function Ix(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function kd(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function Dd(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Ct(r,...e){if(!Ix(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function jm(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 _x(r,e){Ct(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Ns(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Bs(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function kP(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var DP=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function MP(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Md(r){if(typeof r=="string")r=MP(r);else if(Ix(r))r=Od(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function Ax(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function Tx(r,e){if(r.length!==e.length)return!1;let t=0;for(let s=0;s<r.length;s++)t|=r[s]^e[s];return t===0}var Ym=(r,e)=>{function t(s,...n){if(Ct(s),!DP)throw new Error("Non little-endian hardware is not yet supported");if(r.nonceLength!==void 0){let u=n[0];if(!u)throw new Error("nonce / iv required");r.varSizeNonce?Ct(u):Ct(u,r.nonceLength)}let o=r.tagLength;o&&n[1]!==void 0&&Ct(n[1]);let i=e(s,...n),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");Ct(h)}},c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ct(u),a(i.encrypt.length,h),i.encrypt(u,h)},decrypt(u,h){if(Ct(u),o&&u.length<o)throw new Error("invalid ciphertext length: smaller than tagLength="+o);return a(i.decrypt.length,h),i.decrypt(u,h)}}}return Object.assign(t,r),t};function Xm(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error("invalid output length, expected "+r+", got: "+e.length);if(t&&!OP(e))throw new Error("invalid output, must be aligned");return e}function Sx(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),o=BigInt(4294967295),i=Number(t>>n&o),a=Number(t&o),c=s?4:0,l=s?0:4;r.setUint32(e+c,i,s),r.setUint32(e+l,a,s)}function Cx(r,e,t){kd(t);let s=new Uint8Array(16),n=kP(s);return Sx(n,0,BigInt(e),t),Sx(n,8,BigInt(r),t),s}function OP(r){return r.byteOffset%4===0}function Od(r){return Uint8Array.from(r)}var kx=r=>Uint8Array.from(r.split("").map(e=>e.charCodeAt(0))),RP=kx("expand 16-byte k"),LP=kx("expand 32-byte k"),NP=Ns(RP),BP=Ns(LP);function $(r,e){return r<<e|r>>>32-e}function Zm(r){return r.byteOffset%4===0}var Rd=64,FP=16,Dx=2**32-1,Px=new Uint32Array;function UP(r,e,t,s,n,o,i,a){let c=n.length,l=new Uint8Array(Rd),u=Ns(l),h=Zm(n)&&Zm(o),d=h?Ns(n):Px,f=h?Ns(o):Px;for(let p=0;p<c;i++){if(r(e,t,s,u,i,a),i>=Dx)throw new Error("arx: counter overflow");let m=Math.min(Rd,c-p);if(h&&m===Rd){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let y=0,b;y<FP;y++)b=g+y,f[b]=d[b]^u[y];p+=Rd;continue}for(let g=0,y;g<m;g++)y=p+g,o[y]=n[y]^l[g];p+=m}}function Qm(r,e){let{allowShortKeys:t,extendNonceFn:s,counterLength:n,counterRight:o,rounds:i}=Ax({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return Dd(n),Dd(i),kd(o),kd(t),(a,c,l,u,h=0)=>{Ct(a),Ct(c),Ct(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Ct(u),Dd(h),h<0||h>=Dx)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let f=[],p=a.length,m,g;if(p===32)f.push(m=Od(a)),g=BP;else if(p===16&&t)m=new Uint8Array(32),m.set(a),m.set(a,16),g=NP,f.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);Zm(c)||f.push(c=Od(c));let y=Ns(m);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(g,y,Ns(c.subarray(0,16)),y),c=c.subarray(16)}let b=16-n;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 w=Ns(c);return UP(r,g,y,w,l,u,h,i),Bs(...f),u}}var wt=(r,e)=>r[e++]&255|(r[e++]&255)<<8,Jm=class{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=Md(e),Ct(e,32);let t=wt(e,0),s=wt(e,2),n=wt(e,4),o=wt(e,6),i=wt(e,8),a=wt(e,10),c=wt(e,12),l=wt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>10|n<<6)&7939,this.r[3]=(n>>>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]=wt(e,16+2*u)}process(e,t,s=!1){let n=s?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],h=i[4],d=i[5],f=i[6],p=i[7],m=i[8],g=i[9],y=wt(e,t+0),b=wt(e,t+2),w=wt(e,t+4),x=wt(e,t+6),E=wt(e,t+8),P=wt(e,t+10),C=wt(e,t+12),D=wt(e,t+14),v=o[0]+(y&8191),M=o[1]+((y>>>13|b<<3)&8191),F=o[2]+((b>>>10|w<<6)&8191),B=o[3]+((w>>>7|x<<9)&8191),I=o[4]+((x>>>4|E<<12)&8191),S=o[5]+(E>>>1&8191),_=o[6]+((E>>>14|P<<2)&8191),k=o[7]+((P>>>11|C<<5)&8191),O=o[8]+((C>>>8|D<<8)&8191),N=o[9]+(D>>>5|n),T=0,L=T+v*a+M*(5*g)+F*(5*m)+B*(5*p)+I*(5*f);T=L>>>13,L&=8191,L+=S*(5*d)+_*(5*h)+k*(5*u)+O*(5*l)+N*(5*c),T+=L>>>13,L&=8191;let K=T+v*c+M*a+F*(5*g)+B*(5*m)+I*(5*p);T=K>>>13,K&=8191,K+=S*(5*f)+_*(5*d)+k*(5*h)+O*(5*u)+N*(5*l),T+=K>>>13,K&=8191;let z=T+v*l+M*c+F*a+B*(5*g)+I*(5*m);T=z>>>13,z&=8191,z+=S*(5*p)+_*(5*f)+k*(5*d)+O*(5*h)+N*(5*u),T+=z>>>13,z&=8191;let ne=T+v*u+M*l+F*c+B*a+I*(5*g);T=ne>>>13,ne&=8191,ne+=S*(5*m)+_*(5*p)+k*(5*f)+O*(5*d)+N*(5*h),T+=ne>>>13,ne&=8191;let ae=T+v*h+M*u+F*l+B*c+I*a;T=ae>>>13,ae&=8191,ae+=S*(5*g)+_*(5*m)+k*(5*p)+O*(5*f)+N*(5*d),T+=ae>>>13,ae&=8191;let Q=T+v*d+M*h+F*u+B*l+I*c;T=Q>>>13,Q&=8191,Q+=S*a+_*(5*g)+k*(5*m)+O*(5*p)+N*(5*f),T+=Q>>>13,Q&=8191;let le=T+v*f+M*d+F*h+B*u+I*l;T=le>>>13,le&=8191,le+=S*c+_*a+k*(5*g)+O*(5*m)+N*(5*p),T+=le>>>13,le&=8191;let Ee=T+v*p+M*f+F*d+B*h+I*u;T=Ee>>>13,Ee&=8191,Ee+=S*l+_*c+k*a+O*(5*g)+N*(5*m),T+=Ee>>>13,Ee&=8191;let Ze=T+v*m+M*p+F*f+B*d+I*h;T=Ze>>>13,Ze&=8191,Ze+=S*u+_*l+k*c+O*a+N*(5*g),T+=Ze>>>13,Ze&=8191;let he=T+v*g+M*m+F*p+B*f+I*d;T=he>>>13,he&=8191,he+=S*h+_*u+k*l+O*c+N*a,T+=he>>>13,he&=8191,T=(T<<2)+T|0,T=T+L|0,L=T&8191,T=T>>>13,K+=T,o[0]=L,o[1]=K,o[2]=z,o[3]=ne,o[4]=ae,o[5]=Q,o[6]=le,o[7]=Ee,o[8]=Ze,o[9]=he}finalize(){let{h:e,pad:t}=this,s=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=n,n=e[a]>>>13,e[a]&=8191;e[0]+=n*5,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,s[0]=e[0]+5,n=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+n,n=s[a]>>>13,s[a]&=8191;s[9]-=8192;let o=(n^1)-1;for(let a=0;a<10;a++)s[a]&=o;o=~o;for(let a=0;a<10;a++)e[a]=e[a]&o|s[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;Bs(s)}update(e){jm(this),e=Md(e),Ct(e);let{buffer:t,blockLen:s}=this,n=e.length;for(let o=0;o<n;){let i=Math.min(s-this.pos,n-o);if(i===s){for(;s<=n-o;o+=s)this.process(e,o);continue}t.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===s&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Bs(this.h,this.r,this.buffer,this.pad)}digestInto(e){jm(this),_x(e,this),this.finished=!0;let{buffer:t,h:s}=this,{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)e[o++]=s[i]>>>0,e[o++]=s[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}};function KP(r){let e=(s,n)=>r(n).update(Md(s)).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>r(s),e}var Mx=KP(r=>new Jm(r));function Lx(r,e,t,s,n,o=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],h=e[1],d=e[2],f=e[3],p=e[4],m=e[5],g=e[6],y=e[7],b=n,w=t[0],x=t[1],E=t[2],P=i,C=a,D=c,v=l,M=u,F=h,B=d,I=f,S=p,_=m,k=g,O=y,N=b,T=w,L=x,K=E;for(let ne=0;ne<o;ne+=2)P=P+M|0,N=$(N^P,16),S=S+N|0,M=$(M^S,12),P=P+M|0,N=$(N^P,8),S=S+N|0,M=$(M^S,7),C=C+F|0,T=$(T^C,16),_=_+T|0,F=$(F^_,12),C=C+F|0,T=$(T^C,8),_=_+T|0,F=$(F^_,7),D=D+B|0,L=$(L^D,16),k=k+L|0,B=$(B^k,12),D=D+B|0,L=$(L^D,8),k=k+L|0,B=$(B^k,7),v=v+I|0,K=$(K^v,16),O=O+K|0,I=$(I^O,12),v=v+I|0,K=$(K^v,8),O=O+K|0,I=$(I^O,7),P=P+F|0,K=$(K^P,16),k=k+K|0,F=$(F^k,12),P=P+F|0,K=$(K^P,8),k=k+K|0,F=$(F^k,7),C=C+B|0,N=$(N^C,16),O=O+N|0,B=$(B^O,12),C=C+B|0,N=$(N^C,8),O=O+N|0,B=$(B^O,7),D=D+I|0,T=$(T^D,16),S=S+T|0,I=$(I^S,12),D=D+I|0,T=$(T^D,8),S=S+T|0,I=$(I^S,7),v=v+M|0,L=$(L^v,16),_=_+L|0,M=$(M^_,12),v=v+M|0,L=$(L^v,8),_=_+L|0,M=$(M^_,7);let z=0;s[z++]=i+P|0,s[z++]=a+C|0,s[z++]=c+D|0,s[z++]=l+v|0,s[z++]=u+M|0,s[z++]=h+F|0,s[z++]=d+B|0,s[z++]=f+I|0,s[z++]=p+S|0,s[z++]=m+_|0,s[z++]=g+k|0,s[z++]=y+O|0,s[z++]=b+N|0,s[z++]=w+T|0,s[z++]=x+L|0,s[z++]=E+K|0}function HP(r,e,t,s){let n=r[0],o=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],h=e[3],d=e[4],f=e[5],p=e[6],m=e[7],g=t[0],y=t[1],b=t[2],w=t[3];for(let E=0;E<20;E+=2)n=n+c|0,g=$(g^n,16),d=d+g|0,c=$(c^d,12),n=n+c|0,g=$(g^n,8),d=d+g|0,c=$(c^d,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),p=p+b|0,u=$(u^p,12),i=i+u|0,b=$(b^i,8),p=p+b|0,u=$(u^p,7),a=a+h|0,w=$(w^a,16),m=m+w|0,h=$(h^m,12),a=a+h|0,w=$(w^a,8),m=m+w|0,h=$(h^m,7),n=n+l|0,w=$(w^n,16),p=p+w|0,l=$(l^p,12),n=n+l|0,w=$(w^n,8),p=p+w|0,l=$(l^p,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+h|0,y=$(y^i,16),d=d+y|0,h=$(h^d,12),i=i+h|0,y=$(y^i,8),d=d+y|0,h=$(h^d,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 x=0;s[x++]=n,s[x++]=o,s[x++]=i,s[x++]=a,s[x++]=g,s[x++]=y,s[x++]=b,s[x++]=w}var zP=Qm(Lx,{counterRight:!1,counterLength:4,allowShortKeys:!1}),qP=Qm(Lx,{counterRight:!1,counterLength:8,extendNonceFn:HP,allowShortKeys:!1});var $P=new Uint8Array(16),Ox=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update($P.subarray(t))},GP=new Uint8Array(32);function Rx(r,e,t,s,n){let o=r(e,t,GP),i=Mx.create(o);n&&Ox(i,n),Ox(i,s);let a=Cx(s.length,n?n.length:0,!0);i.update(a);let c=i.digest();return Bs(o,a),c}var Nx=r=>(e,t,s)=>({encrypt(o,i){let a=o.length;i=Xm(a+16,i,!1),i.set(o);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=Rx(r,e,t,c,s);return i.set(l,a),Bs(l),i},decrypt(o,i){i=Xm(o.length-16,i,!1);let a=o.subarray(0,-16),c=o.subarray(-16),l=Rx(r,e,t,a,s);if(!Tx(c,l))throw new Error("invalid tag");return i.set(o.subarray(0,-16)),r(e,t,i,i,1),Bs(l),i}}),eg=Ym({blockSize:64,nonceLength:12,tagLength:16},Nx(zP)),Kre=Ym({blockSize:64,nonceLength:24,tagLength:16},Nx(qP));var Fs=xe(oe("node:crypto"),1),To=Fs&&typeof Fs=="object"&&"webcrypto"in Fs?Fs.webcrypto:Fs&&typeof Fs=="object"&&"randomBytes"in Fs?Fs:void 0;function Po(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Co(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Pt(r,...e){if(!Po(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function Gc(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Co(r.outputLen),Co(r.blockLen)}function ji(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 Fx(r,e){Pt(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Ur(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ld(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Kr(r,e){return r<<32-e|r>>>e}var Ux=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",VP=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ko(r){if(Pt(r),Ux)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=VP[r[t]];return e}var Us={_0:48,_9:57,A:65,F:70,a:97,f:102};function Bx(r){if(r>=Us._0&&r<=Us._9)return r-Us._0;if(r>=Us.A&&r<=Us.F)return r-(Us.A-10);if(r>=Us.a&&r<=Us.f)return r-(Us.a-10)}function Nd(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ux)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 s=new Uint8Array(t);for(let n=0,o=0;n<t;n++,o+=2){let i=Bx(r.charCodeAt(o)),a=Bx(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)}s[n]=i*16+a}return s}function tg(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function pn(r){return typeof r=="string"&&(r=tg(r)),Pt(r),r}function Yi(...r){let e=0;for(let s=0;s<r.length;s++){let n=r[s];Pt(n),e+=n.length}let t=new Uint8Array(e);for(let s=0,n=0;s<r.length;s++){let o=r[s];t.set(o,n),n+=o.length}return t}var Wi=class{};function rg(r){let e=s=>r().update(pn(s)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Vc(r=32){if(To&&typeof To.getRandomValues=="function")return To.getRandomValues(new Uint8Array(r));if(To&&typeof To.randomBytes=="function")return Uint8Array.from(To.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function WP(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),o=BigInt(4294967295),i=Number(t>>n&o),a=Number(t&o),c=s?4:0,l=s?0:4;r.setUint32(e+c,i,s),r.setUint32(e+l,a,s)}function Kx(r,e,t){return r&e^~r&t}function Hx(r,e,t){return r&e^r&t^e&t}var Wc=class extends Wi{constructor(e,t,s,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ld(this.buffer)}update(e){ji(this),e=pn(e),Pt(e);let{view:t,buffer:s,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(n-this.pos,o-i);if(a===n){let c=Ld(e);for(;n<=o-i;i+=n)this.process(c,i);continue}s.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ji(this),Fx(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,Ur(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(s,0),i=0);for(let h=i;h<n;h++)t[h]=0;WP(s,n-8,BigInt(this.length*8),o),this.process(s,0);let a=Ld(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should 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 h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:s,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%t&&e.buffer.set(s),e}clone(){return this._cloneInto()}},Ks=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Bd=BigInt(4294967295),zx=BigInt(32);function jP(r,e=!1){return e?{h:Number(r&Bd),l:Number(r>>zx&Bd)}:{h:Number(r>>zx&Bd)|0,l:Number(r&Bd)|0}}function qx(r,e=!1){let t=r.length,s=new Uint32Array(t),n=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=jP(r[o],e);[s[o],n[o]]=[i,a]}return[s,n]}var sg=(r,e,t)=>r>>>t,ng=(r,e,t)=>r<<32-t|e>>>t,Do=(r,e,t)=>r>>>t|e<<32-t,Mo=(r,e,t)=>r<<32-t|e>>>t,jc=(r,e,t)=>r<<64-t|e>>>t-32,Yc=(r,e,t)=>r>>>t-32|e<<64-t;function us(r,e,t,s){let n=(e>>>0)+(s>>>0);return{h:r+t+(n/2**32|0)|0,l:n|0}}var $x=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Gx=(r,e,t,s)=>e+t+s+(r/2**32|0)|0,Vx=(r,e,t,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0),Wx=(r,e,t,s,n)=>e+t+s+n+(r/2**32|0)|0,jx=(r,e,t,s,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0),Yx=(r,e,t,s,n,o)=>e+t+s+n+o+(r/2**32|0)|0;var XP=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]),mn=new Uint32Array(64),Fd=class extends Wc{constructor(e=32){super(64,e,8,!1),this.A=Ks[0]|0,this.B=Ks[1]|0,this.C=Ks[2]|0,this.D=Ks[3]|0,this.E=Ks[4]|0,this.F=Ks[5]|0,this.G=Ks[6]|0,this.H=Ks[7]|0}get(){let{A:e,B:t,C:s,D:n,E:o,F:i,G:a,H:c}=this;return[e,t,s,n,o,i,a,c]}set(e,t,s,n,o,i,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)mn[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let d=mn[h-15],f=mn[h-2],p=Kr(d,7)^Kr(d,18)^d>>>3,m=Kr(f,17)^Kr(f,19)^f>>>10;mn[h]=m+mn[h-7]+p+mn[h-16]|0}let{A:s,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let d=Kr(a,6)^Kr(a,11)^Kr(a,25),f=u+d+Kx(a,c,l)+XP[h]+mn[h]|0,m=(Kr(s,2)^Kr(s,13)^Kr(s,22))+Hx(s,n,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=n,n=s,s=f+m|0}s=s+this.A|0,n=n+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(s,n,o,i,a,c,l,u)}roundClean(){Ur(mn)}destroy(){this.set(0,0,0,0,0,0,0,0),Ur(this.buffer)}};var Xx=qx(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),ZP=Xx[0],QP=Xx[1],gn=new Uint32Array(80),yn=new Uint32Array(80),og=class extends Wc{constructor(e=64){super(128,e,16,!1),this.Ah=xt[0]|0,this.Al=xt[1]|0,this.Bh=xt[2]|0,this.Bl=xt[3]|0,this.Ch=xt[4]|0,this.Cl=xt[5]|0,this.Dh=xt[6]|0,this.Dl=xt[7]|0,this.Eh=xt[8]|0,this.El=xt[9]|0,this.Fh=xt[10]|0,this.Fl=xt[11]|0,this.Gh=xt[12]|0,this.Gl=xt[13]|0,this.Hh=xt[14]|0,this.Hl=xt[15]|0}get(){let{Ah:e,Al:t,Bh:s,Bl:n,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:d,Gh:f,Gl:p,Hh:m,Hl:g}=this;return[e,t,s,n,o,i,a,c,l,u,h,d,f,p,m,g]}set(e,t,s,n,o,i,a,c,l,u,h,d,f,p,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=s|0,this.Bl=n|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let w=0;w<16;w++,t+=4)gn[w]=e.getUint32(t),yn[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let x=gn[w-15]|0,E=yn[w-15]|0,P=Do(x,E,1)^Do(x,E,8)^sg(x,E,7),C=Mo(x,E,1)^Mo(x,E,8)^ng(x,E,7),D=gn[w-2]|0,v=yn[w-2]|0,M=Do(D,v,19)^jc(D,v,61)^sg(D,v,6),F=Mo(D,v,19)^Yc(D,v,61)^ng(D,v,6),B=Vx(C,F,yn[w-7],yn[w-16]),I=Wx(B,P,M,gn[w-7],gn[w-16]);gn[w]=I|0,yn[w]=B|0}let{Ah:s,Al:n,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:d,Fh:f,Fl:p,Gh:m,Gl:g,Hh:y,Hl:b}=this;for(let w=0;w<80;w++){let x=Do(h,d,14)^Do(h,d,18)^jc(h,d,41),E=Mo(h,d,14)^Mo(h,d,18)^Yc(h,d,41),P=h&f^~h&m,C=d&p^~d&g,D=jx(b,E,C,QP[w],yn[w]),v=Yx(D,y,x,P,ZP[w],gn[w]),M=D|0,F=Do(s,n,28)^jc(s,n,34)^jc(s,n,39),B=Mo(s,n,28)^Yc(s,n,34)^Yc(s,n,39),I=s&o^s&a^o&a,S=n&i^n&c^i&c;y=m|0,b=g|0,m=f|0,g=p|0,f=h|0,p=d|0,{h,l:d}=us(l|0,u|0,v|0,M|0),l=a|0,u=c|0,a=o|0,c=i|0,o=s|0,i=n|0;let _=$x(M,B,S);s=Gx(_,v,F,I),n=_|0}({h:s,l:n}=us(this.Ah|0,this.Al|0,s|0,n|0)),{h:o,l:i}=us(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=us(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=us(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:d}=us(this.Eh|0,this.El|0,h|0,d|0),{h:f,l:p}=us(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:g}=us(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:b}=us(this.Hh|0,this.Hl|0,y|0,b|0),this.set(s,n,o,i,a,c,l,u,h,d,f,p,m,g,y,b)}roundClean(){Ur(gn,yn)}destroy(){Ur(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Zx=rg(()=>new Fd);var Qx=rg(()=>new og);var cg=BigInt(0),ag=BigInt(1);function Ud(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Xc(r,e,t=""){let s=Po(r),n=r?.length,o=e!==void 0;if(!s||o&&n!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Jx(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?cg:BigInt("0x"+r)}function ev(r){return Jx(ko(r))}function Hr(r){return Pt(r),Jx(ko(Uint8Array.from(r).reverse()))}function lg(r,e){return Nd(r.toString(16).padStart(e*2,"0"))}function Kd(r,e){return lg(r,e).reverse()}function kt(r,e,t){let s;if(typeof e=="string")try{s=Nd(e)}catch(o){throw new Error(r+" must be hex string or Uint8Array, cause: "+o)}else if(Po(e))s=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let n=s.length;if(typeof t=="number"&&n!==t)throw new Error(r+" of length "+t+" expected, got "+n);return s}function tv(r,e){if(r.length!==e.length)return!1;let t=0;for(let s=0;s<r.length;s++)t|=r[s]^e[s];return t===0}function ug(r){return Uint8Array.from(r)}var ig=r=>typeof r=="bigint"&&cg<=r;function JP(r,e,t){return ig(r)&&ig(e)&&ig(t)&&e<=r&&r<t}function Xi(r,e,t,s){if(!JP(e,t,s))throw new Error("expected valid "+r+": "+t+" <= n < "+s+", got "+e)}function rv(r){let e;for(e=0;r>cg;r>>=ag,e+=1);return e}var Zc=r=>(ag<<BigInt(r))-ag;function Oo(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function s(n,o,i){let a=r[n];if(i&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${n}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([n,o])=>s(n,o,!1)),Object.entries(t).forEach(([n,o])=>s(n,o,!0))}var hg=()=>{throw new Error("not implemented")};function dg(r){let e=new WeakMap;return(t,...s)=>{let n=e.get(t);if(n!==void 0)return n;let o=r(t,...s);return e.set(t,o),o}}var Ht=BigInt(0),Dt=BigInt(1),Ro=BigInt(2),ov=BigInt(3),iv=BigInt(4),av=BigInt(5),ek=BigInt(7),cv=BigInt(8),tk=BigInt(9),lv=BigInt(16);function Be(r,e){let t=r%e;return t>=Ht?t:e+t}function Sr(r,e,t){let s=r;for(;e-- >Ht;)s*=s,s%=t;return s}function sv(r,e){if(r===Ht)throw new Error("invert: expected non-zero number");if(e<=Ht)throw new Error("invert: expected positive modulus, got "+e);let t=Be(r,e),s=e,n=Ht,o=Dt,i=Dt,a=Ht;for(;t!==Ht;){let l=s/t,u=s%t,h=n-i*l,d=o-a*l;s=t,t=u,n=i,o=a,i=h,a=d}if(s!==Dt)throw new Error("invert: does not exist");return Be(n,e)}function fg(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+Dt)/iv,s=r.pow(e,t);return fg(r,s,e),s}function rk(r,e){let t=(r.ORDER-av)/cv,s=r.mul(e,Ro),n=r.pow(s,t),o=r.mul(e,n),i=r.mul(r.mul(o,Ro),n),a=r.mul(o,r.sub(i,r.ONE));return fg(r,a,e),a}function sk(r){let e=zs(r),t=hv(r),s=t(e,e.neg(e.ONE)),n=t(e,s),o=t(e,e.neg(s)),i=(r+ek)/lv;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,s),h=a.mul(l,n),d=a.mul(l,o),f=a.eql(a.sqr(u),c),p=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(d,h,p);let m=a.eql(a.sqr(u),c),g=a.cmov(l,u,m);return fg(a,g,c),g}}function hv(r){if(r<ov)throw new Error("sqrt is not defined for small field");let e=r-Dt,t=0;for(;e%Ro===Ht;)e/=Ro,t++;let s=Ro,n=zs(r);for(;nv(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return uv;let o=n.pow(s,e),i=(e+Dt)/Ro;return function(c,l){if(c.is0(l))return l;if(nv(c,l)!==1)throw new Error("Cannot find square root");let u=t,h=c.mul(c.ONE,o),d=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===u)throw new Error("Cannot find square root");let g=Dt<<BigInt(u-p-1),y=c.pow(h,g);u=p,h=c.sqr(y),d=c.mul(d,h),f=c.mul(f,y)}return f}}function nk(r){return r%iv===ov?uv:r%cv===av?rk:r%lv===tk?sk(r):hv(r)}var Hs=(r,e)=>(Be(r,e)&Dt)===Dt,ok=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function dv(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=ok.reduce((s,n)=>(s[n]="function",s),e);return Oo(r,t),r}function ik(r,e,t){if(t<Ht)throw new Error("invalid exponent, negatives unsupported");if(t===Ht)return r.ONE;if(t===Dt)return e;let s=r.ONE,n=e;for(;t>Ht;)t&Dt&&(s=r.mul(s,n)),n=r.sqr(n),t>>=Dt;return s}function Hd(r,e,t=!1){let s=new Array(e.length).fill(t?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(s[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(s[c]=r.mul(i,s[c]),r.mul(i,a)),o),s}function nv(r,e){let t=(r.ORDER-Dt)/Ro,s=r.pow(e,t),n=r.eql(s,r.ONE),o=r.eql(s,r.ZERO),i=r.eql(s,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function fv(r,e){e!==void 0&&Co(e);let t=e!==void 0?e:r.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function zs(r,e,t=!1,s={}){if(r<=Ht)throw new Error("invalid field: expected ORDER > 0, got "+r);let n,o,i=!1,a;if(typeof e=="object"&&e!=null){if(s.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(n=d.BITS),d.sqrt&&(o=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(n=e),s.sqrt&&(o=s.sqrt);let{nBitLength:c,nByteLength:l}=fv(r,n);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,h=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:l,MASK:Zc(c),ZERO:Ht,ONE:Dt,allowedLengths:a,create:d=>Be(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Ht<=d&&d<r},is0:d=>d===Ht,isValidNot0:d=>!h.is0(d)&&h.isValid(d),isOdd:d=>(d&Dt)===Dt,neg:d=>Be(-d,r),eql:(d,f)=>d===f,sqr:d=>Be(d*d,r),add:(d,f)=>Be(d+f,r),sub:(d,f)=>Be(d-f,r),mul:(d,f)=>Be(d*f,r),pow:(d,f)=>ik(h,d,f),div:(d,f)=>Be(d*sv(f,r),r),sqrN:d=>d*d,addN:(d,f)=>d+f,subN:(d,f)=>d-f,mulN:(d,f)=>d*f,inv:d=>sv(d,r),sqrt:o||(d=>(u||(u=nk(r)),u(h,d))),toBytes:d=>t?Kd(d,l):lg(d,l),fromBytes:(d,f=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let m=new Uint8Array(l);m.set(d,t?0:m.length-d.length),d=m}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let p=t?Hr(d):ev(d);if(i&&(p=Be(p,r)),!f&&!h.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>Hd(h,d),cmov:(d,f,p)=>p?f:d});return Object.freeze(h)}var zd=BigInt(0),yg=BigInt(1);function pv(r,e){let t=e.negate();return r?t:e}function Qc(r,e){let t=Hd(r.Fp,e.map(s=>s.Z));return e.map((s,n)=>r.fromAffine(s.toAffine(t[n])))}function bv(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function pg(r,e){bv(r,e);let t=Math.ceil(e/r)+1,s=2**(r-1),n=2**r,o=Zc(r),i=BigInt(r);return{windows:t,windowSize:s,mask:o,maxNumber:n,shiftBy:i}}function mv(r,e,t){let{windowSize:s,mask:n,maxNumber:o,shiftBy:i}=t,a=Number(r&n),c=r>>i;a>s&&(a-=o,c+=yg);let l=e*s,u=l+Math.abs(a)-1,h=a===0,d=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:d,isNegF:f,offsetF:l}}function ak(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function ck(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}var mg=new WeakMap,wv=new WeakMap;function gg(r){return wv.get(r)||1}function gv(r){if(r!==zd)throw new Error("invalid wNAF")}var qd=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,s=this.ZERO){let n=e;for(;t>zd;)t&yg&&(s=s.add(n)),n=n.double(),t>>=yg;return s}precomputeWindow(e,t){let{windows:s,windowSize:n}=pg(t,this.bits),o=[],i=e,a=i;for(let c=0;c<s;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE,i=pg(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:d,offsetF:f}=mv(s,a,i);s=c,u?o=o.add(pv(d,t[f])):n=n.add(pv(h,t[l]))}return gv(s),{p:n,f:o}}wNAFUnsafe(e,t,s,n=this.ZERO){let o=pg(e,this.bits);for(let i=0;i<o.windows&&s!==zd;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=mv(s,i,o);if(s=a,!l){let h=t[c];n=n.add(u?h.negate():h)}}return gv(s),n}getPrecomputes(e,t,s){let n=mg.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof s=="function"&&(n=s(n)),mg.set(t,n))),n}cached(e,t,s){let n=gg(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){let o=gg(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,s),t,n)}createCache(e,t){bv(t,this.bits),wv.set(e,t),mg.delete(e)}hasCache(e){return gg(e)!==1}};function $d(r,e,t,s){ak(t,r),ck(s,e);let n=t.length,o=s.length;if(n!==o)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=rv(BigInt(n)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Zc(c),u=new Array(Number(l)+1).fill(i),h=Math.floor((e.BITS-1)/c)*c,d=i;for(let f=h;f>=0;f-=c){u.fill(i);for(let m=0;m<o;m++){let g=s[m],y=Number(g>>BigInt(f)&l);u[y]=u[y].add(t[m])}let p=i;for(let m=u.length-1,g=i;m>0;m--)g=g.add(u[m]),p=p.add(g);if(d=d.add(p),f!==0)for(let m=0;m<c;m++)d=d.double()}return d}function yv(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return dv(e),e}else return zs(r,{isLE:t})}function xv(r,e,t={},s){if(s===void 0&&(s=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>zd))throw new Error(`CURVE.${c} must be positive bigint`)}let n=yv(e.p,t.Fp,s),o=yv(e.n,t.Fn,s),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!n.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:n,Fn:o}}var bn=BigInt(0),mt=BigInt(1),bg=BigInt(2),lk=BigInt(8);function uk(r,e,t,s){let n=r.sqr(t),o=r.sqr(s),i=r.add(r.mul(e.a,n),o),a=r.add(r.ONE,r.mul(e.d,r.mul(n,o)));return r.eql(i,a)}function hk(r,e={}){let t=xv("edwards",r,e,e.FpFnLE),{Fp:s,Fn:n}=t,o=t.CURVE,{h:i}=o;Oo(e,{},{uvRatio:"function"});let a=bg<<BigInt(n.BYTES*8)-mt,c=g=>s.create(g),l=e.uvRatio||((g,y)=>{try{return{isValid:!0,value:s.sqrt(s.div(g,y))}}catch{return{isValid:!1,value:bn}}});if(!uk(s,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(g,y,b=!1){let w=b?mt:bn;return Xi("coordinate "+g,y,w,a),y}function h(g){if(!(g instanceof p))throw new Error("ExtendedPoint expected")}let d=dg((g,y)=>{let{X:b,Y:w,Z:x}=g,E=g.is0();y==null&&(y=E?lk:s.inv(x));let P=c(b*y),C=c(w*y),D=s.mul(x,y);if(E)return{x:bn,y:mt};if(D!==mt)throw new Error("invZ was invalid");return{x:P,y:C}}),f=dg(g=>{let{a:y,d:b}=o;if(g.is0())throw new Error("bad point: ZERO");let{X:w,Y:x,Z:E,T:P}=g,C=c(w*w),D=c(x*x),v=c(E*E),M=c(v*v),F=c(C*y),B=c(v*c(F+D)),I=c(M+c(b*c(C*D)));if(B!==I)throw new Error("bad point: equation left != right (1)");let S=c(w*x),_=c(E*P);if(S!==_)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,b,w,x){this.X=u("x",y),this.Y=u("y",b),this.Z=u("z",w,!0),this.T=u("t",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:b,y:w}=y||{};return u("x",b),u("y",w),new p(b,w,mt,c(b*w))}static fromBytes(y,b=!1){let w=s.BYTES,{a:x,d:E}=o;y=ug(Xc(y,w,"point")),Ud(b,"zip215");let P=ug(y),C=y[w-1];P[w-1]=C&-129;let D=Hr(P),v=b?a:s.ORDER;Xi("point.y",D,bn,v);let M=c(D*D),F=c(M-mt),B=c(E*M-x),{isValid:I,value:S}=l(F,B);if(!I)throw new Error("bad point: invalid y coordinate");let _=(S&mt)===mt,k=(C&128)!==0;if(!b&&S===bn&&k)throw new Error("bad point: x=0 and x_0=1");return k!==_&&(S=c(-S)),p.fromAffine({x:S,y:D})}static fromHex(y,b=!1){return p.fromBytes(kt("point",y),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,b=!0){return m.createCache(this,y),b||this.multiply(bg),this}assertValidity(){f(this)}equals(y){h(y);let{X:b,Y:w,Z:x}=this,{X:E,Y:P,Z:C}=y,D=c(b*C),v=c(E*x),M=c(w*C),F=c(P*x);return D===v&&M===F}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=o,{X:b,Y:w,Z:x}=this,E=c(b*b),P=c(w*w),C=c(bg*c(x*x)),D=c(y*E),v=b+w,M=c(c(v*v)-E-P),F=D+P,B=F-C,I=D-P,S=c(M*B),_=c(F*I),k=c(M*I),O=c(B*F);return new p(S,_,O,k)}add(y){h(y);let{a:b,d:w}=o,{X:x,Y:E,Z:P,T:C}=this,{X:D,Y:v,Z:M,T:F}=y,B=c(x*D),I=c(E*v),S=c(C*w*F),_=c(P*M),k=c((x+E)*(D+v)-B-I),O=_-S,N=_+S,T=c(I-b*B),L=c(k*O),K=c(N*T),z=c(k*T),ne=c(O*N);return new p(L,K,ne,z)}subtract(y){return this.add(y.negate())}multiply(y){if(!n.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:w}=m.cached(this,y,x=>Qc(p,x));return Qc(p,[b,w])[0]}multiplyUnsafe(y,b=p.ZERO){if(!n.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===bn?p.ZERO:this.is0()||y===mt?this:m.unsafe(this,y,w=>Qc(p,w),b)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,o.n).is0()}toAffine(y){return d(this,y)}clearCofactor(){return i===mt?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:b}=this.toAffine(),w=s.toBytes(b);return w[w.length-1]|=y&mt?128:0,w}toHex(){return ko(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(y){return Qc(p,y)}static msm(y,b){return $d(p,n,y,b)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}p.BASE=new p(o.Gx,o.Gy,mt,c(o.Gx*o.Gy)),p.ZERO=new p(bn,mt,mt,bn),p.Fp=s,p.Fn=n;let m=new qd(p,n.BITS);return p.BASE.precompute(8),p}var Gd=class{constructor(e){this.ep=e}static fromBytes(e){hg()}static fromHex(e){hg()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return ko(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function dk(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Oo(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:s}=t,{BASE:n,Fp:o,Fn:i}=r,a=t.randomBytes||Vc,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,M,F)=>{if(Ud(F,"phflag"),M.length||F)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(Hr(v))}function h(v){let M=w.secretKey;v=kt("private key",v,M);let F=kt("hashed private key",e(v),2*M),B=c(F.slice(0,M)),I=F.slice(M,2*M),S=u(B);return{head:B,prefix:I,scalar:S}}function d(v){let{head:M,prefix:F,scalar:B}=h(v),I=n.multiply(B),S=I.toBytes();return{head:M,prefix:F,scalar:B,point:I,pointBytes:S}}function f(v){return d(v).pointBytes}function p(v=Uint8Array.of(),...M){let F=Yi(...M);return u(e(l(F,kt("context",v),!!s)))}function m(v,M,F={}){v=kt("message",v),s&&(v=s(v));let{prefix:B,scalar:I,pointBytes:S}=d(M),_=p(F.context,B,v),k=n.multiply(_).toBytes(),O=p(F.context,k,S,v),N=i.create(_+O*I);if(!i.isValid(N))throw new Error("sign failed: invalid s");let T=Yi(k,i.toBytes(N));return Xc(T,w.signature,"result")}let g={zip215:!0};function y(v,M,F,B=g){let{context:I,zip215:S}=B,_=w.signature;v=kt("signature",v,_),M=kt("message",M),F=kt("publicKey",F,w.publicKey),S!==void 0&&Ud(S,"zip215"),s&&(M=s(M));let k=_/2,O=v.subarray(0,k),N=Hr(v.subarray(k,_)),T,L,K;try{T=r.fromBytes(F,S),L=r.fromBytes(O,S),K=n.multiplyUnsafe(N)}catch{return!1}if(!S&&T.isSmallOrder())return!1;let z=p(I,L.toBytes(),T.toBytes(),M);return L.add(T.multiplyUnsafe(z)).subtract(K).clearCofactor().is0()}let b=o.BYTES,w={secretKey:b,publicKey:b,signature:2*b,seed:b};function x(v=a(w.seed)){return Xc(v,w.seed,"seed")}function E(v){let M=D.randomSecretKey(v);return{secretKey:M,publicKey:f(M)}}function P(v){return Po(v)&&v.length===i.BYTES}function C(v,M){try{return!!r.fromBytes(v,M)}catch{return!1}}let D={getExtendedPublicKey:d,randomSecretKey:x,isValidSecretKey:P,isValidPublicKey:C,toMontgomery(v){let{y:M}=r.fromBytes(v),F=w.publicKey,B=F===32;if(!B&&F!==57)throw new Error("only defined for 25519 and 448");let I=B?o.div(mt+M,mt-M):o.div(M-mt,M+mt);return o.toBytes(I)},toMontgomerySecret(v){let M=w.secretKey;Xc(v,M);let F=e(v.subarray(0,M));return c(F).subarray(0,M)},randomPrivateKey:x,precompute(v=8,M=r.BASE){return M.precompute(v,!1)}};return Object.freeze({keygen:E,getPublicKey:f,sign:m,verify:y,utils:D,Point:r,lengths:w})}function fk(r){let e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,s=zs(e.n,r.nBitLength,!0),n={Fp:t,Fn:s,uvRatio:r.uvRatio},o={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:n,hash:r.hash,eddsaOpts:o}}function pk(r,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:r,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function vv(r){let{CURVE:e,curveOpts:t,hash:s,eddsaOpts:n}=fk(r),o=hk(e,t),i=dk(o,s,n);return pk(r,i)}var Jc=BigInt(0),Zi=BigInt(1),Vd=BigInt(2);function mk(r){return Oo(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function Ev(r){let e=mk(r),{P:t,type:s,adjustScalarBytes:n,powPminus2:o,randomBytes:i}=e,a=s==="x25519";if(!a&&s!=="x448")throw new Error("invalid type");let c=i||Vc,l=a?255:448,u=a?32:56,h=BigInt(a?9:5),d=BigInt(a?121665:39081),f=a?Vd**BigInt(254):Vd**BigInt(447),p=a?BigInt(8)*Vd**BigInt(251)-Zi:BigInt(4)*Vd**BigInt(445)-Zi,m=f+p+Zi,g=I=>Be(I,t),y=b(h);function b(I){return Kd(g(I),u)}function w(I){let S=kt("u coordinate",I,u);return a&&(S[31]&=127),g(Hr(S))}function x(I){return Hr(n(kt("scalar",I,u)))}function E(I,S){let _=D(w(S),x(I));if(_===Jc)throw new Error("invalid private or public key received");return b(_)}function P(I){return E(I,y)}function C(I,S,_){let k=g(I*(S-_));return S=g(S-k),_=g(_+k),{x_2:S,x_3:_}}function D(I,S){Xi("u",I,Jc,t),Xi("scalar",S,f,m);let _=S,k=I,O=Zi,N=Jc,T=I,L=Zi,K=Jc;for(let ne=BigInt(l-1);ne>=Jc;ne--){let ae=_>>ne&Zi;K^=ae,{x_2:O,x_3:T}=C(K,O,T),{x_2:N,x_3:L}=C(K,N,L),K=ae;let Q=O+N,le=g(Q*Q),Ee=O-N,Ze=g(Ee*Ee),he=le-Ze,it=T+L,zo=T-L,ya=g(zo*Q),ba=g(it*Ee),c3=ya+ba,l3=ya-ba;T=g(c3*c3),L=g(k*g(l3*l3)),O=g(le*Ze),N=g(he*(le+g(d*he)))}({x_2:O,x_3:T}=C(K,O,T)),{x_2:N,x_3:L}=C(K,N,L);let z=o(N);return g(O*z)}let v={secretKey:u,publicKey:u,seed:u},M=(I=c(u))=>(Pt(I,v.seed),I);function F(I){let S=M(I);return{secretKey:S,publicKey:P(S)}}return{keygen:F,getSharedSecret:(I,S)=>E(I,S),getPublicKey:I=>P(I),scalarMult:E,scalarMultBase:P,utils:{randomSecretKey:M,randomPrivateKey:M},GuBytes:y.slice(),lengths:v}}var gk=BigInt(0),$s=BigInt(1),Sv=BigInt(2),yk=BigInt(3),bk=BigInt(5),wk=BigInt(8),Qi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),el={p:Qi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:wk,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Av(r){let e=BigInt(10),t=BigInt(20),s=BigInt(40),n=BigInt(80),o=Qi,a=r*r%o*r%o,c=Sr(a,Sv,o)*a%o,l=Sr(c,$s,o)*r%o,u=Sr(l,bk,o)*l%o,h=Sr(u,e,o)*u%o,d=Sr(h,t,o)*h%o,f=Sr(d,s,o)*d%o,p=Sr(f,n,o)*f%o,m=Sr(p,n,o)*f%o,g=Sr(m,e,o)*u%o;return{pow_p_5_8:Sr(g,Sv,o)*r%o,b2:a}}function Tv(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var wg=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Eg(r,e){let t=Qi,s=Be(e*e*e,t),n=Be(s*s*e,t),o=Av(r*n).pow_p_5_8,i=Be(r*s*o,t),a=Be(e*i*i,t),c=i,l=Be(i*wg,t),u=a===r,h=a===Be(-r,t),d=a===Be(-r*wg,t);return u&&(i=c),(h||d)&&(i=l),Hs(i,t)&&(i=Be(-i,t)),{isValid:u||h,value:i}}var qs=zs(el.p,{isLE:!0}),xk=zs(el.n,{isLE:!0}),vk={...el,Fp:qs,hash:Qx,adjustScalarBytes:Tv,uvRatio:Eg},Lo=vv(vk);var tl=(()=>{let r=qs.ORDER;return Ev({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:s}=Av(e);return Be(Sr(t,yk,r)*s,r)},adjustScalarBytes:Tv})})();var xg=wg,Ek=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Sk=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Ik=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),_k=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Iv=r=>Eg($s,r),Ak=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),vg=r=>Lo.Point.Fp.create(Hr(r)&Ak);function _v(r){let{d:e}=el,t=Qi,s=y=>qs.create(y),n=s(xg*r*r),o=s((n+$s)*Ik),i=BigInt(-1),a=s((i-e*n)*s(n+e)),{isValid:c,value:l}=Eg(o,a),u=s(l*r);Hs(u,t)||(u=s(-u)),c||(l=u),c||(i=n);let h=s(i*(n-$s)*_k-a),d=l*l,f=s((l+l)*a),p=s(h*Ek),m=s($s-d),g=s($s+d);return new Lo.Point(s(f*g),s(m*p),s(p*g),s(f*m))}function Tk(r){Pt(r,64);let e=vg(r.subarray(0,32)),t=_v(e),s=vg(r.subarray(32,64)),n=_v(s);return new Gs(t.add(n))}var Gs=class r extends Gd{constructor(e){super(e)}static fromAffine(e){return new r(Lo.Point.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static hashToCurve(e){return Tk(kt("ristrettoHash",e,64))}static fromBytes(e){Pt(e,32);let{a:t,d:s}=el,n=Qi,o=x=>qs.create(x),i=vg(e);if(!tv(qs.toBytes(i),e)||Hs(i,n))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o($s+t*a),l=o($s-t*a),u=o(c*c),h=o(l*l),d=o(t*s*u-h),{isValid:f,value:p}=Iv(o(d*h)),m=o(p*l),g=o(p*m*d),y=o((i+i)*m);Hs(y,n)&&(y=o(-y));let b=o(c*g),w=o(y*b);if(!f||Hs(w,n)||b===gk)throw new Error("invalid ristretto255 encoding 2");return new r(new Lo.Point(y,b,$s,w))}static fromHex(e){return r.fromBytes(kt("ristrettoHex",e,32))}static msm(e,t){return $d(r,Lo.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:s,T:n}=this.ep,o=Qi,i=g=>qs.create(g),a=i(i(s+t)*i(s-t)),c=i(e*t),l=i(c*c),{value:u}=Iv(i(a*l)),h=i(u*a),d=i(u*c),f=i(h*d*n),p;if(Hs(n*f,o)){let g=i(t*xg),y=i(e*xg);e=g,t=y,p=i(h*Sk)}else p=d;Hs(e*f,o)&&(t=i(-t));let m=i((s-t)*p);return Hs(m,o)&&(m=i(-m)),qs.toBytes(m)}equals(e){this.assertSame(e);let{X:t,Y:s}=this.ep,{X:n,Y:o}=e.ep,i=l=>qs.create(l),a=i(t*o)===i(s*n),c=i(s*o)===i(t*n);return a||c}is0(){return this.equals(r.ZERO)}};Gs.BASE=new Gs(Lo.Point.BASE);Gs.ZERO=new Gs(Lo.Point.ZERO);Gs.Fp=qs;Gs.Fn=xk;var Wd=class extends Wi{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Gc(e);let s=pn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(s.length>n?e.create().update(s).digest():s);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ur(o)}update(e){return ji(this),this.iHash.update(e),this}digestInto(e){ji(this),Pt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:s,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},jd=(r,e,t)=>new Wd(r,e).update(t).digest();jd.create=(r,e)=>new Wd(r,e);function Pv(r,e,t){return Gc(r),t===void 0&&(t=new Uint8Array(r.outputLen)),jd(r,pn(t),pn(e))}var Sg=Uint8Array.from([0]),Cv=Uint8Array.of();function kv(r,e,t,s=32){Gc(r),Co(s);let n=r.outputLen;if(s>255*n)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(s/n);t===void 0&&(t=Cv);let i=new Uint8Array(o*n),a=jd.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)Sg[0]=u+1,c.update(u===0?Cv:l).update(t).update(Sg).digestInto(l),i.set(l,n*u),a._cloneInto(c);return a.destroy(),c.destroy(),Ur(l,Sg),i.slice(0,s)}var Yd=Zx;var Ig={hashSHA256(r){return Yd(r.subarray())},getHKDF(r,e){let t=Pv(Yd,e,r),n=kv(Yd,t,void 0,96),o=n.subarray(0,32),i=n.subarray(32,64),a=n.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){let r=tl.utils.randomPrivateKey();return{publicKey:tl.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:tl.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return tl.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,s){return eg(s,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,s,n){return eg(s,e,t).decrypt(r.subarray(),n)}};var Ck=(0,Qd.newInstance)(),Dv=new Qd.ChaCha20Poly1305(Ck),Mv="chacha20-poly1305",Ji=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),rl=Buffer.from([48,42,48,5,6,3,43,101,110,3,33,0]);var _g={hashSHA256(r){let e=hs.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,s){let n=hs.default.createCipheriv(Mv,s,e,{authTagLength:16});if(n.setAAD(t,{plaintextLength:r.byteLength}),r instanceof Uint8Array){let a=n.update(r),c=n.final(),l=n.getAuthTag();return Buffer.concat([a,c,l],a.byteLength+c.byteLength+l.byteLength)}let o=new W;for(let a of r)o.append(n.update(a));let i=n.final();return i.byteLength>0&&o.append(i),o.append(n.getAuthTag()),o},chaCha20Poly1305Decrypt(r,e,t,s,n){let o=r.subarray(r.length-16),i=hs.default.createDecipheriv(Mv,s,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),h=i.final();return h.byteLength>0?Buffer.concat([u,h],u.byteLength+h.byteLength):u}let c=new W;for(let u of a)c.append(i.update(u));let l=i.final();return l.byteLength>0&&c.append(l),c}},Xd={hashSHA256(r){return yx(r.subarray())},chaCha20Poly1305Encrypt(r,e,t,s){return Dv.seal(s,e,r.subarray(),t)},chaCha20Poly1305Decrypt(r,e,t,s,n){let o=Dv.open(s,e,r.subarray(),t,n);if(!o)throw new Error("Invalid chacha20poly1305 decryption");return o}},Zd={...Ig,hashSHA256(r){return _g.hashSHA256(r)},chaCha20Poly1305Encrypt(r,e,t,s){return r.byteLength<1200?Xd.chaCha20Poly1305Encrypt(r,e,t,s):_g.chaCha20Poly1305Encrypt(r,e,t,s)},chaCha20Poly1305Decrypt(r,e,t,s,n){return r.byteLength<1200?Xd.chaCha20Poly1305Decrypt(r,e,t,s,n):_g.chaCha20Poly1305Decrypt(r,e,t,s,n)},generateX25519KeyPair(){let{publicKey:r,privateKey:e}=hs.default.generateKeyPairSync("x25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return{publicKey:r.subarray(rl.length),privateKey:e.subarray(Ji.length)}},generateX25519KeyPairFromSeed(r){let e=hs.default.createPrivateKey({key:Buffer.concat([Ji,r],Ji.byteLength+r.byteLength),type:"pkcs8",format:"der"});return{publicKey:hs.default.createPublicKey(e).export({type:"spki",format:"der"}).subarray(rl.length),privateKey:r}},generateX25519SharedKey(r,e){return e instanceof Uint8Array?e=Buffer.concat([rl,e],rl.byteLength+e.byteLength):e=new W(rl,e).subarray(),r instanceof Uint8Array?r=Buffer.concat([Ji,r],Ji.byteLength+r.byteLength):r=new W(Ji,r).subarray(),hs.default.diffieHellman({publicKey:hs.default.createPublicKey({key:Buffer.from(e.buffer,e.byteOffset,e.byteLength),type:"spki",format:"der"}),privateKey:hs.default.createPrivateKey({key:Buffer.from(r.buffer,r.byteOffset,r.byteLength),type:"pkcs8",format:"der"})})}};Ex&&(Zd.chaCha20Poly1305Encrypt=Xd.chaCha20Poly1305Encrypt,Zd.chaCha20Poly1305Decrypt=Xd.chaCha20Poly1305Decrypt);function Ov(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 ea=r=>{let e=tt(2);return e[0]=r>>8,e[1]=r,e};ea.bytes=2;var sl=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)};sl.bytes=2;function Rv(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"})}}Pe();function Ag(r,e){!e.enabled||!$i||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${U(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${U(r.privateKey,"hex")}`)):e("Missing local static keys."))}function Tg(r,e){!e.enabled||!$i||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${U(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${U(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Lv(r,e){!e.enabled||!$i||e(r?`REMOTE_STATIC_PUBLIC_KEY ${U(r.subarray(),"hex")}`:"Missing remote static public key.")}function Cg(r,e){!e.enabled||!$i||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${U(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Pg(r,e,t){!t.enabled||!$i||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&U(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&U(e.k,"hex")}`))}at();Gt();rt();wa();Vr();be();Pe();rt();var ta=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};rt();var Pk=0,kk=4294967295,Dk="Cipherstate has reached maximum n, a new handshake must be performed",Jd=class{n;bytes;view;constructor(e=Pk){this.n=e,this.bytes=ee(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>kk)throw new Error(Dk)}};var No=ee(0),ra=class{k;n;crypto;constructor(e,t=void 0,s=0){this.crypto=e,this.k=t,this.n=new Jd(s)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let s=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),s}decryptWithAd(e,t,s){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,s);return this.n.increment(),n}},kg=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let s=R(t,"utf-8");this.h=Mk(e,s),this.ck=this.h,this.cs=new ra(e)}mixKey(e){let[t,s]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new ra(this.crypto,s)}mixHash(e){this.h=this.crypto.hash(new W(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,No);return[new ra(this.crypto,e),new ra(this.crypto,t)]}},Dg=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:s,prologue:n,initiator:o,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new kg(t,s),this.ss.mixHash(n),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 s=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+s)throw new Error("message is not long enough");let n=e.sublist(t,t+s);return this.rs=this.ss.decryptAndHash(n),s}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},nl=class extends Dg{writeMessageA(e){return new W(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let s=this.writeS();return this.writeES(),new W(t,s,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new W(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new ta(`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 ta(`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 ta(`handshake stage 2 validation fail: ${t.message}`)}}};function Mk(r,e){if(e.length<=32){let t=ee(32);return t.set(e),t}else return r.hash(e)}lt();X();Vr();be();ws();rt();var e1;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{if(n.lengthDelimited!==!1&&s.fork(),t.webtransportCerthashes!=null)for(let o of t.webtransportCerthashes)s.uint32(10),s.bytes(o);if(t.streamMuxers!=null)for(let o of t.streamMuxers)s.uint32(18),s.string(o);n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={webtransportCerthashes:[],streamMuxers:[]},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(n.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===n.limits.webtransportCerthashes)throw new Se('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(t.bytes());break}case 2:{if(n.limits?.streamMuxers!=null&&o.streamMuxers.length===n.limits.streamMuxers)throw new Se('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=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(e1||(e1={}));var ol;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(s.uint32(10),s.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(s.uint32(18),s.bytes(t.identitySig)),t.extensions!=null&&(s.uint32(34),e1.codec().encode(t.extensions,s)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={identityKey:ee(0),identitySig:ee(0)},i=s==null?t.len:t.pos+s;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=e1.codec().decode(t,t.uint32(),{limits:n.limits?.extensions});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(ol||(ol={}));async function Mg(r,e,t){let s=await r.sign(Nv(e));return ol.encode({identityKey:He(r.publicKey),identitySig:s,extensions:t})}async function Og(r,e,t){try{let s=ol.decode(r),n=nt(s.identityKey);if(t?.equals(n)===!1)throw new Error(`Payload identity key ${n} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let o=Nv(e);if(!await n.verify(o,s.identitySig))throw new Error("Invalid payload signature");return s}catch(s){throw new ru(s.message)}}function Nv(r){let e=R("noise-libp2p-static-key:");return r instanceof Uint8Array?st([e,r],e.length+r.length):(r.prepend(e),r)}async function Bv(r,e){let{log:t,connection:s,crypto:n,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Mg(o,a.publicKey,l),h=new nl({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Ag(h.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await s.write(h.writeMessageA(No),e),t.trace("Stage 0 - Initiator finished sending first message."),Tg(h.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=h.readMessageB(await s.read(e));t.trace("Stage 1 - Initiator received the message."),Cg(h.re,t),Lv(h.rs,t),t.trace("Initiator going to check remote's signature...");let f=await Og(d,h.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await s.write(h.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[p,m]=h.ss.split();return Pg(p,m,t),{payload:f,encrypt:g=>p.encryptWithAd(No,g),decrypt:(g,y)=>m.decryptWithAd(No,g,y)}}async function Fv(r,e){let{log:t,connection:s,crypto:n,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Mg(o,a.publicKey,l),h=new nl({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Ag(h.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await s.read(e)),t.trace("Stage 0 - Responder received first message."),Cg(h.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await s.write(h.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Tg(h.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let d=h.readMessageC(await s.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let f=await Og(d,h.rs,c),[p,m]=h.ss.split();return Pg(p,m,t),{payload:f,encrypt:g=>m.encryptWithAd(No,g),decrypt:(g,y)=>p.decryptWithAd(No,g,y)}}at();var Kv=16;function Hv(r,e){return async function*(t){for await(let s of t)for(let n=0;n<s.length;n+=65519){let o=n+65519;o>s.length&&(o=s.length);let i;s instanceof Uint8Array?i=r.encrypt(s.subarray(n,o)):i=r.encrypt(s.sublist(n,o)),e?.encryptedPackets.increment(),yield new W(ea(i.byteLength),i)}}}function zv(r,e){return async function*(t){for await(let s of t)for(let n=0;n<s.length;n+=65535){let o=n+65535;if(o>s.length&&(o=s.length),o-Kv<n)throw new Error("Invalid chunk");let i=s.sublist(n,o),a=s.subarray(n,o-Kv);try{let c=r.decrypt(i,a);e?.decryptedPackets.increment(),yield c}catch(c){throw e?.decryptErrors.increment(),c}}}}var t1=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){let{staticNoiseKey:s,extensions:n,crypto:o,prologueBytes:i}=t,{metrics:a}=e;this.components=e;let c=o??Zd;this.crypto=Ov(c),this.extensions={webtransportCerthashes:[],...n},this.metrics=a?Rv(a):void 0,s?this.staticKey=c.generateX25519KeyPairFromSeed(s):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ee(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ye]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let s=is(e,{lengthEncoder:ea,lengthDecoder:sl,maxDataLength:65535}),n=await this.performHandshakeInitiator(s,this.components.privateKey,t?.remotePeer?.publicKey,t),o=await this.createSecureConnection(s,n);e.source=o.source,e.sink=o.sink;let i=nt(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:_s(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let s of e){let n=t.get(s);if(n!=null)return n}if(e.length)throw new su("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let s=is(e,{lengthEncoder:ea,lengthDecoder:sl,maxDataLength:65535}),n=await this.performHandshakeResponder(s,this.components.privateKey,t?.remotePeer?.publicKey,t),o=await this.createSecureConnection(s,n);e.source=o.source,e.sink=o.sink;let i=nt(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:_s(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,s,n){let o,i=n?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{o=await Bv({connection:e,privateKey:t,remoteIdentityKey:s,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){throw this.metrics?.xxHandshakeErrors.increment(),a}return o}async performHandshakeResponder(e,t,s,n){let o,i=n?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{o=await Fv({connection:e,privateKey:t,remoteIdentityKey:s,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){throw this.metrics?.xxHandshakeErrors.increment(),a}return o}async createSecureConnection(e,t){let[s,n]=ox(),o=e.unwrap();return await Qe(s,Hv(t,this.metrics),o,i=>Zt(i,{lengthDecoder:sl}),zv(t,this.metrics),s),n}};function qv(r={}){return e=>new t1(e,r)}X();function r1(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}at();X();var zr=class extends Error{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e),this.name="InvalidFrameError"}},sa=class extends Error{static name="UnrequestedPingError";constructor(e="Unrequested ping error"){super(e),this.name="UnrequestedPingError"}},na=class extends Error{static name="NotMatchingPingError";constructor(e="Unrequested ping error"){super(e),this.name="NotMatchingPingError"}},s1=class extends Error{static name="InvalidStateError";constructor(e="Invalid state"){super(e),this.name="InvalidStateError"}},n1=class extends Error{static name="StreamAlreadyExistsError";constructor(e="Strean already exists"){super(e),this.name="StreamAlreadyExistsError"}},o1=class extends Error{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e),this.name="DecodeInvalidVersionError"}},i1=class extends Error{static name="BothClientsError";constructor(e="Both clients"){super(e),this.name="BothClientsError"}},oa=class extends Error{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e),this.name="ReceiveWindowExceededError"}};var $v=new Set([zr.name,sa.name,na.name,n1.name,o1.name,i1.name,oa.name]),al=256*1024,Gv=16*1024*1024;var Vv={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:al,maxStreamWindowSize:Gv,maxMessageSize:64*1024};function Wv(r){if(r.keepAliveInterval<=0)throw new V("keep-alive interval must be positive");if(r.maxInboundStreams<0)throw new V("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams<0)throw new V("max outbound streams must be larger or equal 0");if(r.initialStreamWindowSize<al)throw new V("InitialStreamWindowSize must be larger or equal 256 kB");if(r.maxStreamWindowSize<r.initialStreamWindowSize)throw new V("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.maxStreamWindowSize>2**32-1)throw new V("MaxStreamWindowSize must be less than equal MAX_UINT32");if(r.maxMessageSize<1024)throw new V("MaxMessageSize must be greater than a kilobyte")}at();var Ve;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Ve||(Ve={}));var Ne;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(Ne||(Ne={}));var aoe=Object.values(Ne).filter(r=>typeof r!="string"),jv=0,Ir;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(Ir||(Ir={}));var wn=12;var Yv=2**24;function Ok(r){if(r[0]!==jv)throw new zr("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*Yv+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*Yv+(r[9]<<16)+(r[10]<<8)+r[11]}}var a1=class{source;buffer;frameInProgress;constructor(e){this.source=Rk(e),this.buffer=new W,this.frameInProgress=!1}async*emitFrames(){for await(let e of this.source)for(this.buffer.append(e);;){let t=this.readHeader();if(t===void 0)break;let{type:s,length:n}=t;s===Ve.Data?(this.frameInProgress=!0,yield{header:t,readData:this.readBytes.bind(this,n)}):yield{header:t}}}readHeader(){if(this.frameInProgress)throw new s1("decoding frame already in progress");if(this.buffer.length<wn)return;let e=Ok(this.buffer.subarray(0,wn));return this.buffer.consume(wn),e}async readBytes(e){if(this.buffer.length<e){for await(let s of this.source)if(this.buffer.append(s),this.buffer.length>=e)break}let t=this.buffer.sublist(0,e);return this.buffer.consume(e),this.frameInProgress=!1,t}};function Rk(r){if(r[Symbol.iterator]!==void 0){let e=r[Symbol.iterator]();return e.return=void 0,{[Symbol.iterator](){return e}}}else if(r[Symbol.asyncIterator]!==void 0){let e=r[Symbol.asyncIterator]();return e.return=void 0,{[Symbol.asyncIterator](){return e}}}else throw new Error("a source must be either an iterable or an async iterable")}function Rg(r){let e=new Uint8Array(wn);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}X();X();at();function Xv(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Zv(r,e){let t=r1(r).return?.();Xv(t)&&t.catch(s=>{e.error("could not cause iterator to return",s)})}var Lk=5e3;function Lg(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var c1=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=me(),this.closed=me(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??Lk,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=gt({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new iu(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let n=this.sendNewStream(t);Lg(n)&&await n}let s=()=>{Zv(e,this.log)};try{this.sinkController.signal.addEventListener("abort",s),this.log.trace("sink reading from source");for await(let n of e){n=n instanceof Uint8Array?new W(n):n;let o=this.sendData(n,t);Lg(o)&&(this.sendingData=me(),await o,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",s)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await Me(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await Me(this.sink([]),e.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Me(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Me(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();Lg(t)&&t.catch(s=>{this.log.error("error sending reset message",s)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new ou("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};function Nk(r){return r[Symbol.asyncIterator]!=null}function Qv(r){return r?.then!=null}function Bk(r,e){let t=0;if(Nk(r))return(async function*(){for await(let c of r){let l=e(c,t++);Qv(l)&&await l,yield c}})();let s=Eh(r),{value:n,done:o}=s.next();if(o===!0)return(function*(){})();if(typeof e(n,t++)?.then=="function")return(async function*(){yield n;for(let c of s){let l=e(c,t++);Qv(l)&&await l,yield c}})();let a=e;return(function*(){yield n;for(let c of s)a(c,t++),yield c})()}var l1=Bk;var _r;(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={}));var u1=class extends c1{name;state;config;_id;sendWindowCapacity;sendWindowCapacityUpdate;recvWindow;recvWindowCapacity;epochStart;getRTT;sendFrame;constructor(e){super({...e,onEnd:t=>{this.state=_r.Finished,e.onEnd?.(t)}}),this.config=e.config,this._id=parseInt(e.id,10),this.name=e.name,this.state=e.state,this.sendWindowCapacity=al,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame,this.source=l1(this.source,()=>{this.sendWindowUpdate()})}async sendNewStream(){}async sendData(e,t={}){for(e=e.sublist();e.byteLength!==0;){if(this.sendWindowCapacity===0&&(this.log?.trace("wait for send window capacity, status %s",this.status),await this.waitForSendWindowCapacity(t),this.status==="closed"||this.status==="aborted"||this.status==="reset")){this.log?.trace("%s while waiting for send window capacity",this.status);return}let s=Math.min(this.sendWindowCapacity,this.config.maxMessageSize-wn,e.length),n=this.getSendFlags();this.sendFrame({type:Ve.Data,flag:n,streamID:this._id,length:s},e.sublist(0,s)),this.sendWindowCapacity-=s,e.consume(s)}}async sendReset(){this.sendFrame({type:Ve.WindowUpdate,flag:Ne.RST,streamID:this._id,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|Ne.FIN;this.sendFrame({type:Ve.WindowUpdate,flag:e,streamID:this._id,length:0})}async sendCloseRead(){}async waitForSendWindowCapacity(e={}){if(this.sendWindowCapacity>0)return;let t,s,n=()=>{this.status==="open"||this.status==="closing"?s(new Bt("Stream aborted")):t()};e.signal?.addEventListener("abort",n);try{await new Promise((o,i)=>{this.sendWindowCapacityUpdate=()=>{o()},s=i,t=o})}finally{e.signal?.removeEventListener("abort",n)}}handleWindowUpdate(e){this.log?.trace("stream received window update id=%s",this._id),this.processFlags(e.flag);let t=this.sendWindowCapacity;this.sendWindowCapacity+=e.length,t===0&&e.length>0&&this.sendWindowCapacityUpdate?.()}async handleData(e,t){if(this.log?.trace("stream received data id=%s",this._id),this.processFlags(e.flag),this.recvWindowCapacity<e.length)throw new oa("Receive window exceeded");let s=await t();this.recvWindowCapacity-=e.length,this.sourcePush(s)}processFlags(e){(e&Ne.ACK)===Ne.ACK&&this.state===_r.SYNSent&&(this.state=_r.Established),(e&Ne.FIN)===Ne.FIN&&this.remoteCloseWrite(),(e&Ne.RST)===Ne.RST&&this.reset()}getSendFlags(){switch(this.state){case _r.Init:return this.state=_r.SYNSent,Ne.SYN;case _r.SYNReceived:return this.state=_r.Established,Ne.ACK;default:return 0}}sendWindowUpdate(){let e=this.getSendFlags(),t=Date.now(),s=this.getRTT();if(e===0&&s>-1&&t-this.epochStart<s*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.config.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let n=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Ve.WindowUpdate,flag:e,streamID:this._id,length:n})}};var Jv="/yamux/1.0.0",Fk=500,h1=class{protocol=Jv;_components;_init;constructor(e,t={}){this._components=e,this._init=t}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[Ye]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new Ng(this._components,{...this._init,...e})}},Ng=class{protocol=Jv;source;sink;config;log;logger;closeController;nextStreamID;_streams;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;onIncomingStream;onStreamEnd;constructor(e,t){this.client=t.direction==="outbound",this.config={...Vv,...t},this.logger=e.logger,this.log=this.logger.forComponent("libp2p:yamux"),Wv(this.config),this.closeController=new AbortController,Y(1/0,this.closeController.signal),this.onIncomingStream=t.onIncomingStream,this.onStreamEnd=t.onStreamEnd,this._streams=new Map,this.source=gt({onEnd:()=>{this.log?.trace("muxer source ended"),this._streams.forEach(s=>{s.destroy()})}}),this.sink=async s=>{let n=()=>{let a=r1(s);if(a.return!=null){let c=a.return();Uk(c)&&c.catch(l=>{this.log?.("could not cause sink source to return",l)})}},o,i;try{let a=new a1(s);try{this.closeController.signal.addEventListener("abort",n);for await(let c of a.emitFrames())await this.handleFrame(c.header,c.readData)}finally{this.closeController.signal.removeEventListener("abort",n)}o=Ir.NormalTermination}catch(a){$v.has(a.name)?(this.log?.error("protocol error in sink",a),o=Ir.ProtocolError):(this.log?.error("internal error in sink",a),o=Ir.InternalError),i=a}this.log?.trace("muxer sink ended"),i!=null?this.abort(i,o):await this.close({reason:o})},this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log?.trace("muxer created"),this.config.enableKeepAlive&&this.keepAliveLoop().catch(s=>this.log?.error("keepalive error: %s",s)),this.ping().catch(s=>this.log?.error("ping error: %s",s))}get streams(){return Array.from(this._streams.values())}newStream(e){if(this.remoteGoAway!==void 0)throw new rn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new rn("Muxer closed locally");let t=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new di("max outbound streams exceeded");this.log?.trace("new outgoing stream id=%s",t);let s=this._newStream(t,e,_r.Init,"outbound");return this._streams.set(t,s),this.numOutboundStreams++,s.sendWindowUpdate(),s}async ping(){if(this.remoteGoAway!==void 0)throw new rn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new rn("Muxer closed locally");if(this.activePing===void 0){let e=()=>{};this.activePing={id:this.nextPingID++,promise:new Promise((n,o)=>{let i=()=>{o(new rn("Muxer closed locally"))};this.closeController.signal.addEventListener("abort",i,{once:!0}),e=()=>{this.closeController.signal.removeEventListener("abort",i),n()}}),resolve:e};let t=Date.now();this.sendPing(this.activePing.id);try{await this.activePing.promise}finally{delete this.activePing}let s=Date.now();this.rtt=s-t}else await this.activePing.promise;return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.closeController.signal.aborted)return;let t=e?.reason??Ir.NormalTermination;if(this.log?.trace("muxer close reason=%s",t),e.signal==null){let s=AbortSignal.timeout(Fk);Y(1/0,s),e={...e,signal:s}}try{await Promise.all([...this._streams.values()].map(async s=>s.close(e))),this.sendGoAway(t),this._closeMuxer()}catch(s){this.abort(s)}}abort(e,t){if(!this.closeController.signal.aborted){t=t??Ir.InternalError,this.log?.error("muxer abort reason=%s error=%s",t,e);for(let s of this._streams.values())s.abort(e);this.sendGoAway(t),this._closeMuxer()}}isClosed(){return this.closeController.signal.aborted}_closeMuxer(){this.closeController.abort(),this.source.end()}_newStream(e,t,s,n){if(this._streams.get(e)!=null)throw new V("Stream already exists with that id");let o=new u1({id:e.toString(),name:t,state:s,direction:n,sendFrame:this.sendFrame.bind(this),onEnd:()=>{this.closeStream(e),this.onStreamEnd?.(o)},log:this.logger.forComponent(`libp2p:yamux:${n}:${e}`),config:this.config,getRTT:this.getRTT.bind(this)});return o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--,this._streams.delete(e)}async keepAliveLoop(){for(this.log?.trace("muxer keepalive enabled interval=%s",this.config.keepAliveInterval);;){let e;try{await Me(new Promise(t=>{e=setTimeout(t,this.config.keepAliveInterval)}),this.closeController.signal),this.ping().catch(t=>this.log?.error("ping error: %s",t))}catch{clearInterval(e);return}}}async handleFrame(e,t){let{streamID:s,type:n,length:o}=e;if(this.log?.trace("received frame %o",e),s===0)switch(n){case Ve.Ping:{this.handlePing(e);return}case Ve.GoAway:{this.handleGoAway(o);return}default:throw new zr("Invalid frame type")}else switch(e.type){case Ve.Data:case Ve.WindowUpdate:{await this.handleStreamMessage(e,t);return}default:throw new zr("Invalid frame type")}}handlePing(e){if(e.flag===Ne.SYN)this.log?.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,Ne.ACK);else if(e.flag===Ne.ACK)this.log?.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new zr("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new sa("ping not requested");if(this.activePing.id!==e)throw new na("ping doesn't match our id");this.activePing.resolve()}handleGoAway(e){this.log?.trace("received GoAway reason=%s",Ir[e]??"unknown"),this.remoteGoAway=e;for(let t of this._streams.values())t.reset();this._closeMuxer()}async handleStreamMessage(e,t){let{streamID:s,flag:n,type:o}=e;(n&Ne.SYN)===Ne.SYN&&this.incomingStream(s);let i=this._streams.get(s);if(i===void 0){if(o===Ve.Data){if(this.log?.("discarding data for stream id=%s",s),t===void 0)throw new Error("unreachable");await t()}else this.log?.trace("frame for missing stream id=%s",s);return}switch(o){case Ve.WindowUpdate:{i.handleWindowUpdate(e);return}case Ve.Data:{if(t===void 0)throw new Error("unreachable");await i.handleData(e,t);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new V("Both endpoints are clients");if(this._streams.has(e))return;if(this.log?.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Ve.WindowUpdate,flag:Ne.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.config.maxInboundStreams){this.log?.("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Ve.WindowUpdate,flag:Ne.RST,streamID:e,length:0});return}let t=this._newStream(e,void 0,_r.SYNReceived,"inbound");this.numInboundStreams++,this._streams.set(e,t),this.onIncomingStream?.(t)}sendFrame(e,t){if(this.log?.trace("sending frame %o",e),e.type===Ve.Data){if(t===void 0)throw new zr("Invalid frame");this.source.push(new W(Rg(e),t))}else this.source.push(Rg(e))}sendPing(e,t=Ne.SYN){t===Ne.SYN?this.log?.trace("sending ping request pingId=%s",e):this.log?.trace("sending ping response pingId=%s",e),this.sendFrame({type:Ve.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Ir.NormalTermination){this.log?.("sending GoAway reason=%s",Ir[e]),this.localGoAway=e,this.sendFrame({type:Ve.GoAway,flag:0,streamID:0,length:e})}};function Uk(r){return r!=null&&typeof r.then=="function"}function eE(r={}){return e=>new h1(e,r)}function qr(r,e){let t=is(r,e),s={read:async(n,o)=>{let i=await t.read(o);return n.decode(i)},write:async(n,o,i)=>{await t.write(o.encode(n),i)},writeV:async(n,o,i)=>{await t.writeV(n.map(a=>o.encode(a)),i)},pb:n=>({read:async o=>s.read(n,o),write:async(o,i)=>s.write(o,n,i),writeV:async(o,i)=>s.writeV(o,n,i),unwrap:()=>s}),unwrap:()=>t.unwrap()};return s}var tE="0.1.0";var rE="1.0.0";ws();var cl;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{if(n.lengthDelimited!==!1&&s.fork(),t.protocolVersion!=null&&(s.uint32(42),s.string(t.protocolVersion)),t.agentVersion!=null&&(s.uint32(50),s.string(t.agentVersion)),t.publicKey!=null&&(s.uint32(10),s.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)s.uint32(18),s.bytes(o);if(t.observedAddr!=null&&(s.uint32(34),s.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)s.uint32(26),s.string(o);t.signedPeerRecord!=null&&(s.uint32(66),s.bytes(t.signedPeerRecord)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={listenAddrs:[],protocols:[]},i=s==null?t.len:t.pos+s;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(n.limits?.listenAddrs!=null&&o.listenAddrs.length===n.limits.listenAddrs)throw new Se('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(n.limits?.protocols!=null&&o.protocols.length===n.limits.protocols)throw new Se('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=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(cl||(cl={}));lt();X();ce();be();var ds={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function sE(r){if(r!=null&&r.length>0)try{return q(r)}catch{}}function zk(r,e){return e??r.userAgent}async function nE(r,e,t,s,n){if(t("received identify from %p",s.remotePeer),n==null)throw new Ft("message was null or undefined");let o={};if(n.listenAddrs.length>0&&(o.addresses=n.listenAddrs.map(c=>({isCertified:!1,multiaddr:q(c)}))),n.protocols.length>0&&(o.protocols=n.protocols),n.publicKey!=null){let c=nt(n.publicKey);if(!_s(c).equals(s.remotePeer))throw new Ft("public key did not match remote PeerId");o.publicKey=c}let i;if(n.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",s.remotePeer);let c=n.signedPeerRecord,l=await nr.openAndCertify(c,or.DOMAIN),u=or.createFromProtobuf(l.payload),h=Jr(l.publicKey.toCID());if(!u.peerId.equals(h))throw new Ft("signing key does not match PeerId in the PeerRecord");if(!s.remotePeer.equals(u.peerId))throw new Ft("signing key does not match remote PeerId");let d;try{d=await r.get(u.peerId)}catch(f){if(f.name!=="NotFoundError")throw f}if(d!=null&&(o.metadata=d.metadata,d.peerRecordEnvelope!=null)){let f=nr.createFromProtobuf(d.peerRecordEnvelope),p=or.createFromProtobuf(f.payload);p.seqNumber>=u.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",p.seqNumber,u.seqNumber),u=p,c=d.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",s.remotePeer);if(t.trace("patching %p with",s.remotePeer,o),await r.patch(s.remotePeer,o),n.agentVersion!=null||n.protocolVersion!=null){let c={};n.agentVersion!=null&&(c.AgentVersion=R(n.agentVersion)),n.protocolVersion!=null&&(c.ProtocolVersion=R(n.protocolVersion)),t.trace("merging %p metadata",s.remotePeer,c),await r.merge(s.remotePeer,{metadata:c})}let a={peerId:s.remotePeer,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(c=>q(c)),observedAddr:n.observedAddr==null?void 0:q(n.observedAddr),protocols:n.protocols,signedPeerRecord:i,connection:s};return e.safeDispatchEvent("peer:identify",{detail:a}),a}var d1=class{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??ds.timeout,this.maxInboundStreams=t.maxInboundStreams??ds.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??ds.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??ds.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??ds.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??ds.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??ds.protocolPrefix}/${tE}`,agentVersion:zk(e.nodeInfo,t.agentVersion)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:R(this.host.agentVersion),ProtocolVersion:R(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,e=>{this.handleProtocol(e).catch(t=>{this.log.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}};lt();X();ce();function oE(r){try{for(let{code:e,value:t}of r.getComponents())if(t!=null&&e===41)return t4("2000::/3",t)}catch{}return!1}Oe();var f1=class extends d1{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??ds.protocolPrefix}/${"id"}/${rE}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??ds.runOnConnectionOpen)&&e.events.addEventListener("connection:open",s=>{let n=s.detail;this.identify(n).catch(o=>{o.name!==Fn.name&&this.log.error("error during identify trigged by connection:open",o)})})}[Ye]=["@libp2p/identify"];async _identify(e,t={}){let s;if(t.signal==null){let n=AbortSignal.timeout(this.timeout);Y(1/0,n),t={...t,signal:n}}try{s=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});let o=await qr(s,{maxDataLength:this.maxMessageSize}).pb(cl).read(t);return await s.close(t),o}catch(n){throw s?.abort(n),n}}async identify(e,t={}){let s=await this._identify(e,t),{publicKey:n,protocols:o,observedAddr:i}=s;if(n==null)throw new Ft("Public key was missing from identify message");let a=nt(n),c=Jr(a.toCID()),l=e.log.newScope("identify");if(!e.remotePeer.equals(c))throw new Ft("Identified peer does not match the expected peer");if(this.peerId.equals(c))throw new Ft("Identified peer is our own peer id?");return this.maybeAddObservedAddress(i,l),l("completed for peer %p and protocols %o",c,o),nE(this.peerStore,this.events,l,e,s)}maybeAddObservedAddress(e,t){let s=sE(e);if(s==null)return;if(t.trace("our observed address was %a",s),Rs(s)){this.log.trace("our observed address was private");return}let n=s.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!oE(s)){t.trace("our observed address was IPv6 but not a global unicast address");return}Ms.exactMatch(s)||(t.trace("storing the observed address"),this.addressManager.addObservedAddr(s))}async handleProtocol(e){let{connection:t,stream:s}=e,n=t.log.newScope("identify"),o=AbortSignal.timeout(this.timeout);Y(1/0,o);try{let i=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(h=>h.decapsulateCode(ki("p2p").code)),c=i.peerRecordEnvelope;if(a.length>0&&c==null){let h=new or({peerId:this.peerId,multiaddrs:a});c=(await nr.seal(h,this.privateKey)).marshal().subarray()}let l=t.remoteAddr.bytes;iw.matches(t.remoteAddr)||(l=void 0),await qr(s).pb(cl).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:He(this.privateKey.publicKey),listenAddrs:a.map(h=>h.bytes),signedPeerRecord:c,observedAddr:l,protocols:i.protocols},{signal:o}),await s.close({signal:o})}catch(i){n.error("could not respond to identify request",i),s.abort(i)}}};function iE(r={}){return e=>new f1(e,r)}X();Oe();Gt();var aE="1.0.0",cE="ping",lE="ipfs";var p1=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??lE}/${cE}/${aE}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[Ye]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{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}handleMessage(e){let t=e.connection.log.newScope("ping");t.trace("ping from %p",e.connection.remotePeer);let{stream:s}=e,n=Date.now(),o=_o(s),i=!1;Promise.resolve().then(async()=>{for(;;){let a=AbortSignal.timeout(this.timeout);Y(1/0,a),a.addEventListener("abort",()=>{s?.abort(new Qr("ping timeout"))});let c=await o.read({bytes:32,signal:a});await o.write(c,{signal:a}),i=!0}}).catch(a=>{i&&a.name==="UnexpectedEOFError"&&s.readStatus!=="ready"||(t.error("ping from %p failed with error - %e",e.connection.remotePeer,a),s?.abort(a))}).finally(()=>{let a=Date.now()-n;t("ping from %p complete in %dms",e.connection.remotePeer,a);let c=AbortSignal.timeout(this.timeout);Y(1/0,c),s.close({signal:c}).catch(l=>{t.error("error closing ping stream from %p - %e",e.connection.remotePeer,l),s?.abort(l)})})}async ping(e,t={}){let s=Date.now(),n=Zr(32),o=await this.components.connectionManager.openConnection(e,t),i=o.log.newScope("ping"),a;if(t.signal==null){let c=AbortSignal.timeout(this.timeout);t={...t,signal:c}}try{a=await o.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});let c=_o(a),[,l]=await Promise.all([c.write(n,t),c.read({...t,bytes:32})]),u=Date.now()-s;if(!de(n,l.subarray()))throw new lu(`Received wrong ping ack after ${u}ms`);return i("ping %p complete in %dms",o.remotePeer,u),u}catch(c){throw i.error("error while pinging %p",o.remotePeer,c),a?.abort(c),c}finally{a!=null&&await a.close(t)}}};function uE(r={}){return e=>new p1(e,r)}X();ce();Ar();at();rt();function m1(r){return r[Symbol.asyncIterator]!=null}var g1=r=>{let e=Ue(r),t=tt(e);return hr(r,t),g1.bytes=e,t};g1.bytes=0;function ia(r,e){e=e??{};let t=e.lengthEncoder??g1;function*s(n){let o=t(n.byteLength);o instanceof Uint8Array?yield o:yield*o,n instanceof Uint8Array?yield n:yield*n}return m1(r)?(async function*(){for await(let n of r)yield*s(n)})():(function*(){for(let n of r)yield*s(n)})()}ia.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??g1;return new W(t(r.byteLength),r)};Ar();at();var y1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},b1=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},w1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},ll=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Wk=8,jk=1024*1024*4,Bo;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Bo||(Bo={}));var Fg=r=>{let e=ms(r);return Fg.bytes=Ue(e),e};Fg.bytes=0;function ul(r,e){let t=new W,s=Bo.LENGTH,n=-1,o=e?.lengthDecoder??Fg,i=e?.maxLengthLength??Wk,a=e?.maxDataLength??jk;function*c(){for(;t.byteLength>0;){if(s===Bo.LENGTH)try{if(n=o(t),n<0)throw new y1("Invalid message length");if(n>a)throw new b1("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(n),s=Bo.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new w1("Message length length too long");break}throw l}if(s===Bo.DATA){if(t.byteLength<n)break;let l=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(l),yield l,s=Bo.LENGTH}}}return m1(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ll("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new ll("Unexpected end of input")})()}ul.fromReader=(r,e)=>{let t=1,s=(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 ul(s,{...e??{},onLength:o=>{t=o}})};Vt();var Ug="/floodsub/1.0.0",Kg="/meshsub/1.0.0",hE="/meshsub/1.1.0",x1="/meshsub/1.2.0";var dE="ERR_TOPIC_VALIDATOR_REJECT",fE="ERR_TOPIC_VALIDATOR_IGNORE";var pE={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};ws();var Vs;(function(r){let e;(function(h){let d;h.codec=()=>(d==null&&(d=se((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.subscribe!=null&&(p.uint32(8),p.bool(f.subscribe)),f.topic!=null&&(p.uint32(18),p.string(f.topic)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={},y=p==null?f.len:f.pos+p;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})),d),h.encode=f=>re(f,h.codec()),h.decode=(f,p)=>te(f,h.codec(),p)})(e=r.SubOpts||(r.SubOpts={}));let t;(function(h){let d;h.codec=()=>(d==null&&(d=se((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.from!=null&&(p.uint32(10),p.bytes(f.from)),f.data!=null&&(p.uint32(18),p.bytes(f.data)),f.seqno!=null&&(p.uint32(26),p.bytes(f.seqno)),f.topic!=null&&f.topic!==""&&(p.uint32(34),p.string(f.topic)),f.signature!=null&&(p.uint32(42),p.bytes(f.signature)),f.key!=null&&(p.uint32(50),p.bytes(f.key)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={topic:""},y=p==null?f.len:f.pos+p;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})),d),h.encode=f=>re(f,h.codec()),h.decode=(f,p)=>te(f,h.codec(),p)})(t=r.Message||(r.Message={}));let s;(function(h){let d;h.codec=()=>(d==null&&(d=se((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.ihave!=null)for(let g of f.ihave)p.uint32(10),r.ControlIHave.codec().encode(g,p);if(f.iwant!=null)for(let g of f.iwant)p.uint32(18),r.ControlIWant.codec().encode(g,p);if(f.graft!=null)for(let g of f.graft)p.uint32(26),r.ControlGraft.codec().encode(g,p);if(f.prune!=null)for(let g of f.prune)p.uint32(34),r.ControlPrune.codec().encode(g,p);if(f.idontwant!=null)for(let g of f.idontwant)p.uint32(42),r.ControlIDontWant.codec().encode(g,p);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},y=p==null?f.len:f.pos+p;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 Se('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 Se('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 Se('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 Se('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 Se('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})),d),h.encode=f=>re(f,h.codec()),h.decode=(f,p)=>te(f,h.codec(),p)})(s=r.ControlMessage||(r.ControlMessage={}));let n;(function(h){let d;h.codec=()=>(d==null&&(d=se((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.topicID!=null&&(p.uint32(10),p.string(f.topicID)),f.messageIDs!=null)for(let g of f.messageIDs)p.uint32(18),p.bytes(g);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={messageIDs:[]},y=p==null?f.len:f.pos+p;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 Se('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),d),h.encode=f=>re(f,h.codec()),h.decode=(f,p)=>te(f,h.codec(),p)})(n=r.ControlIHave||(r.ControlIHave={}));let o;(function(h){let d;h.codec=()=>(d==null&&(d=se((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.messageIDs!=null)for(let g of f.messageIDs)p.uint32(10),p.bytes(g);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={messageIDs:[]},y=p==null?f.len:f.pos+p;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 Se('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),d),h.encode=f=>re(f,h.codec()),h.decode=(f,p)=>te(f,h.codec(),p)})(o=r.ControlIWant||(r.ControlIWant={}));let i;(function(h){let d;h.codec=()=>(d==null&&(d=se((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.topicID!=null&&(p.uint32(10),p.string(f.topicID)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={},y=p==null?f.len:f.pos+p;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})),d),h.encode=f=>re(f,h.codec()),h.decode=(f,p)=>te(f,h.codec(),p)})(i=r.ControlGraft||(r.ControlGraft={}));let a;(function(h){let d;h.codec=()=>(d==null&&(d=se((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.topicID!=null&&(p.uint32(10),p.string(f.topicID)),f.peers!=null)for(let g of f.peers)p.uint32(18),r.PeerInfo.codec().encode(g,p);f.backoff!=null&&(p.uint32(24),p.uint64Number(f.backoff)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={peers:[]},y=p==null?f.len:f.pos+p;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 Se('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})),d),h.encode=f=>re(f,h.codec()),h.decode=(f,p)=>te(f,h.codec(),p)})(a=r.ControlPrune||(r.ControlPrune={}));let c;(function(h){let d;h.codec=()=>(d==null&&(d=se((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.peerID!=null&&(p.uint32(10),p.bytes(f.peerID)),f.signedPeerRecord!=null&&(p.uint32(18),p.bytes(f.signedPeerRecord)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={},y=p==null?f.len:f.pos+p;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})),d),h.encode=f=>re(f,h.codec()),h.decode=(f,p)=>te(f,h.codec(),p)})(c=r.PeerInfo||(r.PeerInfo={}));let l;(function(h){let d;h.codec=()=>(d==null&&(d=se((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.messageIDs!=null)for(let g of f.messageIDs)p.uint32(10),p.bytes(g);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={messageIDs:[]},y=p==null?f.len:f.pos+p;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 Se('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(b&7);break}}}return g})),d),h.encode=f=>re(f,h.codec()),h.decode=(f,p)=>te(f,h.codec(),p)})(l=r.ControlIDontWant||(r.ControlIDontWant={}));let u;r.codec=()=>(u==null&&(u=se((h,d,f={})=>{if(f.lengthDelimited!==!1&&d.fork(),h.subscriptions!=null)for(let p of h.subscriptions)d.uint32(10),r.SubOpts.codec().encode(p,d);if(h.messages!=null)for(let p of h.messages)d.uint32(18),r.Message.codec().encode(p,d);h.control!=null&&(d.uint32(26),r.ControlMessage.codec().encode(h.control,d)),f.lengthDelimited!==!1&&d.ldelim()},(h,d,f={})=>{let p={subscriptions:[],messages:[]},m=d==null?h.len:h.pos+d;for(;h.pos<m;){let g=h.uint32();switch(g>>>3){case 1:{if(f.limits?.subscriptions!=null&&p.subscriptions.length===f.limits.subscriptions)throw new Se('Decode error - map field "subscriptions" had too many elements');p.subscriptions.push(r.SubOpts.codec().decode(h,h.uint32(),{limits:f.limits?.subscriptions$}));break}case 2:{if(f.limits?.messages!=null&&p.messages.length===f.limits.messages)throw new Se('Decode error - map field "messages" had too many elements');p.messages.push(r.Message.codec().decode(h,h.uint32(),{limits:f.limits?.messages$}));break}case 3:{p.control=r.ControlMessage.codec().decode(h,h.uint32(),{limits:f.limits?.control});break}default:{h.skipType(g&7);break}}}return p})),u),r.encode=h=>re(h,r.codec()),r.decode=(h,d)=>te(h,r.codec(),d)})(Vs||(Vs={}));var v1=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,s){this.gossip=e,this.msgIdToStrFn=s;for(let n=0;n<t;n++)this.history[n]=[]}get size(){return this.msgs.size}put(e,t,s=!1){let{msgIdStr:n}=e;return this.msgs.has(n)?!1:(this.msgs.set(n,{message:t,validated:s,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),s||this.notValidatedCount++,!0)}observeDuplicate(e,t){let s=this.msgs.get(e);s!=null&&!s.validated&&s.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let s=this.msgs.get(e);if(s==null)return null;let n=(s.iwantCounts.get(t)??0)+1;return s.iwantCounts.set(t,n),{msg:s.message,count:n}}getGossipIDs(e){let t=new Map;for(let s=0;s<this.gossip;s++)this.history[s].forEach(n=>{if((this.msgs.get(n.msgIdStr)?.validated??!1)&&e.has(n.topic)){let i=t.get(n.topic);i==null&&(i=[],t.set(n.topic,i)),i.push(n.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:s,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:s,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach(t=>{let s=this.msgs.get(t.msgIdStr);s!=null&&(this.msgs.delete(t.msgIdStr),s.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)}};X();X();var mE;(function(r){r.StrictSign="StrictSign",r.StrictNoSign="StrictNoSign"})(mE||(mE={}));var xn;(function(r){r[r.Signing=0]="Signing",r[r.Anonymous=1]="Anonymous"})(xn||(xn={}));var zt;(function(r){r.Error="error",r.Ignore="ignore",r.Reject="reject",r.Blacklisted="blacklisted"})(zt||(zt={}));var Mt;(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"})(Mt||(Mt={}));var Ot;(function(r){r.duplicate="duplicate",r.invalid="invalid",r.valid="valid"})(Ot||(Ot={}));function Hg(r){switch(r){case Nt.Ignore:return zt.Ignore;case Nt.Reject:return zt.Reject;default:throw new Error("Unreachable")}}var gE;(function(r){r.forward="forward",r.publish="publish"})(gE||(gE={}));var qt;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(qt||(qt={}));var $r;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Excess="excess"})($r||($r={}));var ca;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(ca||(ca={}));var la;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(la||(la={}));var aa;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(aa||(aa={}));function yE(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(s){return this.topicStrToLabel.get(s)??s},onJoin(s){this.topicSubscriptionStatus.set({topicStr:s},1),this.meshPeerCounts.set({topicStr:s},0)},onLeave(s){this.topicSubscriptionStatus.set({topicStr:s},0),this.meshPeerCounts.set({topicStr:s},0)},onAddToMesh(s,n,o){let i=this.toTopic(s);switch(n){case qt.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case qt.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case qt.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case qt.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case qt.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case qt.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:i},o);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:i},o);break}},onRemoveFromMesh(s,n,o){let i=this.toTopic(s);switch(n){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(s,n,o){if(this.asyncValidationMcacheHit.inc({hit:s!=null?"hit":"miss"}),s!=null){let i=this.toTopic(s.message.topic);switch(n){case Nt.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case Nt.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case Nt.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(s){this.scoringPenalties.inc({penalty:s},1)},onIhaveRcv(s,n,o){let i=this.toTopic(s);this.ihaveRcvMsgids.inc({topic:i},n),this.ihaveRcvNotSeenMsgids.inc({topic:i},o)},onIwantRcv(s,n){for(let[o,i]of s){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},i)}this.iwantRcvDonthaveMsgids.inc(n)},onIdontwantRcv(s,n){this.idontwantRcvMsgids.inc(s),this.idontwantRcvDonthaveMsgids.inc(n)},onForwardMsg(s,n){let o=this.toTopic(s);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},n)},onPublishMsg(s,n,o,i,a){let c=this.toTopic(s);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},o*i),this.msgPublishPeersByTopic.inc({topic:c},o),this.directPeersPublishedTotal.inc({topic:c},n.direct),this.floodsubPeersPublishedTotal.inc({topic:c},n.floodsub),this.meshPeersPublishedTotal.inc({topic:c},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},n.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(s){let n=this.toTopic(s);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(s){let n=this.toTopic(s);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(s,n){let o=this.toTopic(s);switch(n){case Ot.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case Ot.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case Ot.valid:this.prevalidationValidTotal.inc({topic:o});break;default:this.prevalidationUnknownTotal.inc({topic:o});break}},onMsgRecvInvalid(s,n){let o=this.toTopic(s),i=n.reason===zt.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:i},1),this.msgReceivedInvalidByTopic.inc({topic:o},1)},onDuplicateMsgDelivery(s,n,o){let i=this.toTopic(s);this.duplicateMsgDeliveryDelay.observe({topic:i},n/1e3),o&&this.duplicateMsgLateDelivery.inc({topic:i},1)},onPublishDuplicateMsg(s){let n=this.toTopic(s);this.duplicateMsgIgnored.inc({topic:n},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(s,n){this.rpcRecvBytes.inc(n),this.rpcRecvCount.inc(1),s.subscriptions!=null&&this.rpcRecvSubscription.inc(s.subscriptions.length),s.messages!=null&&this.rpcRecvMessage.inc(s.messages.length),s.control!=null&&(this.rpcRecvControl.inc(1),s.control.ihave!=null&&this.rpcRecvIHave.inc(s.control.ihave.length),s.control.iwant!=null&&this.rpcRecvIWant.inc(s.control.iwant.length),s.control.graft!=null&&this.rpcRecvGraft.inc(s.control.graft.length),s.control.prune!=null&&this.rpcRecvPrune.inc(s.control.prune.length))},onRpcSent(s,n){if(this.rpcSentBytes.inc(n),this.rpcSentCount.inc(1),s.subscriptions!=null&&this.rpcSentSubscription.inc(s.subscriptions.length),s.messages!=null&&this.rpcSentMessage.inc(s.messages.length),s.control!=null){let o=s.control.ihave?.length??0,i=s.control.iwant?.length??0,a=s.control.graft?.length??0,c=s.control.prune?.length??0,l=s.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(s,n){let o=0,i=0,a=0,c=0;for(let l of s)l>=n.graylistThreshold&&o++,l>=n.publishThreshold&&i++,l>=n.gossipThreshold&&a++,l>=0&&c++;this.peersByScoreThreshold.set({threshold:aa.graylist},o),this.peersByScoreThreshold.set({threshold:aa.publish},i),this.peersByScoreThreshold.set({threshold:aa.gossip},a),this.peersByScoreThreshold.set({threshold:aa.mesh},c),this.score.set(s)},registerScoreWeights(s){for(let[n,o]of s.byTopic)this.scoreWeights.set({topic:n,p:"p1"},o.p1w),this.scoreWeights.set({topic:n,p:"p2"},o.p2w),this.scoreWeights.set({topic:n,p:"p3"},o.p3w),this.scoreWeights.set({topic:n,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:n,p:"p4"},o.p4w);this.scoreWeights.set({p:"p5"},s.p5w),this.scoreWeights.set({p:"p6"},s.p6w),this.scoreWeights.set({p:"p7"},s.p7w)},registerScorePerMesh(s,n){let o=new Map;s.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(n.get(l)??0)}),this.scorePerMesh.set({topic:i},c)}}}}var we=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var Xk={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},Zk={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 bE(r={}){return{...Xk,...r,topics:r.topics!=null?Object.entries(r.topics).reduce((e,[t,s])=>(e[t]=Qk(s),e),{}):{}}}function Qk(r={}){return{...Zk,...r}}function wE(r){for(let[e,t]of Object.entries(r.topics))try{Jk(t)}catch(s){throw new we(`invalid score parameters for topic ${e}: ${s.message}`)}if(r.topicScoreCap<0)throw new we("invalid topic score cap; must be positive (or 0 for no cap)");if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new we("missing application specific score function");if(r.IPColocationFactorWeight>0)throw new we("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new we("invalid IPColocationFactorThreshold; must be at least 1");if(r.behaviourPenaltyWeight>0)throw new we("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new we("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(r.decayInterval<1e3)throw new we("invalid DecayInterval; must be at least 1s");if(r.decayToZero<=0||r.decayToZero>=1)throw new we("invalid DecayToZero; must be between 0 and 1")}function Jk(r){if(r.topicWeight<0)throw new we("invalid topic weight; must be >= 0");if(r.timeInMeshQuantum===0)throw new we("invalid TimeInMeshQuantum; must be non zero");if(r.timeInMeshWeight<0)throw new we("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new we("invalid TimeInMeshQuantum; must be positive");if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new we("invalid TimeInMeshCap; must be positive");if(r.firstMessageDeliveriesWeight<0)throw new we("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new we("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new we("invalid FirstMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight>0)throw new we("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new we("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new we("invalid MeshMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new we("invalid MeshMessageDeliveriesThreshold; must be positive");if(r.meshMessageDeliveriesWindow<0)throw new we("invalid MeshMessageDeliveriesWindow; must be non-negative");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new we("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(r.meshFailurePenaltyWeight>0)throw new we("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new we("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(r.invalidMessageDeliveriesWeight>0)throw new we("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new we("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var eD={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function xE(r={}){return{...eD,...r}}function S1(r,e,t=()=>!0){let s=new Set;if(e<=0)return s;for(let n of r){if(s.size>=e)break;t(n)&&(s.add(n),r.delete(n))}return s}function vE(r,e){return S1(r,e,()=>!0)}var E1=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 EE(r,e,t,s){let n=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,p=f*f;l+=p*c.meshMessageDeliveriesWeight}let h=a.meshFailurePenalty;l+=h*c.meshFailurePenaltyWeight;let d=a.invalidMessageDeliveries*a.invalidMessageDeliveries;l+=d*c.invalidMessageDeliveriesWeight,n+=l*c.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let o=t.appSpecificScore(r);if(n+=o*t.appSpecificWeight,e.knownIPs.forEach(i=>{if(t.IPColocationFactorWhitelist.has(i))return;let a=s.get(i),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let l=c-t.IPColocationFactorThreshold,u=l*l;n+=u*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let i=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=i*i;n+=a*t.behaviourPenaltyWeight}return n}var _E=xe(IE(),1);var $t;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})($t||($t={}));var I1=class{records;queue;constructor(){this.records=new Map,this.queue=new _E.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:$t.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let s={msgId:e,expire:Date.now()+12e4};return this.queue.push(s),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 _1=class{params;metrics;peerStats=new Map;peerIPs=new E1(()=>new Set);scoreCache=new Map;deliveryRecords=new I1;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,s,n){this.params=e,this.metrics=t,wE(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??EE,this.log=s.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((s,n)=>{if(!s.connected){e>s.expire&&(this.removeIPsForPeer(n,s.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n));return}Object.entries(s.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)))}),s.behaviourPenalty*=this.params.behaviourPenaltyDecay,s.behaviourPenalty<t&&(s.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let s=Date.now(),n=this.scoreCache.get(e);if(n!=null&&n.cacheUntil>s)return n.score;this.metrics?.scoreFnRuns.inc();let o=this.computeScore(e,t,this.params,this.peerIPs),i=s+this.scoreCacheValidityMs;return n!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(o-n.score)),n.score=o,n.cacheUntil=i):this.scoreCache.set(e,{score:o,cacheUntil:i}),o}addPenalty(e,t,s){let n=this.peerStats.get(e);n!=null&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(s))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let s=this.peerStats.get(e);s?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let s=this.peerStats.get(e);s?.knownIPs.delete(t);let n=this.peerIPs.get(t);n!=null&&(n.delete(e),n.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(([s,n])=>{n.firstMessageDeliveries=0;let o=this.params.topics[s].meshMessageDeliveriesThreshold;if(n.inMesh&&n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<o){let i=o-n.meshMessageDeliveries;n.meshFailurePenalty+=i*i}n.inMesh=!1,n.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);n!=null&&(n.inMesh=!0,n.graftTime=Date.now(),n.meshTime=0,n.meshMessageDeliveriesActive=!1)}}prune(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);if(n!=null){let o=this.params.topics[t].meshMessageDeliveriesThreshold;if(n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<o){let i=o-n.meshMessageDeliveries;n.meshFailurePenalty+=i*i}n.meshMessageDeliveriesActive=!1,n.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,s){this.markFirstMessageDelivery(e,s);let n=this.deliveryRecords.ensureRecord(t),o=Date.now();if(n.status!==$t.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-n.firstSeenTsMs,$t[n.status]);return}n.status=$t.valid,n.validated=o,n.peers.forEach(i=>{i!==e.toString()&&this.markDuplicateMessageDelivery(i,s)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,s,n){switch(n){case zt.Error:this.markInvalidMessageDelivery(e,s);return;case zt.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==$t.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,$t[o.status]);return}if(n===zt.Ignore){o.status=$t.ignored,o.peers.clear();return}o.status=$t.invalid,this.markInvalidMessageDelivery(e,s),o.peers.forEach(i=>{this.markInvalidMessageDelivery(i,s)}),o.peers.clear()}duplicateMessage(e,t,s){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case $t.unknown:n.peers.add(e);break;case $t.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,s,n.validated);break;case $t.invalid:this.markInvalidMessageDelivery(e,s);break;case $t.ignored:break}}markInvalidMessageDelivery(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);n!=null&&(n.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);if(n!=null){let o=this.params.topics[t].firstMessageDeliveriesCap;n.firstMessageDeliveries=Math.min(o,n.firstMessageDeliveries+1),n.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,n.meshMessageDeliveries=Math.min(o,n.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,s){let n=this.peerStats.get(e);if(n!=null){let o=s!==void 0?Date.now():0,i=this.getPtopicStats(n,t);if(i!=null&&i.inMesh){let a=this.params.topics[t];if(s!==void 0){let l=o-s,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 s of t){let n=this.peerIPs.get(s);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(s))}}getPtopicStats(e,t){let s=e.topics[t];return s!==void 0?s:this.params.topics[t]!==void 0?(s={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=s,s):null}};function tD(r,e,t,s,n){let o=0,i=new Map;if(Object.entries(e.topics).forEach(([d,f])=>{let p=n.get(d)??"unknown",m=t.topics[d];if(m===void 0)return;let g=i.get(p);g==null&&(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(p,g));let y=0,b=0,w=0,x=0,E=0;if(f.inMesh){let v=Math.max(f.meshTime/m.timeInMeshQuantum,m.timeInMeshCap);y+=v*m.timeInMeshWeight}let P=f.firstMessageDeliveries;if(P>m.firstMessageDeliveriesCap&&(P=m.firstMessageDeliveriesCap),b+=P*m.firstMessageDeliveriesWeight,f.meshMessageDeliveriesActive&&f.meshMessageDeliveries<m.meshMessageDeliveriesThreshold){let v=m.meshMessageDeliveriesThreshold-f.meshMessageDeliveries,M=v*v;w+=M*m.meshMessageDeliveriesWeight}let C=f.meshFailurePenalty;x+=C*m.meshFailurePenaltyWeight;let D=f.invalidMessageDeliveries*f.invalidMessageDeliveries;E+=D*m.invalidMessageDeliveriesWeight,o+=(y+b+w+x+E)*m.topicWeight,g.p1w+=y,g.p2w+=b,g.p3w+=w,g.p3bw+=x,g.p4w+=E}),t.topicScoreCap>0&&o>t.topicScoreCap){o=t.topicScoreCap;let d=t.topicScoreCap/o;for(let f of i.values())f.p1w*=d,f.p2w*=d,f.p3w*=d,f.p3bw*=d,f.p4w*=d}let a=0,c=0,l=0,u=t.appSpecificScore(r);a+=u*t.appSpecificWeight,e.knownIPs.forEach(d=>{if(t.IPColocationFactorWhitelist.has(d))return;let f=s.get(d),p=f!=null?f.size:0;if(p>t.IPColocationFactorThreshold){let m=p-t.IPColocationFactorThreshold,g=m*m;c+=g*t.IPColocationFactorWeight}});let h=e.behaviourPenalty*e.behaviourPenalty;return l+=h*t.behaviourPenaltyWeight,o+=a+c+l,{byTopic:i,p5w:a,p6w:c,p7w:l,score:o}}function AE(r,e,t,s,n){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let i of r){let a=e.get(i);if(a!=null){let c=tD(i,a,t,s,n);for(let[l,u]of c.byTopic){let h=o.byTopic.get(l);h==null&&(h={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(l,h)),h.p1w.push(u.p1w),h.p2w.push(u.p2w),h.p3w.push(u.p3w),h.p3bw.push(u.p3bw),h.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 A1=class{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,s){this.rawStream=e,this.pushable=gt(),this.closeController=new AbortController,this.maxBufferSize=s.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(n=>{e.abort(n)})}),Qe(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(ia.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()}},T1=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(s=>{e.abort(s)})}),this.source=Qe(this.rawStream,s=>ul(s,t))}async close(){this.closeController.abort()}};var C1=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,s){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=s,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let s=Math.floor(Math.random()*t.length),n=t[s],o=this.msgIdToStrFn(n),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,s=0;return this.promises.forEach((n,o)=>{n.forEach((i,a)=>{i<e&&(t.set(a,(t.get(a)??0)+1),n.delete(a),s++)}),n.size===0&&this.promises.delete(o)}),this.metrics?.iwantPromiseBroken.inc(s),t}deliverMessage(e,t=!1){this.trackMessage(e);let s=this.promises.get(e);s!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(s.size)))}rejectMessage(e,t){switch(this.trackMessage(e),t){case zt.Error:return;default:break}this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[s,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(s),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))}}};lt();X();ce();Vt();Vr();be();Pe();var TE=R("libp2p-pubsub:");async function CE(r,e,t,s){switch(r.type){case xn.Signing:{let n={from:r.author.toMultihash().bytes,data:s,seqno:Zr(8),topic:e,signature:void 0,key:void 0},o=st([TE,Vs.Message.encode(n)]);n.signature=await r.privateKey.sign(o),n.key=r.key;let i={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${U(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:nt(n.key)};return{raw:n,msg:i}}case xn.Anonymous:return{raw:{from:void 0,data:s,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 PE(r,e){switch(r){case li:return e.signature!=null?{valid:!1,error:Mt.SignaturePresent}:e.seqno!=null?{valid:!1,error:Mt.SeqnoPresent}:e.from!=null?{valid:!1,error:Mt.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case Ln:{if(e.seqno==null)return{valid:!1,error:Mt.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:Mt.InvalidSeqno};if(e.signature==null)return{valid:!1,error:Mt.InvalidSignature};if(e.from==null)return{valid:!1,error:Mt.InvalidPeerId};let t;try{t=Ut(ct(e.from))}catch{return{valid:!1,error:Mt.InvalidPeerId}}let s;if(e.key!=null){if(s=nt(e.key),t.publicKey!==void 0&&!s.equals(t.publicKey))return{valid:!1,error:Mt.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:Mt.InvalidPeerId};s=t.publicKey}let n={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=st([TE,Vs.Message.encode(n)]);return await s.verify(o,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${U(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:s}}:{valid:!1,error:Mt.InvalidSignature}}default:throw new Error("Unreachable")}}function Gr(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 zg(r){return r.control===void 0&&(r.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),r}function fs(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 s=e(),n=r[t];r[t]=r[s],r[s]=n}return r}Pe();function kE(r){return U(r,"base64")}lt();X();function DE(r,e,t){switch(r){case Ln:return{type:xn.Signing,author:e,key:He(t.publicKey),privateKey:t};case li:return{type:xn.Anonymous};default:throw new Error(`Unknown signature policy "${r}"`)}}lt();Vt();jr();be();Pe();var ME=(r,e)=>{let t=R(e.toString(16).padStart(16,"0"),"base16"),s=He(r),n=new Uint8Array(s.byteLength+t.length);return n.set(s,0),n.set(t,s.byteLength),n};jr();function OE(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return ME(r.from.publicKey??r.key,r.sequenceNumber)}async function RE(r){return et.encode(r.data)}var P1;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(P1||(P1={}));function LE(r){for(let e of r.tuples())switch(e[0]){case P1.ip4:case P1.ip6:return r4(e[0],e[1]);default:break}return null}var ua=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,s]of this.entries.entries())if(s.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 lr;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(lr||(lr={}));var qg=class extends Ae{globalSignaturePolicy;multicodecs=[x1,hE,Kg];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=gt({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=x1;opts;decodeRpcLimits;metrics;status={code:lr.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let s={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:bE(t.scoreParams),scoreThresholds:xE(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=s.decodeRpcLimits??pE,this.globalSignaturePolicy=s.globalSignaturePolicy??Ln,s.fallbackToFloodsub&&this.multicodecs.push(Ug),this.log=e.logger.forComponent(s.debugName??"libp2p:gossipsub"),this.opts=s,this.direct=new Set(s.directPeers.map(n=>n.id.toString())),this.seenCache=new ua({validityMs:s.seenTTL}),this.publishedMessageIds=new ua({validityMs:s.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Ln:this.msgIdFn=OE;break;case li:this.msgIdFn=RE;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new ua({validityMs:s.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??kE,this.mcache=t.messageCache??new v1(s.mcacheGossip,s.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 n=Math.max(...Object.values(s.scoreParams.topics).map(i=>i.meshMessageDeliveriesWindow),1e3),o=yE(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:s.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:n/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 C1(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new _1(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:s.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=s.allowedTopics!=null?new Set(s.allowedTopics):null}[Symbol.toStringTag]="@chainsafe/libp2p-gossipsub";[Ye]=["@libp2p/pubsub"];[Kn]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===lr.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=DE(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=gt({objectMode:!0}),Qe(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},s=await Promise.all(this.multicodecs.map(async o=>e.register(o,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:lr.started,registrarTopologyIds:s,heartbeatTimeout:n,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!==lr.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:lr.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 n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let s=[];for(let n of this.streamsOutbound.values())s.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())s.push(n.close());this.streamsInbound.clear(),await Promise.all(s),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 s=t.remotePeer;this.addPeer(s,t.direction,t.remoteAddr),this.createInboundStream(s,e),this.outboundInflightQueue.push({peerId:s,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 s=e.toString();if(this.peers.has(s)&&!this.streamsOutbound.has(s))try{let n=new A1(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(s,n);let o=n.protocol;o===Ug&&this.floodsubPeers.add(s),this.metrics?.peersPerProtocol.inc({protocol:o},1),this.subscriptions.size>0&&(this.log("send subscriptions to",s),this.sendSubscriptions(s,Array.from(this.subscriptions),!0))}catch(n){this.log.error("createOutboundStream error",n)}}createInboundStream(e,t){if(!this.isStarted())return;let s=e.toString();if(!this.peers.has(s))return;let n=this.streamsInbound.get(s);n!==void 0&&(this.log("replacing existing inbound steam %s",s),n.close().catch(i=>{this.log.error(i)})),this.log("create inbound stream %s",s);let o=new T1(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(s,o),this.pipePeerReadStream(e,o.source).catch(i=>{this.log(i)})}addPeer(e,t,s){let n=e.toString();if(!this.peers.has(n)){this.log("new peer %p",e),this.peers.set(n,e),this.score.addPeer(n);let o=LE(s);o!==null?this.score.addIP(n,o):this.log("Added peer has no IP in current address %s %s",n,s.toString()),this.outbound.has(n)||this.outbound.set(n,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 s=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);s!=null&&this.metrics?.peersPerProtocol.inc({protocol:s.protocol},-1),s?.close().catch(o=>{this.log.error(o)}),n?.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===lr.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(s=>this.peers.get(s)??G(s))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await Qe(t,async s=>{for await(let n of s)try{let o=n.subarray(),i=Vs.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(s){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(s,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 s=t.subscriptions!=null?t.subscriptions.length:0,n=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 ${s} messages ${n} ihave ${o} iwant ${i} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let l=[];t.subscriptions.forEach(u=>{let h=u.topic,d=u.subscribe===!0;if(h!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,d),l.push({topic:h,subscribe:d})}}),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(h=>{this.metrics?.onMsgRecvError(l.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await u}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,s){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);n==null&&(n=new Set,this.topics.set(t,n)),s?n.add(e.toString()):n.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let s=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,s.code);let n=s.code;switch(n){case Ot.duplicate:this.score.duplicateMessage(e.toString(),s.msgIdStr,t.topic),this.gossipTracer.deliverMessage(s.msgIdStr,!0),this.mcache.observeDuplicate(s.msgIdStr,e.toString());return;case Ot.invalid:if(s.msgIdStr!=null){let o=s.msgIdStr;this.score.rejectMessage(e.toString(),o,t.topic,s.reason),this.gossipTracer.rejectMessage(o,s.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,s);return;case Ot.valid:this.score.validateMessage(s.messageId.msgIdStr),this.gossipTracer.deliverMessage(s.messageId.msgIdStr),this.mcache.put(s.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:s.messageId.msgIdStr,msg:s.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:s.msg}))),this.opts.asyncValidation||this.forwardMessage(s.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let s=this.fastMsgIdFn?.(t),n=s!==void 0?this.fastMsgIdCache?.get(s):void 0;if(n!=null)return{code:Ot.duplicate,msgIdStr:n};let o=await PE(this.globalSignaturePolicy,t);if(!o.valid)return{code:Ot.invalid,reason:zt.Error,error:o.error};let i=o.message;try{this.dataTransform!=null&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(h){return this.log("Invalid message, transform failed",h),{code:Ot.invalid,reason:zt.Error,error:Mt.TransformFailed}}let a=await this.msgIdFn(i),c=this.msgIdToStrFn(a),l={msgId:a,msgIdStr:c};if(s!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(s,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:Ot.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 h;try{h=await u(e,i)}catch(d){let f=d.code;f===fE&&(h=Nt.Ignore),f===dE?h=Nt.Reject:h=Nt.Ignore}if(h!==Nt.Accept)return{code:Ot.invalid,reason:Hg(h),msgIdStr:c}}return{code:Ot.valid,messageId:l,msg:i}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,s){this.sendRpc(e,{subscriptions:t.map(n=>({topic:n,subscribe:s})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let s=t.ihave?.length>0?this.handleIHave(e,t.ihave):[],n=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),s.length===0&&n.length===0&&o.length===0)return;let i=this.sendRpc(e,Gr(n,{iwant:s,prune:o})),a=s[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(),s=this.acceptFromWhitelist.get(e);if(s!=null&&s.messagesAccepted<128&&s.acceptUntil>=t)return s.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),n>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let s=this.score.score(e);if(s<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:la.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:la.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:la.MaxIasked}),[];let i=new Map;if(t.forEach(({topicID:l,messageIDs:u})=>{if(l==null||u==null||!this.mesh.has(l))return;let h=0;u.forEach(d=>{let f=this.msgIdToStrFn(d);this.seenCache.has(f)||(i.set(f,d),h++)}),this.metrics?.onIhaveRcv(l,u.length,h)}),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 fs(c),c=c.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:c}]}handleIWant(e,t){if(t.length===0)return[];let s=this.score.score(e);if(s<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,s),[];let n=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}n.set(l,u.msg)})}),this.metrics?.onIwantRcv(o,i),n.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",n.size,e),Array.from(n.values()))}async handleGraft(e,t){let s=[],n=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),s.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,ca.GraftBackoff),i=!1;let h=u+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<h&&this.score.addPenalty(e,1,ca.GraftBackoff),this.addBackoff(e,c),s.push(c)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,c),s.push(c),i=!1,this.addBackoff(e,c)):l.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(s.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,qt.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),s.length===0)return[];let a=!1;return Promise.all(s.map(async c=>this.makePrune(e,c,i,a)))}async handlePrune(e,t){let s=this.score.score(e);for(let{topicID:n,backoff:o,peers:i}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,$r.Prune,1)),typeof o=="number"&&o>0?this.doAddBackoff(e,n,o*1e3):this.addBackoff(e,n),i!=null&&i.length>0&&(s<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,s,n):await this.pxConnect(i)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n,direction:"inbound"}})}}handleIdontwant(e,t){let s=this.idontwantCounts.get(e)??0;if(s>=this.opts.idontwantMaxMessages)return;let n=s,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(s>=this.opts.idontwantMaxMessages)break e;s++;let u=this.msgIdToStrFn(l);o.set(u,this.heartbeatTicks),this.mcache.msgs.has(u)||i++}this.idontwantCounts.set(e,s);let a=s-n;this.metrics?.onIdontwantRcv(a,i)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,s){let n=this.backoff.get(t);n==null&&(n=new Map,this.backoff.set(t,n));let o=Date.now()+s;(n.get(e)??0)<o&&n.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,ca.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,s)=>{t.forEach((n,o)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(o)}),t.size===0&&this.backoff.delete(s)})}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&&(fs(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async s=>{if(s.peerID==null)return;let n=Ut(ct(s.peerID)),o=n.toString();if(!this.peers.has(o)){if(s.signedPeerRecord==null){t.push(o);return}try{if(!await this.components.peerStore.consumePeerRecord(s.signedPeerRecord,n)){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 s=>this.connect(s)))}async connect(e){this.log("Initiating connection with %s",e);let t=G(e),s=await this.components.connectionManager.openConnection(t);for(let n of this.multicodecs)for(let o of this.components.registrar.getTopologies(n))o.onConnect?.(t,s)}subscribe(e){if(this.status.code!==lr.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!==lr.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 s of this.peers.keys())this.sendSubscriptions(s,[e],!1);this.leave(e)}join(e){if(this.status.code!==lr.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,s=this.backoff.get(e),n=this.fanout.get(e);if(n!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(o=>{!this.direct.has(o)&&this.score.score(o)>=0&&s?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,qt.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&&s?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,qt.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!==lr.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 s=>{this.log("LEAVE: Remove mesh link to %s in %s",s,e),await this.sendPrune(s,e)})).catch(s=>{this.log("Error sending prunes to mesh peers",s)}),this.mesh.delete(e))}selectPeersToForward(e,t,s){let n=new Set,o=this.topics.get(e);o!=null&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(s?.has(a)??!1)&&n.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(s?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&n.add(a)}));let i=this.mesh.get(e);return i!=null&&i.size>0&&i.forEach(a=>{t!==a&&!(s?.has(a)??!1)&&n.add(a)}),n}selectPeersToPublish(e){let t=new Set,s={direct:0,floodsub:0,mesh:0,fanout:0},n=this.topics.get(e);if(n!=null)if(this.opts.floodPublish)n.forEach(o=>{this.direct.has(o)?(t.add(o),s.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),s.floodsub++)});else{this.direct.forEach(i=>{n.has(i)&&(t.add(i),s.direct++)}),this.floodsubPeers.forEach(i=>{n.has(i)&&this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),s.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(i=>{t.add(i),s.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),s.mesh++});else{let i=this.fanout.get(e);if(i!=null&&i.size>0)i.forEach(a=>{t.add(a),s.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),s.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:s}}forwardMessage(e,t,s,n){s!=null&&this.score.deliverMessage(s,e,t.topic);let o=this.selectPeersToForward(t.topic,s,n);o.forEach(i=>{this.sendRpc(i,Gr([t]))}),this.metrics?.onForwardMsg(t.topic,o.size)}async publish(e,t,s){let n=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 CE(this.publishConfig,e,t,o),c=await this.msgIdFn(a),l=this.msgIdToStrFn(c),u=s?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(l)){if(u)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:h,tosendCount:d}=this.selectPeersToPublish(e),f=this.opts.emitSelf&&this.subscriptions.has(e),p=s?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(h.size===0&&!p&&!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=s?.batchPublish??this.opts.batchPublish,g=Gr([i]);if(m)this.sendRpcInBatch(h,g);else for(let b of h)this.sendRpc(b,g)||h.delete(b);let y=Date.now()-n;return this.metrics?.onPublishMsg(e,d,h.size,i.data!=null?i.data.length:0,y),f&&(h.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(h.values()).map(b=>this.peers.get(b)??G(b))}}sendRpcInBatch(e,t){let s=Vs.encode(t),n=ia.single(s);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(n)}catch(a){e.delete(o),this.log.error(`Cannot send rpc to ${o}`,a)}this.metrics?.onRpcSent(t,s.length)}}reportMessageValidationResult(e,t,s){let n;if(s===Nt.Accept){if(n=this.mcache.validate(e),n!=null){let{message:i,originatingPeers:a}=n;this.score.deliverMessage(t,e,i.topic),this.forwardMessage(e,n.message,t,a)}}else if(n=this.mcache.remove(e),n!=null){let i=Hg(s),{message:a,originatingPeers:c}=n;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(n,s,o)}sendGraft(e,t){let n=Gr([],{graft:[{topicID:t}]});this.sendRpc(e,n)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],o=Gr([],{prune:n});this.sendRpc(e,o)}sendIDontWants(e,t,s){let n=this.mesh.get(t);if(n==null)return;let o=new Set(n);o.delete(s);for(let a of o)this.streamsOutbound.get(a)?.protocol!==x1&&o.delete(a);let i=Gr([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(o,i)}sendRpc(e,t){let s=this.streamsOutbound.get(e);if(s==null)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let n=this.control.get(e);n!=null&&(this.piggybackControl(e,t,n),this.control.delete(e));let o=this.gossip.get(e);o!=null&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let i=Vs.encode(t);try{s.push(i)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),n!=null&&this.control.set(e,n),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,s){let n=zg(t);for(let o of s.graft)o.topicID!=null&&(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.graft.push(o);for(let o of s.prune)o.topicID!=null&&!(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.prune.push(o)}piggybackGossip(e,t,s){let n=zg(t);n.control.ihave=s}async sendGraftPrune(e,t,s){let n=this.opts.doPX,o=!1;for(let[i,a]of e){let c=a.map(h=>({topicID:h})),l=[],u=t.get(i);u!=null&&(l=await Promise.all(u.map(async h=>this.makePrune(i,h,n&&!(s.get(i)??!1),o))),t.delete(i)),this.sendRpc(i,Gr([],{graft:c,prune:l}))}for(let[i,a]of t){let c=await Promise.all(a.map(async l=>this.makePrune(i,l,n&&!(s.get(i)??!1),o)));this.sendRpc(i,Gr([],{prune:c}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[s,n]of e)this.doEmitGossip(s,n,t.get(s)??[])}doEmitGossip(e,t,s){if(s.length===0||(fs(s),s.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",s.length),t.size===0))return;let n=this.opts.Dlazy,i=this.opts.gossipFactor*t.size,a=t;i>n&&(n=i),n>a.size?n=a.size:a=fs(Array.from(a)).slice(0,n),a.forEach(c=>{let l=s;s.length>5e3&&(l=fs(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,Gr([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let s=Gr([],{graft:t.graft,prune:t.prune});this.sendRpc(e,s)}}pushGossip(e,t){this.log("Add gossip to %s",e);let s=this.gossip.get(e)??[];this.gossip.set(e,s.concat(t))}async makePrune(e,t,s,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===Kg)return{topicID:t,peers:[]};let o=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=o/1e3;if(this.doAddBackoff(e,t,o),!s)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)??G(l),h;try{h=await this.components.peerStore.get(u)}catch(d){if(d.name!=="NotFoundError")throw d}return{peerID:u.toMultihash().bytes,signedPeerRecord:h?.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===lr.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:s,Dscore:n,Dout:o,fanoutTTL:i}=this.opts;this.heartbeatTicks++;let a=new Map,c=p=>{let m=a.get(p);return m===void 0&&(m=this.score.score(p),a.set(p,m)),m},l=new Map,u=new Map,h=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 p of this.idontwants.values())for(let[m,g]of p)this.heartbeatTicks-g>=this.opts.mcacheLength&&p.delete(m);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let d=new Map;this.mesh.forEach((p,m)=>{let g=this.topics.get(m),y=new Set,b=new Set;if(d.set(m,b),g!=null){let E=fs(Array.from(g)),P=this.backoff.get(m);for(let C of E){let D=this.streamsOutbound.get(C);if(D!=null&&this.multicodecs.includes(D.protocol)&&!p.has(C)&&!this.direct.has(C)){let v=c(C);P?.has(C)!==!0&&v>=0&&y.add(C),v>=this.opts.scoreThresholds.gossipThreshold&&b.add(C)}}}let w=(E,P)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",E,m),this.addBackoff(E,m),p.delete(E),c(E)>=this.opts.scoreThresholds.gossipThreshold&&b.add(E),this.metrics?.onRemoveFromMesh(m,P,1);let C=u.get(E);C==null?u.set(E,[m]):C.push(m)},x=(E,P)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",E,m),this.score.graft(E,m),p.add(E),b.delete(E),this.metrics?.onAddToMesh(m,P,1);let C=l.get(E);C==null?l.set(E,[m]):C.push(m)};if(p.forEach(E=>{let P=c(E);P<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",E,P,m),w(E,$r.BadScore),h.set(E,!0))}),p.size<t){let E=e-p.size;vE(y,E).forEach(C=>{x(C,qt.NotEnough)})}if(p.size>s){let E=Array.from(p);E.sort((C,D)=>c(D)-c(C)),E=E.slice(0,n).concat(fs(E.slice(n)));let P=0;if(E.slice(0,e).forEach(C=>{(this.outbound.get(C)??!1)&&P++}),P<o){let C=v=>{let M=E[v];for(let F=v;F>0;F--)E[F]=E[F-1];E[0]=M};if(P>0){let v=P;for(let M=1;M<e&&v>0;M++)(this.outbound.get(E[M])??!1)&&(C(M),v--)}let D=e-P;for(let v=e;v<E.length&&D>0;v++)(this.outbound.get(E[v])??!1)&&(C(v),D--)}E.slice(e).forEach(C=>{w(C,$r.Excess)})}if(p.size>=t){let E=0;if(p.forEach(P=>{(this.outbound.get(P)??!1)&&E++}),E<o){let P=o-E;S1(y,P,D=>this.outbound.get(D)===!0).forEach(D=>{x(D,qt.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&p.size>1){let E=Array.from(p).sort((D,v)=>c(D)-c(v)),P=Math.floor(p.size/2),C=c(E[P]);if(C<this.opts.scoreThresholds.opportunisticGraftThreshold){let D=this.opts.opportunisticGraftPeers,v=S1(y,D,M=>c(M)>C);for(let M of v)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",M,m),x(M,qt.Opportunistic)}}});let f=Date.now();this.fanoutLastpub.forEach((p,m)=>{p+i<f&&(this.fanout.delete(m),this.fanoutLastpub.delete(m))}),this.fanout.forEach((p,m)=>{let g=this.topics.get(m);p.forEach(x=>{(!(g?.has(x)??!1)||c(x)<this.opts.scoreThresholds.publishThreshold)&&p.delete(x)});let y=this.topics.get(m),b=[],w=new Set;if(d.set(m,w),y!=null){let x=fs(Array.from(y));for(let E of x){let P=this.streamsOutbound.get(E);if(P!=null&&this.multicodecs.includes(P.protocol)&&!p.has(E)&&!this.direct.has(E)){let C=c(E);C>=this.opts.scoreThresholds.publishThreshold&&b.push(E),C>=this.opts.scoreThresholds.gossipThreshold&&w.add(E)}}}if(p.size<e){let x=e-p.size;b.slice(0,x).forEach(E=>{p.add(E),w?.delete(E)})}}),this.emitGossip(d),await this.sendGraftPrune(l,u,h),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,s=()=>!0){let n=this.topics.get(e);if(n==null)return new Set;let o=[];return n.forEach(i=>{let a=this.streamsOutbound.get(i);a!=null&&this.multicodecs.includes(a.protocol)&&s(i)&&o.push(i)}),o=fs(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,s=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-s)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let c of this.idontwants.values())n+=c.size;e.cacheSize.set({cache:"idontwants"},n);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=AE(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:s}=e.detail;this.components.peerStore.merge(this.peers.get(t)??G(t),{tags:{[s]:{value:100}}}).catch(n=>{this.log.error("Error tagging peer %s with topic %s",t,s,n)})};untagMeshPeer=e=>{let{peerId:t,topic:s}=e.detail;this.components.peerStore.merge(this.peers.get(t)??G(t),{tags:{[s]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,s,n)})}};function BE(r={}){return e=>new qg(e,r)}X();ce();var PD=H("dns4"),kD=H("dns6"),DD=H("dnsaddr"),Uo=Xe(H("dns"),DD,PD,kD),M1=Xe(H("ip4"),H("ip6")),da=Xe(j(M1,H("tcp")),j(Uo,H("tcp"))),O1=j(M1,H("udp")),MD=j(O1,H("utp")),OD=j(O1,H("quic")),RD=j(O1,H("quic-v1")),$g=Xe(j(da,H("ws")),j(Uo,H("ws"))),k1=Xe(j($g,H("p2p")),$g),Gg=Xe(j(da,H("wss")),j(Uo,H("wss")),j(da,H("tls"),H("ws")),j(Uo,H("tls"),H("ws"))),D1=Xe(j(Gg,H("p2p")),Gg),Vg=Xe(j(da,H("http")),j(M1,H("http")),j(Uo,H("http"))),Wg=Xe(j(da,H("https")),j(M1,H("https")),j(Uo,H("https"))),FE=j(O1,H("webrtc-direct"),H("certhash")),HE=Xe(j(FE,H("p2p")),FE),UE=j(RD,H("webtransport"),H("certhash"),H("certhash")),zE=Xe(j(UE,H("p2p")),UE),qE=Xe(j(k1,H("p2p-webrtc-star"),H("p2p")),j(D1,H("p2p-webrtc-star"),H("p2p")),j(k1,H("p2p-webrtc-star")),j(D1,H("p2p-webrtc-star"))),Mce=Xe(j(k1,H("p2p-websocket-star"),H("p2p")),j(D1,H("p2p-websocket-star"),H("p2p")),j(k1,H("p2p-websocket-star")),j(D1,H("p2p-websocket-star"))),$E=Xe(j(Vg,H("p2p-webrtc-direct"),H("p2p")),j(Wg,H("p2p-webrtc-direct"),H("p2p")),j(Vg,H("p2p-webrtc-direct")),j(Wg,H("p2p-webrtc-direct"))),Ko=Xe($g,Gg,Vg,Wg,qE,$E,da,MD,OD,Uo,HE,zE),Oce=Xe(j(Ko,H("p2p-stardust"),H("p2p")),j(Ko,H("p2p-stardust"))),vn=Xe(j(Ko,H("p2p")),qE,$E,HE,zE,H("p2p")),KE=Xe(j(vn,H("p2p-circuit"),vn),j(vn,H("p2p-circuit")),j(H("p2p-circuit"),vn),j(Ko,H("p2p-circuit")),j(H("p2p-circuit"),Ko),H("p2p-circuit")),GE=()=>Xe(j(KE,GE),KE),Fo=GE(),VE=Xe(j(Fo,vn,Fo),j(vn,Fo),j(Fo,vn),Fo,vn);var Rce=Xe(j(Fo,H("webrtc"),H("p2p")),j(Fo,H("webrtc")),j(Ko,H("webrtc"),H("p2p")),j(Ko,H("webrtc")),H("webrtc"));function WE(r){function e(t){let s;try{s=q(t)}catch{return!1}let n=r(s.protoNames());return n===null?!1:n===!0||n===!1?n:n.length===0}return e}function j(...r){function e(t){if(t.length<r.length)return null;let s=t;return r.some(n=>(s=typeof n=="function"?n().partialMatch(t):n.partialMatch(t),Array.isArray(s)&&(t=s),s===null)),s}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:WE(e),partialMatch:e}}function Xe(...r){function e(s){let n=null;return r.some(o=>{let i=typeof o=="function"?o().partialMatch(s):o.partialMatch(s);return i!=null?(n=i,!0):!1}),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:WE(e),partialMatch:e}}function H(r){let e=r;function t(n){let o;try{o=q(n)}catch{return!1}let i=o.protoNames();return i.length===1&&i[0]===e}function s(n){return n.length===0?null:n[0]===e?n.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:s}}Oe();var LD="bootstrap",ND=50,BD=1e3,jg=class extends Ae{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??BD,this.list=[];for(let s of t.list){if(!VE.matches(s)){this.log.error("Invalid multiaddr");continue}let n=q(s),o=n.getPeerId();if(o==null){this.log.error("Invalid bootstrap multiaddr without peer id");continue}let i={id:G(o),multiaddrs:[n]};this.list.push(i)}this._init=t}[Ga]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[Ye]=["@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(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??LD]:{value:this._init.tagValue??ND,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.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function jE(r){return e=>new jg(e,r)}lt();ce();Oe();Vt();X();var Yg=1e3,YE=60*Yg,R1=290,XE=15,ZE=120*YE,QE=1,L1=2e3,JE=100,Xg="circuit-relay-source",hl=`${ci}-circuit-relay`,Zg=`${ci}-circuit-relay-source`,eS=2*YE,tS=BigInt(1<<17),ps="/libp2p/circuit/relay/0.2.0/hop",dl="/libp2p/circuit/relay/0.2.0/stop",rS=30*Yg,qce=30*Yg,fl=300,sS=4096,nS=.001;ws();rt();var ve;(function(r){let e;(function(n){n.RESERVE="RESERVE",n.CONNECT="CONNECT",n.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(n){n[n.RESERVE=0]="RESERVE",n[n.CONNECT=1]="CONNECT",n[n.STATUS=2]="STATUS"})(t||(t={})),(function(n){n.codec=()=>Pn(t)})(e=r.Type||(r.Type={}));let s;r.codec=()=>(s==null&&(s=se((n,o,i={})=>{i.lengthDelimited!==!1&&o.fork(),n.type!=null&&(o.uint32(8),r.Type.codec().encode(n.type,o)),n.peer!=null&&(o.uint32(18),fa.codec().encode(n.peer,o)),n.reservation!=null&&(o.uint32(26),N1.codec().encode(n.reservation,o)),n.limit!=null&&(o.uint32(34),pa.codec().encode(n.limit,o)),n.status!=null&&(o.uint32(40),ie.codec().encode(n.status,o)),i.lengthDelimited!==!1&&o.ldelim()},(n,o,i={})=>{let a={},c=o==null?n.len:n.pos+o;for(;n.pos<c;){let l=n.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(n);break}case 2:{a.peer=fa.codec().decode(n,n.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=N1.codec().decode(n,n.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=pa.codec().decode(n,n.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=ie.codec().decode(n);break}default:{n.skipType(l&7);break}}}return a})),s),r.encode=n=>re(n,r.codec()),r.decode=(n,o)=>te(n,r.codec(),o)})(ve||(ve={}));var ur;(function(r){let e;(function(n){n.CONNECT="CONNECT",n.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(n){n[n.CONNECT=0]="CONNECT",n[n.STATUS=1]="STATUS"})(t||(t={})),(function(n){n.codec=()=>Pn(t)})(e=r.Type||(r.Type={}));let s;r.codec=()=>(s==null&&(s=se((n,o,i={})=>{i.lengthDelimited!==!1&&o.fork(),n.type!=null&&(o.uint32(8),r.Type.codec().encode(n.type,o)),n.peer!=null&&(o.uint32(18),fa.codec().encode(n.peer,o)),n.limit!=null&&(o.uint32(26),pa.codec().encode(n.limit,o)),n.status!=null&&(o.uint32(32),ie.codec().encode(n.status,o)),i.lengthDelimited!==!1&&o.ldelim()},(n,o,i={})=>{let a={},c=o==null?n.len:n.pos+o;for(;n.pos<c;){let l=n.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(n);break}case 2:{a.peer=fa.codec().decode(n,n.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=pa.codec().decode(n,n.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=ie.codec().decode(n);break}default:{n.skipType(l&7);break}}}return a})),s),r.encode=n=>re(n,r.codec()),r.decode=(n,o)=>te(n,r.codec(),o)})(ur||(ur={}));var fa;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{if(n.lengthDelimited!==!1&&s.fork(),t.id!=null&&t.id.byteLength>0&&(s.uint32(10),s.bytes(t.id)),t.addrs!=null)for(let o of t.addrs)s.uint32(18),s.bytes(o);n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={id:ee(0),addrs:[]},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.id=t.bytes();break}case 2:{if(n.limits?.addrs!=null&&o.addrs.length===n.limits.addrs)throw new Se('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=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(fa||(fa={}));var N1;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{if(n.lengthDelimited!==!1&&s.fork(),t.expire!=null&&t.expire!==0n&&(s.uint32(8),s.uint64(t.expire)),t.addrs!=null)for(let o of t.addrs)s.uint32(18),s.bytes(o);t.voucher!=null&&(s.uint32(26),B1.codec().encode(t.voucher,s)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={expire:0n,addrs:[]},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.expire=t.uint64();break}case 2:{if(n.limits?.addrs!=null&&o.addrs.length===n.limits.addrs)throw new Se('Decode error - map field "addrs" had too many elements');o.addrs.push(t.bytes());break}case 3:{o.voucher=B1.codec().decode(t,t.uint32(),{limits:n.limits?.voucher});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(N1||(N1={}));var pa;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.duration!=null&&(s.uint32(8),s.uint32(t.duration)),t.data!=null&&(s.uint32(16),s.uint64(t.data)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={},i=s==null?t.len:t.pos+s;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=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(pa||(pa={}));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 Qg;(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"})(Qg||(Qg={}));(function(r){r.codec=()=>Pn(Qg)})(ie||(ie={}));var ma;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.relay!=null&&t.relay.byteLength>0&&(s.uint32(10),s.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(s.uint32(18),s.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(s.uint32(24),s.uint64(t.expiration)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={relay:ee(0),peer:ee(0),expiration:0n},i=s==null?t.len:t.pos+s;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=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(ma||(ma={}));var B1;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(s.uint32(10),s.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(s.uint32(18),s.bytes(t.payloadType)),t.payload!=null&&(s.uint32(26),ma.codec().encode(t.payload,s)),t.signature!=null&&t.signature.byteLength>0&&(s.uint32(42),s.bytes(t.signature)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={publicKey:ee(0),payloadType:ee(0),signature:ee(0)},i=s==null?t.len:t.pos+s;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=ma.codec().decode(t,t.uint32(),{limits:n.limits?.payload});break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,s)=>te(t,r.codec(),s)})(B1||(B1={}));Cr();jr();var F1=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},pl=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}},ml=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},U1=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},K1=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*oS(r,e,t){let s=e.remaining;for await(let n of r){let o=BigInt(n.byteLength);if(e.remaining-o<0){let i=Number(e.remaining);e.remaining=0n;try{i!==0&&(yield n.subarray(0,i))}catch(a){t.log.error(a)}throw new F1(`data limit of ${s} bytes exceeded`)}e.remaining-=o,yield n}}function iS(r,e,t,s,n){function o(h){r.abort(h),e.abort(h)}let i=[t,s.signal];s.limit?.duration!=null&&(n.log("limiting relayed connection duration to %dms",s.limit.duration),i.push(AbortSignal.timeout(s.limit.duration)));let a=cr(i),c=!1,l=!1,u;s.limit?.data!=null&&(u={remaining:s.limit.data}),queueMicrotask(()=>{let h=()=>{n.log("relayed connection reached time limit"),e.abort(new pl(`duration limit of ${s.limit?.duration} ms exceeded`))};a.addEventListener("abort",h,{once:!0}),e.sink(u==null?r.source:oS(r.source,u,n)).catch(d=>{n.log.error("error while relaying streams src -> dst",d),o(d)}).finally(()=>{c=!0,l&&(a.removeEventListener("abort",h),a.clear())})}),queueMicrotask(()=>{let h=()=>{n.log("relayed connection reached time limit"),r.abort(new pl(`duration limit of ${s.limit?.duration} ms exceeded`))};a.addEventListener("abort",h,{once:!0}),r.sink(u==null?e.source:oS(e.source,u,n)).catch(d=>{n.log.error("error while relaying streams dst -> src",d),o(d)}).finally(()=>{l=!0,c&&(a.removeEventListener("abort",h),a.clear())})})}function Jg(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var gl=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}},H1=Ie(fe(dw.matchers[0],Ce(290))),z1=Ie(Ce(290));var e3=class extends Error{type;code;constructor(e,t,s){super(e??"The operation was aborted"),this.type="aborted",this.name=s??"AbortError",this.code=t??"ABORT_ERR"}};function aS(r,e){let t=new e3(e?.errorMessage,e?.errorCode,e?.errorName),s=new AbortController,n=()=>{s.abort(t)},o=AbortSignal.timeout(r);o.addEventListener("abort",n);let i=s.signal;return i.reset=a=>{o?.removeEventListener("abort",n),o=AbortSignal.timeout(a??r),o.addEventListener("abort",()=>{s.abort(t)})},i.clear=()=>{o?.removeEventListener("abort",n),o=void 0},i}var q1=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??XE,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??ZE,this.defaultDurationLimit=t.defaultDurationLimit??eS,this.defaultDataLimit=t.defaultDataLimit??tS,this.reservations=_c({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,s){let n=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&n==null)return{status:ie.RESERVATION_REFUSED};let o=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=s??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),n!=null?(this.log("refreshing reservation for client %p",e),n.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),n={addr:t,expiry:o,limit:i,signal:aS(this.reservationTtl)}),this.reservations.set(e,n),n.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 $1=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:s}){this.relay=e,this.peer=t,this.expiration=s}marshal(){return ma.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 cS=r=>r.protoCodes().includes(R1),FD={maxOutboundStopStreams:fl},t3=class extends Ae{registrar;peerStore;addressManager;peerId;privateKey;connectionManager;connectionGater;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.registrar=e.registrar,this.peerStore=e.peerStore,this.addressManager=e.addressManager,this.peerId=e.peerId,this.privateKey=e.privateKey,this.connectionManager=e.connectionManager,this.connectionGater=e.connectionGater,this.started=!1,this.hopTimeout=t?.hopTimeout??rS,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??FD.maxOutboundStopStreams,this.reservationStore=new q1(e,t.reservations),this.shutdownController=new AbortController,Y(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.registrar.handle(ps,e=>{this.onHop(e).catch(t=>{this.log.error(t)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.registrar.unhandle(ps),this.started=!1}async onHop({connection:e,stream:t}){this.log("received circuit v2 hop protocol stream from %p",e.remotePeer);let s={signal:AbortSignal.timeout(this.hopTimeout)},n=qr(t);try{let o=await n.pb(ve).read(s);if(o?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",o.type),await this.handleHopProtocol({connection:e,stream:n,request:o},s)}catch(o){this.log.error("error while handling hop",o),await n.pb(ve).write({type:ve.Type.STATUS,status:ie.MALFORMED_MESSAGE},s),t.abort(o)}}async handleHopProtocol({stream:e,request:t,connection:s},n){switch(this.log("received hop message"),t.type){case ve.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:s},n);break;case ve.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:s},n);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,s.remotePeer),await e.pb(ve).write({type:ve.Type.STATUS,status:ie.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},s){let n=e.pb(ve);if(this.log("hop reserve request from %p",t.remotePeer),cS(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await n.write({type:ve.Type.STATUS,status:ie.PERMISSION_DENIED},s);return}if(await this.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await n.write({type:ve.Type.STATUS,status:ie.PERMISSION_DENIED},s);return}let o=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(o.status!==ie.OK){await n.write({type:ve.Type.STATUS,status:o.status},s);return}if(o.expire!=null){let i=o.expire*1e3-Date.now();await this.peerStore.merge(t.remotePeer,{tags:{[Xg]:{value:1,ttl:i},[Zg]:{value:1,ttl:i}}})}await n.write({type:ve.Type.STATUS,status:ie.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(o.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},s),this.log("sent confirmation response to %s",t.remotePeer)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.peerStore.merge(t.remotePeer,{tags:{[Xg]:void 0,[Zg]:void 0}})}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let s=[];for(let o of this.addressManager.getAddresses())o.toString().includes("/p2p-circuit")||s.push(o.bytes);let n=await nr.seal(new $1({peer:e,relay:this.peerId,expiration:t}),this.privateKey);return{addrs:s,expire:t,voucher:{publicKey:He(n.publicKey),payloadType:n.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.peerId.toMultihash().bytes,expiration:t},signature:n.signature}}}async handleConnect({stream:e,request:t,connection:s},n){let o=e.pb(ve);if(cS(s.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",s.remotePeer),await o.write({type:ve.Type.STATUS,status:ie.PERMISSION_DENIED},n);return}this.log("hop connect request from %p",s.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=Ut(ct(t.peer.id))}catch(d){this.log.error("invalid hop connect request via peer %p %s",s.remotePeer,d),await o.write({type:ve.Type.STATUS,status:ie.MALFORMED_MESSAGE},n);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,s.remotePeer,ie.NO_RESERVATION),await o.write({type:ve.Type.STATUS,status:ie.NO_RESERVATION},n);return}if(await this.connectionGater.denyOutboundRelayedConnection?.(s.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",s.remotePeer,i),await o.write({type:ve.Type.STATUS,status:ie.PERMISSION_DENIED},n);return}let c=this.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,s.remotePeer),await o.write({type:ve.Type.STATUS,status:ie.NO_RESERVATION},n);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:ur.Type.CONNECT,peer:{id:s.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},n);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await o.write({type:ve.Type.STATUS,status:ie.CONNECTION_FAILED},n);return}await o.write({type:ve.Type.STATUS,status:ie.OK,limit:a?.limit},n);let h=e.unwrap();this.log("connection from %p to %p established - merging streams",s.remotePeer,i),iS(h,u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},s){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let n=await e.newStream([dl],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...s}),o=qr(n),i=o.pb(ur);await i.write(t,s);let a;try{a=await i.read(s)}catch{this.log.error("error parsing stop message response from %p",e.remotePeer)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await n.close(s);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 n.close(s)}get reservations(){return this.reservationStore.reservations}};function r3(r={}){return e=>new t3(e,r)}X();ce();function s3(r){let{stream:e,remoteAddr:t,log:s,onDataRead:n,onDataWrite:o}=r,i=!1,a=!1,c=e.close.bind(e);e.close=async f=>{await c(f),d(!0)};let l=e.abort.bind(e);e.abort=f=>{l(f),d(!0)};let u=e.sink.bind(e);e.sink=async f=>{try{await u(Qe(f,p=>l1(p,m=>o?.(m))))}catch(p){h.log.error("errored - %e",p),p.type!=="aborted"&&h.log.error("%s error in sink - %e",t,p)}finally{a=!0,d()}};let h={log:s.newScope("stream-to-maconn"),sink:e.sink,source:(async function*(){try{for await(let f of e.source)n?.(f),yield f}finally{i=!0,d()}})(),remoteAddr:t,timeline:{open:Date.now(),close:void 0},close:e.close,abort:e.abort};function d(f){f===!0&&(i=!0,a=!0),i&&a&&h.timeline.close==null&&(h.timeline.close=Date.now())}return h}Oe();Vt();Oe();Pe();var G1=class extends Ae{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(ps,{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:[s=>s.protocols.includes(ps)],orders:[()=>Math.random()<.5?1:-1,(s,n)=>{let o=lS(s),i=lS(n);return o>i?-1:i>o?1:0}]});for(let s of e)this.log.trace("found relay peer %p in peer store",s.id),this.safeDispatchEvent("relay:discover",{detail:s.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new hn({concurrency:5});this.log("start random walk");for await(let s of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",s.id),t.has(s.id)){this.log.trace("random peer %p was already in queue",s.id);continue}if(this.components.connectionManager.getConnections(s.id)?.length>0){this.log.trace("random peer %p was already connected",s.id);continue}if(!await this.components.connectionManager.isDialable(s.multiaddrs)){this.log.trace("random peer %p was not dialable",s.id,s.multiaddrs.map(n=>n.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",s.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",s.id,t.size,t.running),t.add(this.dialPeer,{peerId:s.id,signal:this.discoveryController.signal}).catch(n=>{this.log.error("error opening connection to random peer %p",s.id,n)})}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)}))}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",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,s=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(s)){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(n=>{this.log.error("error opening connection to discovered peer %p",e.detail.id,n)})}async dialPeer({peerId:e,signal:t}){let s=cr([AbortSignal.timeout(5e3),t]);Y(1/0,s);try{await this.components.connectionManager.openConnection(e,{signal:s})}finally{s.clear()}}};function lS(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(U(e)).getTime()}X();Oe();var n3=class extends Ae{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??L1,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(z1.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(H1.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);Y(1/0,t);let s=e.decapsulate("/p2p-circuit"),n=await this.connectionManager.openConnection(s,{signal:t});if(!this.reservationStore.hasReservation(n.remotePeer)){this.log("making reservation on peer %p",n.remotePeer);let o=await this.reservationStore.addRelay(n.remotePeer,"configured");this.addedRelay(o)}}else throw new Un(`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 uS(r){return new n3(r)}X();Oe();var o3=oe("node:crypto");var hS="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var UD=128,Ho,ga;function KD(r){!Ho||Ho.length<r?(Ho=Buffer.allocUnsafe(r*UD),o3.webcrypto.getRandomValues(Ho),ga=0):ga+r>Ho.length&&(o3.webcrypto.getRandomValues(Ho),ga=0),ga+=r}function dS(r=21){KD(r|=0);let e="";for(let t=ga-r;t<ga;t++)e+=hS[Ho[t]&63];return e}var HD=60*1e3*10,zD=60*1e3*5,qD=30*1e3,V1=class extends Ae{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 Xt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??JE,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??L1,this.started=!1,this.relayFilter=os(100),this.reserveQueue=new hn({concurrency:t?.reservationConcurrency??QE,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",s=>{[...this.reservations.values()].find(o=>o.connection===s.detail.id)!=null&&this.#t(s.detail.remotePeer).catch(o=>{this.log("could not remove relay %p - %e",s.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(hl)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[hl]: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(e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=dS();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 Un("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new K1("The reservation queue is full");let s=this.reserveQueue.find(e);if(s!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),s.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new Un("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let n=Date.now();try{let o=this.reservations.get(e);if(o!=null){let p=this.connectionManager.getConnections(e),m=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),p.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&&Jg(o.reservation.expire)>HD)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 ml("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(Os.matches(a.remoteAddr))throw new U1("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=Jg(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-zD,qD),Math.pow(2,31)-1),h=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",e,p),await this.#t(e)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",e,p)})},u),d;if(t==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new ml("Made reservation on relay but did not need any more discovered relays");d={timeout:h,reservation:c,type:t,connection:a.id,id:p}}else d={timeout:h,reservation:c,type:t,connection:a.id};this.reservations.set(e,d),await this.peerStore.merge(e,{tags:{[hl]:{value:1,ttl:l}}}),this.#r();let f={relay:e,details:d};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()-n,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,s)=>(s.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 s=await e.newStream(ps,t),o=qr(s).pb(ve);this.log.trace("send RESERVE to %p",e.remotePeer),await o.write({type:ve.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await o.read(t)}catch(c){throw s.abort(c),c}finally{s.status!=="closed"&&await s.close(t)}if(this.log.trace("read response %o",i),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=q(l);u.getPeerId()==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:{[hl]: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=os(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var $D=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(q)}catch{return!1}return!0},fS={maxInboundStopStreams:fl,maxOutboundStopStreams:fl,stopTimeout:3e4},W1=class{discovery;registrar;peerStore;connectionManager;transportManager;peerId;upgrader;addressManager;connectionGater;reservationStore;logger;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.logger=e.logger,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,this.maxInboundStopStreams=t.maxInboundStopStreams??fS.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??fS.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new G1(e,{filter:t.discoveryFilter??B2(sS,nS)}),this.discovery.addEventListener("relay:discover",s=>{this.reservationStore.addRelay(s.detail,"discovered").catch(n=>{n.name!=="HadEnoughRelaysError"&&n.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p",s.detail,n)})}),this.reservationStore=new V1(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}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Ye]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Kn](){return this.discovery!=null?["@libp2p/identify"]:[]}[tu]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,Y(1/0,this.shutdownController.signal),await this.registrar.handle(dl,e=>{let t=this.upgrader.createInboundAbortSignal(this.shutdownController.signal);this.onStop(e,t).catch(s=>{this.log.error("error while handling STOP protocol",s),e.stream.abort(s)}).finally(()=>{t.clear()})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await pu(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await mu(this.discovery,this.reservationStore),await this.registrar.unhandle(dl),this.started=!1}async dial(e,t){if(e.protoCodes().filter(f=>f===R1).length!==1){let f="Invalid circuit relay address";throw this.log.error(f,e),new Is(f)}let s=e.toString().split("/p2p-circuit"),n=q(s[0]),o=q(s[s.length-1]),i=n.getPeerId(),a=o.getPeerId();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 Is(`C${f}`)}let c=G(i),l=G(a),h=this.connectionManager.getConnections(c)[0];h==null?(await this.peerStore.merge(c,{multiaddrs:[n]}),t.onProgress?.(new ke("circuit-relay:open-connection")),h=await this.connectionManager.openConnection(c,t)):t.onProgress?.(new ke("circuit-relay:reuse-connection"));let d;try{t.onProgress?.(new ke("circuit-relay:open-hop-stream")),d=await h.newStream(ps,t);let f=qr(d),p=f.pb(ve);t.onProgress?.(new ke("circuit-relay:write-connect-message")),await p.write({type:ve.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[q(o).bytes]}},t),t.onProgress?.(new ke("circuit-relay:read-connect-response"));let m=await p.read(t);if(m.status!==ie.OK)throw new Ft(`failed to connect via relay with status ${m?.status?.toString()??"undefined"}`);let g=new gl(m.limit),y=s3({stream:f.unwrap(),remoteAddr:e,localAddr:n.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),log:this.log,onDataRead:g.onData,onDataWrite:g.onData}),b=await this.upgrader.upgradeOutbound(y,{...t,limits:g.getLimits()});return b.log("outbound relayed connection established to %p with limits %o, over connection %s",b.remotePeer,m.limit??"none",h.id),b}catch(f){throw this.log.error("circuit relay dial to destination %p via relay %p failed",l,c,f),d?.abort(f),f}}createListener(e){return uS({peerId:this.peerId,connectionManager:this.connectionManager,addressManager:this.addressManager,reservationStore:this.reservationStore,logger:this.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>H1.exactMatch(t)||z1.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Os.exactMatch(t))}async onStop({connection:e,stream:t},s){if(!this.reservationStore.hasReservation(e.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.transportManager.listen([e.remoteAddr.encapsulate("/p2p-circuit")])}catch(h){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",h)}let n=qr(t).pb(ur),o=await n.read({signal:s});if(this.log("new circuit relay v2 stop stream from %p with type %s",e.remotePeer,o.type),o?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",e.remotePeer),await n.write({type:ur.Type.STATUS,status:ie.MALFORMED_MESSAGE},{signal:s}),await t.close();return}if(o.type!==ur.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",e.remotePeer),await n.write({type:ur.Type.STATUS,status:ie.UNEXPECTED_MESSAGE},{signal:s}),await t.close();return}if(!$D(o)){this.log.error("invalid stop connect request via peer %p",e.remotePeer),await n.write({type:ur.Type.STATUS,status:ie.MALFORMED_MESSAGE},{signal:s}),await t.close({signal:s});return}let i=Ut(ct(o.peer.id));if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",e.remotePeer),await n.write({type:ur.Type.STATUS,status:ie.PERMISSION_DENIED},{signal:s}),await t.close({signal:s});return}this.log.trace("sending success response to %p",e.remotePeer),await n.write({type:ur.Type.STATUS,status:ie.OK},{signal:s});let a=new gl(o.limit),c=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.addressManager.getAddresses()[0],u=s3({stream:n.unwrap().unwrap(),remoteAddr:c,localAddr:l,log:this.log,onDataRead:a.onData,onDataWrite:a.onData});await this.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:s}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,o.limit??"none",e.id)}};function i3(r={}){return e=>new W1(e,r)}ce();var j1=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(s=>this.seedKey(s)))).filter(s=>s.status==="rejected");t.length>0&&this.log("Failed to seed %d keys",t.length),await new Promise(s=>setTimeout(s,50))})(),this.readyPromise)}async seedKey(e){let t=this.getFret();if(!t)throw new Error("FRET service not available for seeding keys");let s=await rr(e),n=t.getNeighbors(s,"both",1)}toCacheKey(e){return Buffer.from(e).toString("base64url")}getKnownPeers(){let e=this.getLibp2p();if(!e)return[];let t=e.peerId,s=e.peerStore?.getPeers?.()??[],n=(e.getConnections?.()??[]).map(a=>a.remotePeer),o=[...s.map(a=>a.id),...n];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 s=(e.peerStore?.getPeers?.()??[]).filter(n=>n.id.toString()!==e.peerId.toString()).length;return s===0?{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0}:{mode:"healthy",connections:s}}async awaitHealthy(e,t){let s=Date.now();for(;Date.now()-s<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 n=this.getLibp2p();if(n){let o=n.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,s=10*6e4){let n=e.toString(),i=(this.blacklist.get(n)?.score??0)+Math.max(1,t);this.blacklist.set(n,{score:i,expires:Date.now()+s})}isBlacklisted(e){let t=e.toString(),s=this.blacklist.get(t);return s?s.expires<=Date.now()?(this.blacklist.delete(t),!1):s.score>=3:!1}recordCoordinator(e,t){let s=this.toCacheKey(e);this.coordinatorCache.set(s,{id:t,expires:Date.now()+this.cfg.cacheTTLs.coordinatorMs})}async findNearestPeerToKey(e){let t=this.getFret(),s=this.getLibp2p();if(!s)throw new Error("Libp2p not initialized");if(t){let a=await rr(e),c=t.getNeighbors(a,"both",1);if(c.length>0){let l=c[0];if(l){let{peerIdFromString:u}=await Promise.resolve().then(()=>(ce(),o0)),h=u(l);if(!this.isBlacklisted(h))return h}}}let n=(s.getConnections?.()??[]).map(a=>a.remotePeer),o=[s.peerId,...n,...this.getKnownPeers()].filter((a,c,l)=>l.findIndex(u=>u.toString()===a.toString())===c).filter(a=>!this.isBlacklisted(a));return o.length===0?s.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),s=this.clusterCache.get(t);if(s&&s.expires>Date.now())return s.ids;let n=this.getFret(),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");if(n){let f=await rr(e),p=n.getDiagnostics?.()??{},m=typeof p.estimate=="number"?p.estimate:typeof p.n=="number"?p.n:void 0,g=Math.max(1,Math.min(this.cfg.clusterSize,Number.isFinite(m)?m:this.cfg.clusterSize)),y=n.assembleCohort(f,g),{peerIdFromString:b}=await Promise.resolve().then(()=>(ce(),o0)),w=y.map(x=>{try{return b(x)}catch(E){return this.log("Invalid peer ID in cohort: %s, %o",x,E),null}}).filter(x=>x!==null&&!this.isBlacklisted(x));if(w.length>0)return this.clusterCache.set(t,{ids:w,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),this.lastEstimate=m!=null?{estimate:m,samples:p.samples??0,updated:Date.now()}:this.lastEstimate,w}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,p,m)=>!this.isBlacklisted(f)&&m.findIndex(g=>g.toString()===f.toString())===p).sort((f,p)=>this.lexLess(this.xor(f.toMultihash().bytes,a),this.xor(p.toMultihash().bytes,a))?-1:1),h=Math.min(this.cfg.clusterSize,u.length),d=u.slice(0,h);return this.clusterCache.set(t,{ids:d,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),d}async getCoordinator(e){let t=this.toCacheKey(e),s=this.coordinatorCache.get(t);if(s){if(s.expires>Date.now())return s.id;this.coordinatorCache.delete(t)}let n=await this.getCluster(e),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");let i=n.find(a=>!this.isBlacklisted(a))??o.peerId;return this.recordCoordinator(e,i),i}xor(e,t){let s=Math.max(e.length,t.length),n=new Uint8Array(s);for(let o=0;o<s;o++){let i=e[e.length-1-o]??0,a=t[t.length-1-o]??0;n[s-1-o]=i^a}return n}lexLess(e,t){let s=Math.max(e.length,t.length);for(let n=0;n<s;n++){let o=e[n]??0,i=t[n]??0;if(o<i)return!0;if(o>i)return!1}return!1}};function a3(r={}){return e=>new j1(e,r)}var Y1=class{peerStatuses=new Map;unreachableThreshold=3;rapidChurnThreshold=5;rapidChurnWindow=1e4;peerTimeoutMs=6e4;recordSuccess(e){let t=Date.now(),s=this.peerStatuses.get(e);s?(s.lastSeen=t,s.consecutiveFailures=0):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:0}),this.cleanupOldPeers()}recordFailure(e){let t=Date.now(),s=this.peerStatuses.get(e);s?(s.consecutiveFailures++,s.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:1})}recordGoodbye(e){let t=Date.now(),s=this.peerStatuses.get(e);s?(s.lastGoodbye=t,s.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,lastGoodbye:t,consecutiveFailures:0})}detectPartition(){let e=Date.now(),t=this.getRecentGoodbyes(this.rapidChurnWindow),s=Array.from(this.peerStatuses.values()).filter(o=>o.consecutiveFailures>=this.unreachableThreshold&&!o.lastGoodbye);return t.length+s.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(s=>s.lastGoodbye&&s.lastGoodbye>t)}cleanupOldPeers(){let e=Date.now()-this.peerTimeoutMs;for(let[t,s]of this.peerStatuses.entries())s.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()}};async function GD(r){let e=r.storageType??"memory",t;if(e==="file"){if(!r.storagePath)throw new Error('storagePath is required when storageType is "file"');t=new oc(r.storagePath)}else t=new ic;let s=async(w,x)=>{},n=new ac(w=>new Ei(w,t,s)),o,i,a={async update(w){if(!o)throw new Error("ClusterMember not initialized");return await o.update(w)}},c={async get(w,x){return await(i??n).get(w,x)},async pend(w,x){return await(i??n).pend(w,x)},async cancel(w,x){return await(i??n).cancel(w,x)},async commit(w,x){return await(i??n).commit(w,x)}},l=r.id?await G(r.id):void 0,u={start:!1,...l?{peerId:l}:{},addresses:{listen:[`/ip4/0.0.0.0/tcp/${r.port}`]},connectionManager:{autoDial:!0,minConnections:1,maxConnections:16,inboundConnectionUpgradeTimeout:1e4,dialQueue:{concurrency:2,attempts:2}},transports:[nx(),i3()],connectionEncrypters:[qv()],streamMuxers:[eE()],services:{identify:iE({protocolPrefix:`/optimystic/${r.networkName}`}),ping:uE(),pubsub:BE({allowPublishToZeroTopicPeers:!0,heartbeatInterval:7e3}),...r.relay?{relay:r3()}:{},cluster:w=>z0({protocolPrefix:`/optimystic/${r.networkName}`,configuredClusterSize:r.clusterSize??10,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})({logger:w.logger,registrar:w.registrar,cluster:a}),repo:w=>G0({protocolPrefix:`/optimystic/${r.networkName}`})({logger:w.logger,registrar:w.registrar,repo:c}),sync:w=>T2({protocolPrefix:`/optimystic/${r.networkName}`})({logger:w.logger,registrar:w.registrar,repo:c}),networkManager:w=>{let E=a3({clusterSize:r.clusterSize??10,expectedRemotes:(r.bootstrapNodes?.length??0)>0,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})(w);try{E.setLibp2p?.(w.libp2p)}catch{}return E},fret:w=>{let E=A2({k:15,m:8,capacity:2048,profile:r.fretProfile??((r.bootstrapNodes?.length??0)>0?"core":"edge"),networkName:r.networkName,bootstraps:r.bootstrapNodes??[]})(w);try{E.setLibp2p(w.libp2p)}catch{}return E}},peerDiscovery:[...r.bootstrapNodes?.length?[jE({list:r.bootstrapNodes})]:[]]},h=await Gw(u);try{h.services?.fret?.setLibp2p?.(h)}catch{}try{h.services?.networkManager?.setLibp2p?.(h)}catch{}await h.start();let d=new Ec(h),f=`/optimystic/${r.networkName}`,p=w=>Hn.create(w,d,f),m=new Y1,g=h.services?.fret;if(o=H0({storageRepo:n,peerNetwork:d,peerId:h.peerId,protocolPrefix:f,partitionDetector:m,fretService:g,validator:r.validator}),i=$0(d,p,{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},g)({storageRepo:n,localCluster:o,localPeerId:h.peerId}),r.arachnode?.enableRingZulu??!0){let w=h.logger?.forComponent?.("db-p2p:arachnode"),x=h.services?.fret;if(x){let E=new vc(x),P=new xc(t,r.arachnode?.storage??{}),C=new wc(E,P,{minCapacity:100*1024*1024,thresholds:{moveOut:.85,moveIn:.4}}),D=h.peerId.toString(),v=await C.createArachnodeInfo(D);E.setArachnodeInfo(v),w?.("Announced Arachnode membership: Ring %d",v.ringDepth);let M=new bc(E,{connect:(S,_)=>h.dialProtocol(S,[_])},`/optimystic/${r.networkName}`),F=async(S,_)=>await M.restore(S,_);n.createBlockStorage=S=>new Ei(S,t,F);let B=setInterval(async()=>{let S=await C.shouldTransition();if(S.shouldMove){w?.("Ring transition needed: moving %s to Ring %d",S.direction,S.newRingDepth);let _=await C.createArachnodeInfo(D);E.setArachnodeInfo(_)}},6e4),I=h.stop.bind(h);h.stop=async()=>{clearInterval(B),await I()}}else w?.("FRET service not available, Arachnode disabled")}return h.coordinatedRepo=i,h.storageRepo=n,h.keyNetwork=d,h}function pS(r,e){let t=Math.max(r.length,e.length),s=new Uint8Array(t);for(let n=0;n<t;n++){let o=r[r.length-1-n]??0,i=e[e.length-1-n]??0;s[t-1-n]=o^i}return s}function mS(r,e){let t=Math.max(r.length,e.length);for(let s=0;s<t;s++){let n=r[s]??0,o=e[s]??0;if(n<o)return!0;if(n>o)return!1}return!1}function gS(r,e){return r.map(t=>({p:t,d:pS(t.id.toMultihash().bytes,e)})).sort((t,s)=>mS(t.d,s.d)?-1:1).map(t=>t.p)}function VD(r,e,t,s){let n=[e,...t],o=gS(n,r);if(n.length<=3)return{inCluster:o[0].id.equals(e.id),nearest:o};let i=Math.min(s,Math.max(1,Math.floor(n.length/2))),a=o.slice(0,i);return{inCluster:a.some(l=>l.id.equals(e.id)),nearest:a}}function WD(r){let e={id:r.peerId,addrs:r.getMultiaddrs().map(o=>o.toString())},t=r.getConnections(),s={};for(let o of t){let i=o.remotePeer,a=i.toString(),c=s[a]??(s[a]={id:i,addrs:new Set}),l=o.remoteAddr?.toString?.();l&&c.addrs.add(l)}let n=Object.values(s).map(o=>({id:o.id,addrs:Array.from(o.addrs)}));return[e,...n]}var jD=yr("network:get-manager");function YD(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){jD("getNetworkManager setLibp2p failed - %o",t)}return e}return ES(XD);})();
29
29
  /*! Bundled license information:
30
30
 
31
31
  @noble/hashes/utils.js: