@streamr/sdk 103.3.1 → 103.6.0-rc.0

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.
@@ -59,7 +59,13 @@ const aI=BigInt(0),cI=BigInt(1);function uI(e){return function(e){const t=nI.red
59
59
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function bI(e){return{hash:e,hmac:(t,...r)=>Lk(e,t,function(...e){const t=new Uint8Array(e.reduce(((e,t)=>e+t.length),0));let r=0;return e.forEach((e=>{if(!kk(e))throw new Error("Uint8Array expected");t.set(e,r),r+=e.length})),t}(...r)),randomBytes:Dk}}BigInt(4);
60
60
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
61
61
  const wI=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),vI=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),EI=BigInt(1),AI=BigInt(2),SI=(e,t)=>(e+t/AI)/t;const kI=function(e,t,r=!1,n={}){if(e<=VC)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:i,nByteLength:s}=iI(e,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=rI(e),a=Object.freeze({ORDER:e,BITS:i,BYTES:s,MASK:FC(i),ZERO:VC,ONE:HC,create:t=>YC(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("Invalid field element: expected bigint, got "+typeof t);return VC<=t&&t<e},is0:e=>e===VC,isOdd:e=>(e&HC)===HC,neg:t=>YC(-t,e),eql:(e,t)=>e===t,sqr:t=>YC(t*t,e),add:(t,r)=>YC(t+r,e),sub:(t,r)=>YC(t-r,e),mul:(t,r)=>YC(t*r,e),pow:(e,t)=>function(e,t,r){if(r<VC)throw new Error("Expected power > 0");if(r===VC)return e.ONE;if(r===HC)return t;let n=e.ONE,i=t;for(;r>VC;)r&HC&&(n=e.mul(n,i)),i=e.sqr(i),r>>=HC;return n}(a,e,t),div:(t,r)=>YC(t*tI(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>tI(t,e),sqrt:n.sqrt||(e=>o(a,e)),invertBatch:e=>function(e,t){const r=new Array(t.length),n=t.reduce(((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n))),e.ONE),i=e.inv(n);return t.reduceRight(((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n))),i),r}(a,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?DC(e,s):OC(e,s),fromBytes:e=>{if(e.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${e.length}`);return r?xC(e):MC(e)}});return Object.freeze(a)}(wI,void 0,void 0,{sqrt:function(e){const t=wI,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,l=u*u*e%t,h=eI(l,r,t)*l%t,d=eI(h,r,t)*l%t,f=eI(d,AI,t)*u%t,p=eI(f,i,t)*f%t,g=eI(p,s,t)*p%t,m=eI(g,a,t)*g%t,y=eI(m,c,t)*m%t,b=eI(y,a,t)*g%t,w=eI(b,r,t)*l%t,v=eI(w,o,t)*p%t,E=eI(v,n,t)*u%t,A=eI(E,AI,t);if(!kI.eql(kI.sqr(A),e))throw new Error("Cannot find square root");return A}}),RI=function(e,t){const r=t=>yI({...e,...bI(t)});return Object.freeze({...r(t),create:r})}({a:BigInt(0),b:BigInt(7),Fp:kI,n:vI,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=vI,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-EI*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=SI(s*e,t),c=SI(-n*e,t);let u=YC(e-a*r-c*i,t),l=YC(-a*n-c*s,t);const h=u>o,d=l>o;if(h&&(u=t-u),d&&(l=t-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:u,k2neg:d,k2:l}}}},$k);BigInt(0),RI.ProjectivePoint;const CI="0x0000000000000000000000000000000000000000",II="0x0000000000000000000000000000000000000000000000000000000000000000";BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),BigInt("1000000000000000000");const PI=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");BigInt("0x8000000000000000000000000000000000000000000000000000000000000000"),BigInt(-1),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const TI=BigInt(0),_I=BigInt(1),NI=BigInt(2),MI=BigInt(27),xI=BigInt(28),OI=BigInt(35),DI={};function BI(e){return ZA(lS(e),32)}class LI{#z;#K;#G;#V;get r(){return this.#z}set r(e){DA(32===WA(e),"invalid r","value",e),this.#z=HA(e)}get s(){return this.#K}set s(e){DA(32===WA(e),"invalid s","value",e);const t=HA(e);DA(parseInt(t.substring(0,3))<8,"non-canonical s","value",t),this.#K=t}get v(){return this.#G}set v(e){const t=cS(e,"value");DA(27===t||28===t,"invalid v","v",e),this.#G=t}get networkV(){return this.#V}get legacyChainId(){const e=this.networkV;return null==e?null:LI.getChainId(e)}get yParity(){return 27===this.v?0:1}get yParityAndS(){const e=qA(this.s);return this.yParity&&(e[0]|=128),HA(e)}get compactSerialized(){return $A([this.r,this.yParityAndS])}get serialized(){return $A([this.r,this.s,this.yParity?"0x1c":"0x1b"])}constructor(e,t,r,n){UA(e,DI,"Signature"),this.#z=t,this.#K=r,this.#G=n,this.#V=null}[Symbol.for("nodejs.util.inspect.custom")](){return`Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`}clone(){const e=new LI(DI,this.r,this.s,this.v);return this.networkV&&(e.#V=this.networkV),e}toJSON(){const e=this.networkV;return{_type:"signature",networkV:null!=e?e.toString():null,r:this.r,s:this.s,v:this.v}}static getChainId(e){const t=iS(e,"v");return t==MI||t==xI?TI:(DA(t>=OI,"invalid EIP-155 v","v",e),(t-OI)/NI)}static getChainIdV(e,t){return iS(e)*NI+BigInt(35+t-27)}static getNormalizedV(e){const t=iS(e);return t===TI||t===MI?27:t===_I||t===xI?28:(DA(t>=OI,"invalid v","v",e),t&_I?27:28)}static from(e){function t(t,r){DA(t,r,"signature",e)}if(null==e)return new LI(DI,II,II,27);if("string"==typeof e){const r=qA(e,"signature");if(64===r.length){const e=HA(r.slice(0,32)),t=r.slice(32,64),n=128&t[0]?28:27;return t[0]&=127,new LI(DI,e,HA(t),n)}if(65===r.length){const e=HA(r.slice(0,32)),n=r.slice(32,64);t(!(128&n[0]),"non-canonical s");const i=LI.getNormalizedV(r[64]);return new LI(DI,e,HA(n),i)}t(!1,"invalid raw signature length")}if(e instanceof LI)return e.clone();const r=e.r;t(null!=r,"missing r");const n=BI(r),i=function(e,r){if(null!=e)return BI(e);if(null!=r){t(KA(r,32),"invalid yParityAndS");const e=qA(r);return e[0]&=127,HA(e)}t(!1,"missing s")}(e.s,e.yParityAndS);t(!(128&qA(i)[0]),"non-canonical s");const{networkV:s,v:o}=function(e,r,n){if(null!=e){const t=iS(e);return{networkV:t>=OI?t:void 0,v:LI.getNormalizedV(t)}}if(null!=r)return t(KA(r,32),"invalid yParityAndS"),{v:128&qA(r)[0]?28:27};if(null!=n){switch(cS(n,"sig.yParity")){case 0:return{v:27};case 1:return{v:28}}t(!1,"invalid yParity")}t(!1,"missing v")}(e.v,e.yParityAndS,e.yParity),a=new LI(DI,n,i,o);return s&&(a.#V=s),t(null==e.yParity||cS(e.yParity,"sig.yParity")===a.yParity,"yParity mismatch"),t(null==e.yParityAndS||e.yParityAndS===a.yParityAndS,"yParityAndS mismatch"),a}}class FI{#H;constructor(e){DA(32===WA(e),"invalid private key","privateKey","[REDACTED]"),this.#H=HA(e)}get privateKey(){return this.#H}get publicKey(){return FI.computePublicKey(this.#H)}get compressedPublicKey(){return FI.computePublicKey(this.#H,!0)}sign(e){DA(32===WA(e),"invalid digest length","digest",e);const t=RI.sign(zA(e),zA(this.#H),{lowS:!0});return LI.from({r:uS(t.r,32),s:uS(t.s,32),v:t.recovery?28:27})}computeSharedSecret(e){const t=FI.computePublicKey(e);return HA(RI.getSharedSecret(zA(this.#H),qA(t),!1))}static computePublicKey(e,t){let r=qA(e,"key");if(32===r.length){return HA(RI.getPublicKey(r,!!t))}if(64===r.length){const e=new Uint8Array(65);e[0]=4,e.set(r,1),r=e}return HA(RI.ProjectivePoint.fromHex(r).toRawBytes(t))}static recoverPublicKey(e,t){DA(32===WA(e),"invalid digest length","digest",e);const r=LI.from(t);let n=RI.Signature.fromCompact(zA($A([r.r,r.s])));n=n.addRecoveryBit(r.yParity);const i=n.recoverPublicKey(zA(e));return DA(null!=i,"invalid signautre for digest","signature",t),"0x"+i.toHex(!1)}static addPoints(e,t,r){const n=RI.ProjectivePoint.fromHex(FI.computePublicKey(e).substring(2)),i=RI.ProjectivePoint.fromHex(FI.computePublicKey(t).substring(2));return"0x"+n.add(i).toHex(!!r)}}const UI=BigInt(0),jI=BigInt(36);function qI(e){const t=(e=e.toLowerCase()).substring(2).split(""),r=new Uint8Array(40);for(let e=0;e<40;e++)r[e]=t[e].charCodeAt(0);const n=qA(xR(r));for(let e=0;e<40;e+=2)n[e>>1]>>4>=8&&(t[e]=t[e].toUpperCase()),(15&n[e>>1])>=8&&(t[e+1]=t[e+1].toUpperCase());return"0x"+t.join("")}const zI={};for(let e=0;e<10;e++)zI[String(e)]=String(e);for(let e=0;e<26;e++)zI[String.fromCharCode(65+e)]=String(10+e);const KI=function(){const e={};for(let t=0;t<36;t++){e["0123456789abcdefghijklmnopqrstuvwxyz"[t]]=BigInt(t)}return e}();function GI(e){if(DA("string"==typeof e,"invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/)){e.startsWith("0x")||(e="0x"+e);const t=qI(e);return DA(!e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||t===e,"bad address checksum","address",e),t}if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){DA(e.substring(2,4)===function(e){let t=(e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00").split("").map((e=>zI[e])).join("");for(;t.length>=15;){let e=t.substring(0,15);t=parseInt(e,10)%97+t.substring(e.length)}let r=String(98-parseInt(t,10)%97);for(;r.length<2;)r="0"+r;return r}(e),"bad icap checksum","address",e);let t=function(e){e=e.toLowerCase();let t=UI;for(let r=0;r<e.length;r++)t=t*jI+KI[e[r]];return t}(e.substring(4)).toString(16);for(;t.length<40;)t="0"+t;return qI("0x"+t)}DA(!1,"invalid address","address",e)}function VI(e){return e&&"function"==typeof e.getAddress}async function HI(e,t){const r=await t;return null!=r&&"0x0000000000000000000000000000000000000000"!==r||(OA("string"!=typeof e,"unconfigured name","UNCONFIGURED_NAME",{value:e}),DA(!1,"invalid AddressLike value; did not resolve to a value address","target",e)),GI(r)}function $I(e,t){return"string"==typeof e?e.match(/^0x[0-9a-f]{40}$/i)?GI(e):(OA(null!=t,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),HI(e,t.resolveName(e))):VI(e)?HI(e,e.getAddress()):e&&"function"==typeof e.then?HI(e,e):void DA(!1,"unsupported addressable value","target",e)}const WI={};function JI(e,t){let r=!1;return t<0&&(r=!0,t*=-1),new YI(WI,`${r?"":"u"}int${t}`,e,{signed:r,width:t})}function QI(e,t){return new YI(WI,`bytes${t||""}`,e,{size:t})}const ZI=Symbol.for("_ethers_typed");class YI{type;value;#$;_typedSymbol;constructor(e,t,r,n){null==n&&(n=null),UA(WI,e,"Typed"),TA(this,{_typedSymbol:ZI,type:t,value:r}),this.#$=n,this.format()}format(){if("array"===this.type)throw new Error("");if("dynamicArray"===this.type)throw new Error("");return"tuple"===this.type?`tuple(${this.value.map((e=>e.format())).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return"string"===this.type}get tupleName(){if("tuple"!==this.type)throw TypeError("not a tuple");return this.#$}get arrayLength(){if("array"!==this.type)throw TypeError("not an array");return!0===this.#$?-1:!1===this.#$?this.value.length:null}static from(e,t){return new YI(WI,e,t)}static uint8(e){return JI(e,8)}static uint16(e){return JI(e,16)}static uint24(e){return JI(e,24)}static uint32(e){return JI(e,32)}static uint40(e){return JI(e,40)}static uint48(e){return JI(e,48)}static uint56(e){return JI(e,56)}static uint64(e){return JI(e,64)}static uint72(e){return JI(e,72)}static uint80(e){return JI(e,80)}static uint88(e){return JI(e,88)}static uint96(e){return JI(e,96)}static uint104(e){return JI(e,104)}static uint112(e){return JI(e,112)}static uint120(e){return JI(e,120)}static uint128(e){return JI(e,128)}static uint136(e){return JI(e,136)}static uint144(e){return JI(e,144)}static uint152(e){return JI(e,152)}static uint160(e){return JI(e,160)}static uint168(e){return JI(e,168)}static uint176(e){return JI(e,176)}static uint184(e){return JI(e,184)}static uint192(e){return JI(e,192)}static uint200(e){return JI(e,200)}static uint208(e){return JI(e,208)}static uint216(e){return JI(e,216)}static uint224(e){return JI(e,224)}static uint232(e){return JI(e,232)}static uint240(e){return JI(e,240)}static uint248(e){return JI(e,248)}static uint256(e){return JI(e,256)}static uint(e){return JI(e,256)}static int8(e){return JI(e,-8)}static int16(e){return JI(e,-16)}static int24(e){return JI(e,-24)}static int32(e){return JI(e,-32)}static int40(e){return JI(e,-40)}static int48(e){return JI(e,-48)}static int56(e){return JI(e,-56)}static int64(e){return JI(e,-64)}static int72(e){return JI(e,-72)}static int80(e){return JI(e,-80)}static int88(e){return JI(e,-88)}static int96(e){return JI(e,-96)}static int104(e){return JI(e,-104)}static int112(e){return JI(e,-112)}static int120(e){return JI(e,-120)}static int128(e){return JI(e,-128)}static int136(e){return JI(e,-136)}static int144(e){return JI(e,-144)}static int152(e){return JI(e,-152)}static int160(e){return JI(e,-160)}static int168(e){return JI(e,-168)}static int176(e){return JI(e,-176)}static int184(e){return JI(e,-184)}static int192(e){return JI(e,-192)}static int200(e){return JI(e,-200)}static int208(e){return JI(e,-208)}static int216(e){return JI(e,-216)}static int224(e){return JI(e,-224)}static int232(e){return JI(e,-232)}static int240(e){return JI(e,-240)}static int248(e){return JI(e,-248)}static int256(e){return JI(e,-256)}static int(e){return JI(e,-256)}static bytes1(e){return QI(e,1)}static bytes2(e){return QI(e,2)}static bytes3(e){return QI(e,3)}static bytes4(e){return QI(e,4)}static bytes5(e){return QI(e,5)}static bytes6(e){return QI(e,6)}static bytes7(e){return QI(e,7)}static bytes8(e){return QI(e,8)}static bytes9(e){return QI(e,9)}static bytes10(e){return QI(e,10)}static bytes11(e){return QI(e,11)}static bytes12(e){return QI(e,12)}static bytes13(e){return QI(e,13)}static bytes14(e){return QI(e,14)}static bytes15(e){return QI(e,15)}static bytes16(e){return QI(e,16)}static bytes17(e){return QI(e,17)}static bytes18(e){return QI(e,18)}static bytes19(e){return QI(e,19)}static bytes20(e){return QI(e,20)}static bytes21(e){return QI(e,21)}static bytes22(e){return QI(e,22)}static bytes23(e){return QI(e,23)}static bytes24(e){return QI(e,24)}static bytes25(e){return QI(e,25)}static bytes26(e){return QI(e,26)}static bytes27(e){return QI(e,27)}static bytes28(e){return QI(e,28)}static bytes29(e){return QI(e,29)}static bytes30(e){return QI(e,30)}static bytes31(e){return QI(e,31)}static bytes32(e){return QI(e,32)}static address(e){return new YI(WI,"address",e)}static bool(e){return new YI(WI,"bool",!!e)}static bytes(e){return new YI(WI,"bytes",e)}static string(e){return new YI(WI,"string",e)}static array(e,t){throw new Error("not implemented yet")}static tuple(e,t){throw new Error("not implemented yet")}static overrides(e){return new YI(WI,"overrides",Object.assign({},e))}static isTyped(e){return e&&"object"==typeof e&&"_typedSymbol"in e&&e._typedSymbol===ZI}static dereference(e,t){if(YI.isTyped(e)){if(e.type!==t)throw new Error(`invalid type: expecetd ${t}, got ${e.type}`);return e.value}return e}}class XI extends gk{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){let r=YI.dereference(t,"string");try{r=GI(r)}catch(e){return this._throwError(e.message,t)}return e.writeValue(r)}decode(e){return GI(uS(e.readValue(),20))}}class eP extends gk{coder;constructor(e){super(e.name,e.type,"_",e.dynamic),this.coder=e}defaultValue(){return this.coder.defaultValue()}encode(e,t){return this.coder.encode(e,t)}decode(e){return this.coder.decode(e)}}function tP(e,t,r){let n=[];if(Array.isArray(r))n=r;else if(r&&"object"==typeof r){let e={};n=t.map((t=>{const n=t.localName;return OA(n,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:r}),OA(!e[n],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:r}),e[n]=!0,r[n]}))}else DA(!1,"invalid tuple value","tuple",r);DA(t.length===n.length,"types/value length mismatch","tuple",r);let i=new mk,s=new mk,o=[];t.forEach(((e,t)=>{let r=n[t];if(e.dynamic){let t=s.length;e.encode(s,r);let n=i.writeUpdatableValue();o.push((e=>{n(e+t)}))}else e.encode(i,r)})),o.forEach((e=>{e(i.length)}));let a=e.appendWriter(i);return a+=e.appendWriter(s),a}function rP(e,t){let r=[],n=[],i=e.subReader(0);return t.forEach((t=>{let s=null;if(t.dynamic){let r=e.readIndex(),n=i.subReader(r);try{s=t.decode(n)}catch(e){if(NA(e,"BUFFER_OVERRUN"))throw e;s=e,s.baseType=t.name,s.name=t.localName,s.type=t.type}}else try{s=t.decode(e)}catch(e){if(NA(e,"BUFFER_OVERRUN"))throw e;s=e,s.baseType=t.name,s.name=t.localName,s.type=t.type}if(null==s)throw new Error("investigate");r.push(s),n.push(t.localName||null)})),fk.fromItems(r,n)}class nP extends gk{coder;length;constructor(e,t,r){super("array",e.type+"["+(t>=0?t:"")+"]",r,-1===t||e.dynamic),TA(this,{coder:e,length:t})}defaultValue(){const e=this.coder.defaultValue(),t=[];for(let r=0;r<this.length;r++)t.push(e);return t}encode(e,t){const r=YI.dereference(t,"array");Array.isArray(r)||this._throwError("expected array value",r);let n=this.length;-1===n&&(n=r.length,e.writeValue(r.length)),BA(r.length,n,"coder array"+(this.localName?" "+this.localName:""));let i=[];for(let e=0;e<r.length;e++)i.push(this.coder);return tP(e,i,r)}decode(e){let t=this.length;-1===t&&(t=e.readIndex(),OA(t*ik<=e.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:e.bytes,offset:t*ik,length:e.dataLength}));let r=[];for(let e=0;e<t;e++)r.push(new eP(this.coder));return rP(e,r)}}class iP extends gk{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){const r=YI.dereference(t,"bool");return e.writeValue(r?1:0)}decode(e){return!!e.readValue()}}class sP extends gk{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=zA(t);let r=e.writeValue(t.length);return r+=e.writeBytes(t),r}decode(e){return e.readBytes(e.readIndex(),!0)}}class oP extends sP{constructor(e){super("bytes",e)}decode(e){return HA(super.decode(e))}}class aP extends gk{size;constructor(e,t){let r="bytes"+String(e);super(r,r,t,!1),TA(this,{size:e},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+2*this.size)}encode(e,t){let r=zA(YI.dereference(t,this.type));return r.length!==this.size&&this._throwError("incorrect data length",t),e.writeBytes(r)}decode(e){return HA(e.readBytes(this.size))}}const cP=new Uint8Array([]);class uP extends gk{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return null!=t&&this._throwError("not null",t),e.writeBytes(cP)}decode(e){return e.readBytes(0),null}}const lP=BigInt(0),hP=BigInt(1),dP=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class fP extends gk{size;signed;constructor(e,t,r){const n=(t?"int":"uint")+8*e;super(n,n,r,!1),TA(this,{size:e,signed:t},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(e,t){let r=iS(YI.dereference(t,this.type)),n=nS(dP,256);if(this.signed){let e=nS(n,8*this.size-1);(r>e||r<-(e+hP))&&this._throwError("value out-of-bounds",t),r=rS(r,256)}else(r<lP||r>nS(n,8*this.size))&&this._throwError("value out-of-bounds",t);return e.writeValue(r)}decode(e){let t=nS(e.readValue(),8*this.size);return this.signed&&(t=tS(t,8*this.size)),t}}class pP extends sP{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,ES(YI.dereference(t,"string")))}decode(e){return AS(super.decode(e))}}class gP extends gk{coders;constructor(e,t){let r=!1;const n=[];e.forEach((e=>{e.dynamic&&(r=!0),n.push(e.type)}));super("tuple","tuple("+n.join(",")+")",t,r),TA(this,{coders:Object.freeze(e.slice())})}defaultValue(){const e=[];this.coders.forEach((t=>{e.push(t.defaultValue())}));const t=this.coders.reduce(((e,t)=>{const r=t.localName;return r&&(e[r]||(e[r]=0),e[r]++),e}),{});return this.coders.forEach(((r,n)=>{let i=r.localName;i&&1===t[i]&&("length"===i&&(i="_length"),null==e[i]&&(e[i]=e[n]))})),Object.freeze(e)}encode(e,t){const r=YI.dereference(t,"tuple");return tP(e,this.coders,r)}decode(e){return rP(e,this.coders)}}function mP(e){return xR(ES(e))}const yP=new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]);function bP(e){return function(e){let t=0;return()=>e[t++]}(function(e){let t=0;function r(){return e[t++]<<8|e[t++]}let n=r(),i=1,s=[0,1];for(let e=1;e<n;e++)s.push(i+=r());let o=r(),a=t;t+=o;let c=0,u=0;function l(){return 0==c&&(u=u<<8|e[t++],c=8),u>>--c&1}const h=2**31,d=h>>>1,f=d>>1,p=h-1;let g=0;for(let e=0;e<31;e++)g=g<<1|l();let m=[],y=0,b=h;for(;;){let e=Math.floor(((g-y+1)*i-1)/b),t=0,r=n;for(;r-t>1;){let n=t+r>>>1;e<s[n]?r=n:t=n}if(0==t)break;m.push(t);let o=y+Math.floor(b*s[t]/i),a=y+Math.floor(b*s[t+1]/i)-1;for(;!((o^a)&d);)g=g<<1&p|l(),o=o<<1&p,a=a<<1&p|1;for(;o&~a&f;)g=g&d|g<<1&p>>>1|l(),o=o<<1^d,a=(a^d)<<1|d|1;y=o,b=1+a-o}let w=n-4;return m.map((t=>{switch(t-w){case 3:return w+65792+(e[a++]<<16|e[a++]<<8|e[a++]);case 2:return w+256+(e[a++]<<8|e[a++]);case 1:return w+e[a++];default:return t-1}}))}(function(e){let t=[];[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach(((e,r)=>t[e.charCodeAt(0)]=r));let r=e.length,n=new Uint8Array(6*r>>3);for(let i=0,s=0,o=0,a=0;i<r;i++)a=a<<6|t[e.charCodeAt(i)],o+=6,o>=8&&(n[s++]=a>>(o-=8));return n}(e)))}function wP(e){return 1&e?~e>>1:e>>1}function vP(e,t){let r=Array(e);for(let n=0,i=0;n<e;n++)r[n]=i+=wP(t());return r}function EP(e,t=0){let r=[];for(;;){let n=e(),i=e();if(!i)break;t+=n;for(let e=0;e<i;e++)r.push(t+e);t+=i+1}return r}function AP(e){return kP((()=>{let t=EP(e);if(t.length)return t}))}function SP(e){let t=[];for(;;){let r=e();if(0==r)break;t.push(CP(r,e))}for(;;){let r=e()-1;if(r<0)break;t.push(IP(r,e))}return t.flat()}function kP(e){let t=[];for(;;){let r=e(t.length);if(!r)break;t.push(r)}return t}function RP(e,t,r){let n=Array(e).fill().map((()=>[]));for(let i=0;i<t;i++)vP(e,r).forEach(((e,t)=>n[t].push(e)));return n}function CP(e,t){let r=1+t(),n=t(),i=kP(t);return RP(i.length,1+e,t).flatMap(((e,t)=>{let[s,...o]=e;return Array(i[t]).fill().map(((e,t)=>{let i=t*n;return[s+t*r,o.map((e=>e+i))]}))}))}function IP(e,t){return RP(1+t(),1+e,t).map((e=>[e[0],e.slice(1)]))}function PP(e){return`{${function(e){return e.toString(16).toUpperCase().padStart(2,"0")}(e)}}`}function TP(e){let t=e.length;if(t<4096)return String.fromCodePoint(...e);let r=[];for(let n=0;n<t;)r.push(String.fromCodePoint(...e.slice(n,n+=4096)));return r.join("")}function _P(e,t){let r=e.length,n=r-t.length;for(let i=0;0==n&&i<r;i++)n=e[i]-t[i];return n}const NP=44032,MP=4352,xP=4449,OP=4519,DP=28,BP=588;function LP(e){return e>>24&255}function FP(e){return 16777215&e}let UP,jP,qP,zP;function KP(e){return e>=NP&&e<55204}function GP(e,t){if(e>=MP&&e<4371&&t>=xP&&t<4470)return NP+(e-MP)*BP+(t-xP)*DP;if(KP(e)&&t>OP&&t<4547&&(e-NP)%DP==0)return e+(t-OP);{let r=zP.get(e);return r&&(r=r.get(t),r)?r:-1}}function VP(e){UP||function(){let e=bP("AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFLoSMEEEl5RFVMKvO0XQ8ExDdJMnIgsj26PTQyy8FfEQ8AY8IPAGcEbwRwBHEEcgRzBHQEdQR2BHcEeAR6BHsEfAR+BIAEgfndBQoBYgULAWIFDAFiBNcE2ATZBRAFEQUvBdALFAsVDPcNBw13DYcOMA4xDjMB4BllHI0B2grbAMDpHLkQ7QHVAPRNQQFnGRUEg0yEB2uaJF8AJpIBpob5AERSMAKNoAXqaQLUBMCzEiACnwRZEkkVsS7tANAsBG0RuAQLEPABv9HICTUBXigPZwRBApMDOwAamhtaABqEAY8KvKx3LQ4ArAB8UhwEBAVSagD8AEFZADkBIadVj2UMUgx5Il4ANQC9AxIB1BlbEPMAs30CGxlXAhwZKQIECBc6EbsCoxngzv7UzRQA8M0BawL6ZwkN7wABAD33OQRcsgLJCjMCjqUChtw/km+NAsXPAoP2BT84PwURAK0RAvptb6cApQS/OMMey5HJS84UdxpxTPkCogVFITaTOwERAK5pAvkNBOVyA7q3BKlOJSALAgUIBRcEdASpBXqzABXFSWZOawLCOqw//AolCZdvv3dSBkEQGyelEPcMMwG1ATsN7UvYBPEGOwTJH30ZGQ/NlZwIpS3dDO0m4y6hgFoj9SqDBe1L9DzdC01RaA9ZC2UJ4zpjgU4DIQENIosK3Q05CG0Q8wrJaw3lEUUHOQPVSZoApQcBCxEdNRW1JhBirAsJOXcG+xr2C48mrxMpevwF0xohBk0BKRr/AM8u54WwWjFcHE9fBgMLJSPHFKhQIA0lQLd4SBobBxUlqQKRQ3BKh1E2HpMh9jw9DWYuE1F8B/U8BRlPC4E8nkarRQ4R0j6NPUgiSUwsBDV/LC8niwnPD4UMuXxyAVkJIQmxDHETMREXN8UIOQcZLZckJxUIIUaVYJoE958D8xPRAwsFPwlBBxMDtRwtEy4VKQUNgSTXAvM21S6zAo9WgAEXBcsPJR/fEFBH4A7pCJsCZQODJesALRUhABcimwhDYwBfj9hTBS7LCMdqbCN0A2cU52ERcweRDlcHpxwzFb8c4XDIXguGCCijrwlbAXUJmQFfBOMICTVbjKAgQWdTi1gYmyBhQT9d/AIxDGUVn0S9h3gCiw9rEhsBNQFzBzkNAQJ3Ee0RaxCVCOuGBDW1M/g6JQRPIYMgEQonA09szgsnJvkM+GkBoxJiAww0PXfuZ6tgtiQX/QcZMsVBYCHxC5JPzQycGsEYQlQuGeQHvwPzGvMn6kFXBf8DowMTOk0z7gS9C2kIiwk/AEkOoxcH1xhqCnGM0AExiwG3mQNXkYMCb48GNwcLAGcLhwV55QAdAqcIowAFAM8DVwA5Aq0HnQAZAIVBAT0DJy8BIeUCjwOTCDHLAZUvAfMpBBvDDBUA9zduSgLDsQKAamaiBd1YAo4CSTUBTSUEBU5HUQOvceEA2wBLBhPfRwEVq0rLGuNDAd9vKwDHAPsABTUHBUEBzQHzbQC3AV8LMQmis7UBTekpAIMAFWsB1wKJAN0ANQB/8QFTAE0FWfkF0wJPSQERMRgrV2EBuwMfATMBDQB5BsuNpckHHwRtB9MCEBsV4QLvLge1AQMi3xPNQsUCvd5VoWACZIECYkJbTa9bNyACofcCaJgCZgkCn4Q4GwsCZjsCZiYEbgR/A38TA36SOQY5dxc5gjojIwJsHQIyNjgKAm3HAm2u74ozZ0UrAWcA3gDhAEoFB5gMjQD+C8IADbUCdy8CdqI/AnlLQwJ4uh1c20WuRtcCfD8CesgCfQkCfPAFWQUgSABIfWMkAoFtAoAAAoAFAn+uSVhKWxUXSswC0QEC0MxLJwOITwOH5kTFkTIC8qFdAwMDrkvOTC0lA89NTE2vAos/AorYwRsHHUNnBbcCjjcCjlxAl4ECjtkCjlx4UbRTNQpS1FSFApP7ApMMAOkAHFUeVa9V0AYsGymVhjLheGZFOzkCl58C77JYIagAWSUClo8ClnycAKlZrFoJgU0AOwKWtQKWTlxEXNECmcsCmWRcyl0HGQKcmznCOp0CnBYCn5sCnriKAB0PMSoPAp3xAp6SALU9YTRh7wKe0wKgbgGpAp6fHwKeTqVjyGQnJSsCJ68CJn4CoPsCoEwCot0CocQCpi8Cpc4Cp/8AfQKn8mh8aLEAA0lqHGrRAqzjAqyuAq1nAq0CAlcdAlXcArHh1wMfTmyXArK9DQKy6Bds4G1jbUhfAyXNArZcOz9ukAMpRQK4XgK5RxUCuSp3cDZw4QK9GQK72nCWAzIRAr6IcgIDM3ECvhpzInNPAsPLAsMEc4J0SzVFdOADPKcDPJoDPb8CxXwCxkcCxhCJAshpUQLIRALJTwLJLgJknQLd0nh5YXiueSVL0AMYo2cCAmH0GfOVJHsLXpJeuxECz2sCz2wvS1PS8xOfAMatAs9zASnqA04SfksFAtwnAtuKAtJPA1JcA1NfAQEDVYyAiT8AyxbtYEWCHILTgs6DjQLaxwLZ3oQQhEmnPAOGpQAvA2QOhnFZ+QBVAt9lAt64c3cC4i/tFAHzMCcB9JsB8tKHAuvzAulweQLq+QLq5AD5RwG5Au6JAuuclqqXAwLuPwOF4Jh5cOBxoQLzAwBpA44WmZMC9xMDkW4DkocC95gC+dkC+GaaHJqruzebHgOdgwL++gEbADmfHJ+zAwWNA6ZqA6bZANHFAwZqoYiiBQkDDEkCwAA/AwDhQRdTARHzA2sHl2cFAJMtK7evvdsBiZkUfxEEOQH7KQUhDp0JnwCS/SlXxQL3AZ0AtwW5AG8LbUEuFCaNLgFDAYD8AbUmAHUDDgRtACwCFgyhAAAKAj0CagPdA34EkQEgRQUhfAoABQBEABMANhICdwEABdUDa+8KxQIA9wqfJ7+xt+UBkSFBQgHpFH8RNMCJAAQAGwBaAkUChIsABjpTOpSNbQC4Oo860ACNOME63AClAOgAywE6gTo7Ofw5+Tt2iTpbO56JOm85GAFWATMBbAUvNV01njWtNWY1dTW2NcU1gjWRNdI14TWeNa017jX9NbI1wTYCNhE1xjXVNhY2JzXeNe02LjY9Ni41LSE2OjY9Njw2yTcIBJA8VzY4Nt03IDcPNsogN4k3MAoEsDxnNiQ3GTdsOo03IULUQwdC4EMLHA8PCZsobShRVQYA6X8A6bABFCnXAukBowC9BbcAbwNzBL8MDAMMAQgDAAkKCwsLCQoGBAVVBI/DvwDz9b29kaUCb0QtsRTNLt4eGBcSHAMZFhYZEhYEARAEBUEcQRxBHEEcQRxBHEEaQRxBHEFCSTxBPElISUhBNkM2QTYbNklISVmBVIgBFLWZAu0BhQCjBcEAbykBvwGJAaQcEZ0ePCklMAAhMvAIMAL54gC7Bm8EescjzQMpARQpKgDUABavAj626xQAJP0A3etzuf4NNRA7efy2Z9NQrCnC0OSyANz5BBIbJ5IFDR6miIavYS6tprjjmuKebxm5C74Q225X1pkaYYPb6f1DK4k3xMEBb9S2WMjEibTNWhsRJIA+vwNVEiXTE5iXs/wezV66oFLfp9NZGYW+Gk19J2+bCT6Ye2w6LDYdgzKMUabk595eLBCXANz9HUpWbATq9vqXVx9XDg+Pc9Xp4+bsS005SVM/BJBM4687WUuf+Uj9dEi8aDNaPxtpbDxcG1THTImUMZq4UCaaNYpsVqraNyKLJXDYsFZ/5jl7bLRtO88t7P3xZaAxhb5OdPMXqsSkp1WCieG8jXm1U99+blvLlXzPCS+M93VnJCiK+09LfaSaBAVBomyDgJua8dfUzR7ga34IvR2Nvj+A9heJ6lsl1KG4NkI1032Cnff1m1wof2B9oHJK4bi6JkEdSqeNeiuo6QoZZincoc73/TH9SXF8sCE7XyuYyW8WSgbGFCjPV0ihLKhdPs08Tx82fYAkLLc4I2wdl4apY7GU5lHRFzRWJep7Ww3wbeA3qmd59/86P4xuNaqDpygXt6M85glSBHOCGgJDnt+pN9bK7HApMguX6+06RZNjzVmcZJ+wcUrJ9//bpRNxNuKpNl9uFds+S9tdx7LaM5ZkIrPj6nIU9mnbFtVbs9s/uLgl8MVczAwet+iOEzzBlYW7RCMgE6gyNLeq6+1tIx4dpgZnd0DksJS5f+JNDpwwcPNXaaVspq1fbQajOrJgK0ofKtJ1Ne90L6VO4MOl5S886p7u6xo7OLjG8TGL+HU1JXGJgppg4nNbNJ5nlzSpuPYy21JUEcUA94PoFiZfjZue+QnyQ80ekOuZVkxx4g+cvhJfHgNl4hy1/a6+RKcKlar/J29y//EztlbVPHVUeQ1zX86eQVAjR/M3dA9w4W8LfaXp4EgM85wOWasli837PzVMOnsLzR+k3o75/lRPAJSE1xAKQzEi5v10ke+VBvRt1cwQRMd+U5mLCTGVd6XiZtgBG5cDi0w22GKcVNvHiu5LQbZEDVtz0onn7k5+heuKXVsZtSzilkLRAUmjMXEMB3J9YC50XBxPiz53SC+EhnPl9WsKCv92SM/OFFIMJZYfl0WW8tIO3UxYcwdMAj7FSmgrsZ2aAZO03BOhP1bNNZItyXYQFTpC3SG1VuPDqH9GkiCDmE+JwxyIVSO5siDErAOpEXFgjy6PQtOVDj+s6e1r8heWVvmZnTciuf4EiNZzCAd7SOMhXERIOlsHIMG399i9aLTy3m2hRLZjJVDNLS53iGIK11dPqQt0zBDyg6qc7YqkDm2M5Ve6dCWCaCbTXX2rToaIgz6+zh4lYUi/+6nqcFMAkQJKHYLK0wYk5N9szV6xihDbDDFr45lN1K4aCXBq/FitPSud9gLt5ZVn+ZqGX7cwm2z5EGMgfFpIFyhGGuDPmso6TItTMwny+7uPnLCf4W6goFQFV0oQSsc9VfMmVLcLr6ZetDZbaSFTLqnSO/bIPjA3/zAUoqgGFAEQS4IhuMzEp2I3jJzbzkk/IEmyax+rhZTwd6f+CGtwPixu8IvzACquPWPREu9ZvGkUzpRwvRRuaNN6cr0W1wWits9ICdYJ7ltbgMiSL3sTPeufgNcVqMVWFkCPDH4jG2jA0XcVgQj62Cb29v9f/z/+2KbYvIv/zzjpQAPkliaVDzNrW57TZ/ZOyZD0nlfMmAIBIAGAI0D3k/mdN4xr9v85ZbZbbqfH2jGd5hUqNZWwl5SPfoGmfElmazUIeNL1j/mkF7VNAzTq4jNt8JoQ11NQOcmhprXoxSxfRGJ9LDEOAQ+dmxAQH90iti9e2u/MoeuaGcDTHoC+xsmEeWmxEKefQuIzHbpw5Tc5cEocboAD09oipWQhtTO1wivf/O+DRe2rpl/E9wlrzBorjJsOeG1B/XPW4EaJEFdNlECEZga5ZoGRHXgYouGRuVkm8tDESiEyFNo+3s5M5puSdTyUL2llnINVHEt91XUNW4ewdMgJ4boJfEyt/iY5WXqbA+A2Fkt5Z0lutiWhe9nZIyIUjyXDC3UsaG1t+eNx6z4W/OYoTB7A6x+dNSTOi9AInctbESqm5gvOLww7OWXPrmHwVZasrl4eD113pm+JtT7JVOvnCXqdzzdTRHgJ0PiGTFYW5Gvt9R9LD6Lzfs0v/TZZHSmyVNq7viIHE6DBK7Qp07Iz55EM8SYtQvZf/obBniTWi5C2/ovHfw4VndkE5XYdjOhCMRjDeOEfXeN/CwfGduiUIfsoFeUxXeQXba7c7972XNv8w+dTjjUM0QeNAReW+J014dKAD/McQYXT7c0GQPIkn3Ll6R7gGjuiQoZD0TEeEqQpKoZ15g/0OPQI17QiSv9AUROa/V/TQN3dvLArec3RrsYlvBm1b8LWzltdugsC50lNKYLEp2a+ZZYqPejULRlOJh5zj/LVMyTDvwKhMxxwuDkxJ1QpoNI0OTWLom4Z71SNzI9TV1iXJrIu9Wcnd+MCaAw8o1jSXd94YU/1gnkrC9BUEOtQvEIQ7g0i6h+KL2JKk8Ydl7HruvgWMSAmNe+LshGhV4qnWHhO9/RIPQzY1tHRj2VqOyNsDpK0cww+56AdDC4gsWwY0XxoucIWIqs/GcwnWqlaT0KPr8mbK5U94/301i1WLt4YINTVvCFBrFZbIbY8eycOdeJ2teD5IfPLCRg7jjcFTwlMFNl9zdh/o3E/hHPwj7BWg0MU09pPrBLbrCgm54A6H+I6v27+jL5gkjWg/iYdks9jbfVP5y/n0dlgWEMlKasl7JvFZd56LfybW1eeaVO0gxTfXZwD8G4SI116yx7UKVRgui6Ya1YpixqXeNLc8IxtAwCU5IhwQgn+NqHnRaDv61CxKhOq4pOX7M6pkA+Pmpd4j1vn6ACUALoLLc4vpXci8VidLxzm7qFBe7s+quuJs6ETYmnpgS3LwSZxPIltgBDXz8M1k/W2ySNv2f9/NPhxLGK2D21dkHeSGmenRT3Yqcdl0m/h3OYr8V+lXNYGf8aCCpd4bWjE4QIPj7vUKN4Nrfs7ML6Y2OyS830JCnofg/k7lpFpt4SqZc5HGg1HCOrHvOdC8bP6FGDbE/VV0mX4IakzbdS/op+Kt3G24/8QbBV7y86sGSQ/vZzU8FXs7u6jIvwchsEP2BpIhW3G8uWNwa3HmjfH/ZjhhCWvluAcF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g");UP=new Map(AP(e).flatMap(((e,t)=>e.map((e=>[e,t+1<<24]))))),jP=new Set(EP(e)),qP=new Map,zP=new Map;for(let[t,r]of SP(e)){if(!jP.has(t)&&2==r.length){let[e,n]=r,i=zP.get(e);i||(i=new Map,zP.set(e,i)),i.set(n,t)}qP.set(t,r.reverse())}}();let t=[],r=[],n=!1;function i(e){let r=UP.get(e);r&&(n=!0,e|=r),t.push(e)}for(let n of e)for(;;){if(n<128)t.push(n);else if(KP(n)){let e=n-NP,t=e%BP/DP|0,r=e%DP;i(MP+(e/BP|0)),i(xP+t),r>0&&i(OP+r)}else{let e=qP.get(n);e?r.push(...e):i(n)}if(!r.length)break;n=r.pop()}if(n&&t.length>1){let e=LP(t[0]);for(let r=1;r<t.length;r++){let n=LP(t[r]);if(0==n||e<=n){e=n;continue}let i=r-1;for(;;){let r=t[i+1];if(t[i+1]=t[i],t[i]=r,!i)break;if(e=LP(t[--i]),e<=n)break}e=LP(t[r])}}return t}function HP(e){return VP(e).map(FP)}function $P(e){return function(e){let t=[],r=[],n=-1,i=0;for(let s of e){let e=LP(s),o=FP(s);if(-1==n)0==e?n=o:t.push(o);else if(i>0&&i>=e)0==e?(t.push(n,...r),r.length=0,n=o):r.push(o),i=e;else{let s=GP(n,o);s>=0?n=s:0==i&&0==e?(t.push(n),n=o):(r.push(o),i=e)}}return n>=0&&t.push(n,...r),t}(VP(e))}const WP=".",JP=e=>Array.from(e);function QP(e,t){return e.P.has(t)||e.Q.has(t)}class ZP extends Array{get is_emoji(){return!0}}let YP,XP,eT,tT,rT,nT,iT,sT,oT,aT,cT;function uT(){if(YP)return;let e=bP("AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAOwA9ACsANgAmAGIAHgAuACgAJwAXAC0AGgAjAB8ALwAUACkAEgAeAAkAGwARABkAFgA5ACgALQArADcAFQApABAAHgAiABAAGgAeABMAGAUhBe8BFxREN8sF2wC5AK5HAW8ArQkDzQCuhzc3NzcBP68NEfMABQdHBuw5BV8FYAA9MzkI9r4ZBg7QyQAWA9CeOwLNCjcCjqkChuA/lm+RAsXTAoP6ASfnEQDytQFJAjWVCkeXAOsA6godAB/cwdAUE0WlBCN/AQUCQRjFD/MRBjHxDQSJbw0jBzUAswBxme+tnIcAYwabAysG8QAjAEMMmxcDqgPKQyDXCMMxA7kUQwD3NXOrAKmFIAAfBC0D3x4BJQDBGdUFAhEgVD8JnwmQJiNWYUzrg0oAGwAUAB0AFnNcACkAFgBP9h3gPfsDOWDKneY2ChglX1UDYD30ABsAFAAdABZzIGRAnwDD8wAjAEEMzRbDqgMB2sAFYwXqAtCnAsS4AwpUJKRtFHsadUz9AMMVbwLpABM1NJEX0ZkCgYMBEyMAxRVvAukAEzUBUFAtmUwSAy4DBTER33EftQHfSwB5MxJ/AjkWKQLzL8E/cwBB6QH9LQDPDtO9ASNriQC5DQANAwCK21EFI91zHwCoL9kBqQcHBwcHKzUDowBvAQohPvU3fAQgHwCyAc8CKQMA5zMSezr7ULgFmDp/LzVQBgEGAi8FYQVgt8AFcTtlQhpCWEmfe5tmZ6IAExsDzQ8t+X8rBKtTAltbAn0jsy8Bl6utPWMDTR8Ei2kRANkDBrNHNysDBzECQWUAcwFpJ3kAiyUhAJ0BUb8AL3EfAbfNAz81KUsFWwF3YQZtAm0A+VEfAzEJDQBRSQCzAQBlAHsAM70GD/v3IZWHBwARKQAxALsjTwHZAeMPEzmXgIHwABIAGQA8AEUAQDt3gdvIEGcQZAkGTRFMdEIVEwK0D64L7REdDNkq09PgADSxB/MDWwfzA1sDWwfzB/MDWwfzA1sDWwNbA1scEvAi28gQZw9QBHUFlgWTBN4IiyZREYkHMAjaVBV0JhxPA00BBCMtSSQ7mzMTJUpMFE0LCAQ2SmyvfUADTzGzVP2QqgPTMlc5dAkGHnkSqAAyD3skNb1OhnpPcagKU0+2tYdJak5vAsY6sEAACikJm2/Dd1YGRRAfJ6kQ+ww3AbkBPw3xS9wE9QY/BM0fgRkdD9GVoAipLeEM8SbnLqWAXiP5KocF8Uv4POELUVFsD10LaQnnOmeBUgMlAREijwrhDT0IcRD3Cs1vDekRSQc9A9lJngCpBwULFR05FbkmFGKwCw05ewb/GvoLkyazEy17AAXXGiUGUQEtGwMA0y7rhbRaNVwgT2MGBwspI8sUrFAkDSlAu3hMGh8HGSWtApVDdEqLUToelyH6PEENai4XUYAH+TwJGVMLhTyiRq9FEhHWPpE9TCJNTDAEOYMsMyePCdMPiQy9fHYBXQklCbUMdRM1ERs3yQg9Bx0xlygnGQglRplgngT7owP3E9UDDwVDCUUHFwO5HDETMhUtBRGBKNsC9zbZLrcCk1aEARsFzw8pH+MQVEfkDu0InwJpA4cl7wAxFSUAGyKfCEdnAGOP3FMJLs8Iy2pwI3gDaxTrZRF3B5UOWwerHDcVwxzlcMxeD4YMKKezCV8BeQmdAWME5wgNNV+MpCBFZ1eLXBifIGVBQ14AAjUMaRWjRMGHfAKPD28SHwE5AXcHPQ0FAnsR8RFvEJkI74YINbkz/DopBFMhhyAVCisDU2zSCysm/Qz8bQGnEmYDEDRBd/Jnr2C6KBgBBx0yyUFkIfULlk/RDKAaxRhGVDIZ6AfDA/ca9yfuQVsGAwOnBxc6UTPyBMELbQiPCUMATQ6nGwfbGG4KdYzUATWPAbudA1uVhwJzkwY7Bw8Aaw+LBX3pACECqwinAAkA0wNbAD0CsQehAB0AiUUBQQMrMwEl6QKTA5cINc8BmTMB9y0EH8cMGQD7O25OAsO1AoBuZqYF4VwCkgJNOQFRKQQJUktVA7N15QDfAE8GF+NLARmvTs8e50cB43MvAMsA/wAJOQcJRQHRAfdxALsBYws1Caa3uQFR7S0AhwAZbwHbAo0A4QA5AIP1AVcAUQVd/QXXAlNNARU1HC9bZQG/AyMBNwERAH0Gz5GpzQsjBHEH1wIQHxXlAu8yB7kFAyLjE9FCyQK94lkAMhoKPAqrCqpgX2Q3CjV2PVQAEh+sPss/UgVVO1c7XDtXO1w7VztcO1c7XDtXO1wDm8Pmw+YKcF9JYe8Mqg3YRMw6TRPfYFVgNhPMLbsUxRXSJVoZQRrAJwkl6FUNDwgt12Y0CDA0eRfAAEMpbINFY4oeNApPHOtTlVT8LR8AtUumM7MNsBsZREQFS3XxYi4WEgomAmSFAmJGX1GzAV83JAKh+wJonAJmDQKfiDgfDwJmPwJmKgRyBIMDfxcDfpY5Cjl7GzmGOicnAmwhAjI6OA4CbcsCbbLzjgM3a0kvAWsA4gDlAE4JB5wMkQECD8YAEbkCdzMCdqZDAnlPRwJ4viFg30WyRvcCfEMCeswCfQ0CfPRIBEiBZygALxlJXEpfGRtK0ALRBQLQ0EsrA4hTA4fqRMmRNgLypV0HAwOyS9JMMSkH001QTbMCi0MCitzFHwshR2sJuwKOOwKOYESbhQKO3QKOYHxRuFM5AQ5S2FSJApP/ApMQAO0AIFUiVbNV1AosHymZijLleGpFPz0Cl6MC77ZYJawAXSkClpMCloCgAK1ZsFoNhVEAPwKWuQKWUlxIXNUCmc8CmWhczl0LHQKcnznGOqECnBoCn58CnryOACETNS4TAp31Ap6WALlBYThh8wKe1wKgcgGtAp6jIwKeUqljzGQrKS8CJ7MCJoICoP8CoFDbAqYzAqXSAqgDAIECp/ZogGi1AAdNaiBq1QKs5wKssgKtawKtBgJXIQJV4AKx5dsDH1JsmwKywRECsuwbbORtZ21MYwMl0QK2YD9DbpQDKUkCuGICuUsZArkue3A6cOUCvR0DLbYDMhUCvoxyBgMzdQK+HnMmc1MCw88CwwhzhnRPOUl05AM8qwEDPJ4DPcMCxYACxksCxhSNAshtVQLISALJUwLJMgJkoQLd1nh9ZXiyeSlL1AMYp2cGAmH4GfeVKHsPXpZevxUCz28Cz3AzT1fW9xejAMqxAs93AS3uA04Wfk8JAtwrAtuOAtJTA1JgA1NjAQUDVZCAjUMEzxrxZEl5A4LSg5EC2ssC2eKEFIRNp0ADhqkAMwNkEoZ1Xf0AWQLfaQLevHd7AuIz7RgB8zQrAfSfAfLWiwLr9wLpdH0DAur9AuroAP1LAb0C7o0C66CWrpcHAu5DA4XkmH1w5HGlAvMHAG0DjhqZlwL3FwORcgOSiwL3nAL53QL4apogmq+/O5siA52HAv7+AR8APZ8gAZ+3AwWRA6ZuA6bdANXJAwZuoYyiCQ0DDE0BEwEjB3EGZb1rCQC/BG/DFY8etxEAG3k9ACcDNxJRA42DAWcrJQCM8wAlAOanC6OVCLsGI6fJBgCvBRnDBvElRUYFFoAFcD9GSDNCKUK8X3kZX8QAls0FOgCQVCGbwTsuYDoZutcONxjOGJHJ/gVfBWAFXwVgBWsFYAVfBWAFXwVgBV8FYAVfBWBOHQjfjW8KCgoKbF7xMwTRA7kGN8PDAMMEr8MA70gxFroFTj5xPnhCR0K+X30/X/AAWBkzswCNBsxzzASm70aCRS4rDDMeLz49fnXfcsH5GcoscQFz13Y4HwVnBXLJycnACNdRYwgICAqEXoWTxgA7P4kACxbZBu21Kw0AjMsTAwkVAOVtJUUsJ1JCuULESUArXy9gPi9AKwnJRQYKTD9LPoA+iT54PnkCkULEUUpDX9NWV3JVEjQAc1w3A3IBE3YnX+g7QiMJb6MKaiszRCUuQrNCxDPMCcwEX9EWJzYREBEEBwIHKn6l33JCNVIfybPJtAltydPUCmhBZw/tEKsZAJOVJU1CLRuxbUHOQAo7P0s+eEJHHA8SJVRPdGM0NVrpvBoKhfUlM0JHHGUQUhEWO1xLSj8MO0ucNAqJIzVCRxv9EFsqKyA4OQgNj2nwZgp5ZNFgE2A1K3YHS2AhQQojJmC7DgpzGG1WYFUZCQYHZO9gHWCdYIVgu2BTYJlwFh8GvRbcXbG8YgtDHrMBwzPVyQonHQgkCyYBgQJ0Ajc4nVqIAwGSCsBPIgDsK3SWEtIVBa5N8gGjAo+kVwVIZwD/AEUSCDweX4ITrRQsJ8K3TwBXFDwEAB0TvzVcAtoTS20RIwDgVgZ9BBImYgA5AL4Coi8LFnezOkCnIQFjAY4KBAPh9RcGsgZSBsEAJctdsWIRu2kTkQstRw7DAcMBKgpPBGIGMDAwKCYnKTQaLg4AKRSVAFwCdl+YUZ0JdicFD3lPAdt1F9ZZKCGxuE3yBxkFVGcA/wBFEgiCBwAOLHQSjxOtQDg1z7deFRMAZ8QTAGtKb1ApIiPHADkAvgKiLy1DFtYCmBiDAlDDWNB0eo7fpaMO/aEVRRv0ATEQZBIODyMEAc8JQhCbDRgzFD4TAEMAu9YBCgCsAOkAm5I3ABwAYxvONnR+MhXJAxgKQyxL2+kkJhMbhQKDBMkSsvF0AD9BNQ6uQC7WqSQHwxEAEEIu1hkhAH2z4iQPwyJPHNWpdyYBRSpnJALzoBAEVPPsH20MxA0CCEQKRgAFyAtFAlMNwwjEDUQJRArELtapMg7DDZgJIw+TGukEIwvDFkMAqAtDEMMMBhioe+QAO3MMRAACrgnEBSPY9Q0FDnbSBoMAB8MSYxkSxAEJAPIJAAB8FWMOFtMc/HcXwxhDAC7DAvOowwAewwJdKDKHAAHDAALrFUQVwwAbwyvzpWMWv8wA/ABpAy++bcYDUKPD0KhDCwKmJ1MAAmMA5+UZwxAagwipBRL/eADfw6fDGOMCGsOjk3l6BwOpo4sAEsMOGxMAA5sAbcMOAAvDp0MJGkMDwgipnNIPAwfIqUMGAOGDAAPzABXDAAcDAAnDAGmTABrDAA7DChjDjnEWAwABYwAOcwAuUyYABsMAF8MIKQANUgC6wy4AA8MADqMq8wCyYgAcIwAB8wqpAAXOCx0V4wAHowBCwwEKAGnDAAuDAB3DAAjDCakABdIAbqcZ3QCZCCkABdIAAAFDAAfjAB2jCCkABqIACYMAGzMAbSMA5sOIAAhjAAhDABTDBAkpAAbSAOOTAAlDC6kOzPtnAAdDAG6kQFAATwAKwwwAA0MACbUDPwAHIwAZgwACE6cDAAojAApDAAoDp/MGwwAJIwADEwAQQwgAFEMAEXMAD5MADfMADcMAGRMOFiMAFUMAbqMWuwHDAMIAE0MLAGkzEgDhUwACQwAEWgAXgwUjAAbYABjDBSYBgzBaAEFNALcQBxUMegAwMngBrA0IZgJ0KxQHBREPd1N0ZzKRJwaIHAZqNT4DqQq8BwngAB4DAwt2AX56T1ocKQNXAh1GATQGC3tOxYNagkgAMQA5CQADAQEAWxLjAIOYNAEzAH7tFRk6TglSAF8NAAlYAQ+S1ACAQwQorQBiAN4dAJ1wPyeTANVzuQDX3AIeEMp9eyMgXiUAEdkBkJizKltbVVAaRMqRAAEAhyQ/SDEz6BmfVwB6ATEsOClKIRcDOF0E/832AFNt5AByAnkCRxGCOs94NjXdAwINGBonDBwPALW2AwICAgAAAAAAAAYDBQMDARrUAwAtAAAAAgEGBgYGBgYFBQUFBQUEBQYHCAkEBQUFBQQAAAICAAAAIgCNAJAAlT0A6gC7ANwApEQAwgCyAK0AqADuAKYA2gCjAOcBCAEDAMcAgQBiANIA1AEDAN4A8gCQAKkBMQDqAN8A3AsBCQ8yO9ra2tq8xuLT1tRJOB0BUgFcNU0BWgFpAWgBWwFMUUlLbhMBUxsNEAs6PhMOACcUKy0vMj5AQENDQ0RFFEYGJFdXV1dZWVhZL1pbXVxcI2NnZ2ZoZypsbnZ1eHh4eHh4enp6enp6enp6enp8fH18e2IARPIASQCaAHgAMgBm+ACOAFcAVwA3AnbvAIsABfj4AGQAk/IAnwBPAGIAZP//sACFAIUAaQBWALEAJAC2AIMCQAJDAPwA5wD+AP4A6AD/AOkA6QDoAOYALwJ7AVEBQAE+AVQBPgE+AT4BOQE4ATgBOAEcAVgXADEQCAEAUx8SHgsdHhYAjgCWAKYAUQBqIAIxAHYAbwCXAxUDJzIDIUlGTzEAkQJPAMcCVwKkAMAClgKWApYClgKWApYCiwKWApYClgKWApYClgKVApUCmAKgApcClgKWApQClAKUApQCkgKVAnUB1AKXAp8ClgKWApUeAIETBQD+DQOfAmECOh8BVBg9AuIZEjMbAU4/G1WZAXusRAFpYQEFA0FPAQYAmTEeIJdyADFoAHEANgCRA5zMk/C2jGINwjMWygIZCaXdfDILBCs5dAE7YnQBugDlhoiHhoiGiYqKhouOjIaNkI6Ij4qQipGGkoaThpSSlYaWhpeKmIaZhpqGm4aci52QnoqfhuIC4XTpAt90AIp0LHSoAIsAdHQEQwRABEIERQRDBEkERgRBBEcESQRIBEQERgRJAJ5udACrA490ALxuAQ10ANFZdHQA13QCFHQA/mJ0AP4BIQD+APwA/AD9APwDhGZ03ASMK23HAP4A/AD8AP0A/CR0dACRYnQA/gCRASEA/gCRAvQA/gCRA4RmdNwEjCttxyR0AP9idAEhAP4A/gD8APwA/QD8AP8A/AD8AP0A/AOEZnTcBIwrbcckdHQAkWJ0ASEA/gCRAP4AkQL0AP4AkQOEZnTcBIwrbcckdAJLAT50AlIBQXQCU8l0dAJfdHQDpgL0A6YDpgOnA6cDpwOnA4RmdNwEjCttxyR0dACRYnQBIQOmAJEDpgCRAvQDpgCRA4RmdNwEjCttxyR0BDh0AJEEOQCRDpU5dSgCADR03gV2CwArdAEFAM5iCnR0AF1iAAYcOgp0dACRCnQAXAEIwWZ0CnRmdHQAkWZ0CnRmdEXgAFF03gp0dEY0tlT2u3SOAQTwscwhjZZKrhYcBSfFp9XNbKiVDOD2b+cpe4/Z17mQnbtzzhaeQtE2GGj0IDNTjRUSyTxxw/RPHW/+vS7d1NfRt9z9QPZg4X7QFfhCnkvgNPIItOsC2eV6hPannZNHlZ9xrwZXIMOlu3jSoQSq78WEjwLjw1ELSlF1aBvfzwk5ZX7AUvQzjPQKbDuQ+sm4wNOp4A6AdVuRS0t1y/DZpg4R6m7FNjM9HgvW7Bi88zaMjOo6lM8wtBBdj8LP4ylv3zCXPhebMKJc066o9sF71oFW/8JXu86HJbwDID5lzw5GWLR/LhT0Qqnp2JQxNZNfcbLIzPy+YypqRm/lBmGmex+82+PisxUumSeJkALIT6rJezxMH+CTJmQtt5uwTVbL3ptmjDUQzlSIvWi8Tl7ng1NpuRn1Ng4n14Qc+3Iil7OwkvNWogLSPkn3pihIFytyIGmMhOe3n1tWsuMy9BdKyqF4Z3v2SgggTL9KVvMXPnCbRe+oOuFFP3HejBG/w9gvmfNYvg6JuWia2lcSSN1uIjBktzoIazOHPJZ7kKHPz8mRWVdW3lA8WGF9dQF6Bm673boov3BUWDU2JNcahR23GtfHKLOz/viZ+rYnZFaIznXO67CYEJ1fXuTRpZhYZkKe54xeoagkNGLs+NTZHE0rX45/XvQ2RGADX6vcAvdxIUBV27wxGm2zjZo4X3ILgAlrOFheuZ6wtsvaIj4yLY7qqawlliaIcrz2G+c3vscAnCkCuMzMmZvMfu9lLwTvfX+3cVSyPdN9ZwgDZhfjRgNJcLiJ67b9xx8JHswprbiE3v9UphotAPIgnXVIN5KmMc0piXhc6cChPnN+MRhG9adtdttQTTwSIpl8I4/j//d3sz1326qTBTpPRM/Hgh3kzqEXs8ZAk4ErQhNO8hzrQ0DLkWMA/N+91tn2MdOJnWC2FCZehkQrwzwbKOjhvZsbM95QoeL9skYyMf4srVPVJSgg7pOLUtr/n9eT99oe9nLtFRpjA9okV2Kj8h9k5HaC0oivRD8VyXkJ81tcd4fHNXPCfloIQasxsuO18/46dR2jgul/UIet2G0kRvnyONMKhHs6J26FEoqSqd+rfYjeEGwHWVDpX1fh1jBBcKGMqRepju9Y00mDVHC+Xdij/j44rKfvfjGinNs1jO/0F3jB83XCDINN/HB84axlP+3E/klktRo+vl3U/aiyMJbIodE1XSsDn6UAzIoMtUObY2+k/4gY/l+AkZJ5Sj2vQrkyLm3FoxjhDX+31UXBFf9XrAH31fFqoBmDEZvhvvpnZ87N+oZEu7U9O/nnk+QWj3x8uyoRbEnf+O5UMr9i0nHP38IF5AvzrBW8YWBUR0mIAzIvndQq9N3v/Jto3aPjPXUPl8ASdPPyAp7jENf8bk7VMM9ol9XGmlBmeDMuGqt+WzuL6CXAxXjIhCPM5vACchgMJ/8XBGLO/D1isVvGhwwHHr1DLaI5mn2Jr/b1pUD90uciDaS8cXNDzCWvNmT/PhQe5e8nTnnnkt8Ds/SIjibcum/fqDhKopxAY8AkSrPn+IGDEKOO+U3XOP6djFs2H5N9+orhOahiQk5KnEUWa+CzkVzhp8bMHRbg81qhjjXuIKbHjSLSIBKWqockGtKinY+z4/RdBUF6pcc3JmnlxVcNgrI4SEzKUZSwcD2QCyxzKve+gAmg6ZuSRkpPFa6mfThu7LJNu3H5K42uCpNvPAsoedolKV/LHe/eJ+BbaG5MG0NaSGVPRUmNFMFFSSpXEcXwbVh7UETOZZtoVNRGOIbbkig3McEtR68cG0RZAoJevWYo7Dg/lZ1CQzblWeUvVHmr8fY4Nqd9JJiH/zEX24mJviH60fAyFr0A3c4bC1j3yZU60VgJxXn8JgJXLUIsiBnmKmMYz+7yBQFBvqb2eYnuW59joZBf56/wXvWIR4R8wTmV80i1mZy+S4+BUES+hzjk0uXpC///z/IlqHZ1monzlXp8aCfhGKMti73FI1KbL1q6IKO4fuBuZ59gagjn5xU79muMpHXg6S+e+gDM/U9BKLHbl9l6o8czQKl4RUkJJiqftQG2i3BMg/TQlUYFkJDYBOOvAugYuzYSDnZbDDd/aSd9x0Oe6F+bJcHfl9+gp6L5/TgA+BdFFovbfCrQ40s5vMPw8866pNX8zyFGeFWdxIpPVp9Rg1UPOVFbFZrvaFq/YAzHQgqMWpahMYfqHpmwXfHL1/kpYmGuHFwT55mQu0dylfNuq2Oq0hTMCPwqfxnuBIPLXfci4Y1ANy+1CUipQxld/izVh16WyG2Q0CQQ9NqtAnx1HCHwDj7sYxOSB0wopZSnOzxQOcExmxrVTF2BkOthVpGfuhaGECfCJpJKpjnihY+xOT2QJxN61+9K6QSqtv2Shr82I3jgJrqBg0wELFZPjvHpvzTtaJnLK6Vb97Yn933koO/saN7fsjwNKzp4l2lJVx2orjCGzC/4ZL4zCver6aQYtC5sdoychuFE6ufOiog+VWi5UDkbmvmtah/3aArEBIi39s5ILUnlFLgilcGuz9CQshEY7fw2ouoILAYPVT/gyAIq3TFAIwVsl+ktkRz/qGfnCDGrm5gsl/l9QdvCWGsjPz3dU7XuqKfdUrr/6XIgjp4rey6AJBmCmUJMjITHVdFb5m1p+dLMCL8t55zD42cmftmLEJC0Da04YiRCVUBLLa8D071/N5UBNBXDh0LFsmhV/5B5ExOB4j3WVG/S3lfK5o+V6ELHvy6RR9n4ac+VsK4VE4yphPvV+kG9FegTBH4ZRXL2HytUHCduJazB/KykjfetYxOXTLws267aGOd+I+JhKP//+VnXmS90OD/jvLcVu0asyqcuYN1mSb6XTlCkqv1vigZPIYwNF/zpWcT1GR/6aEIRjkh0yhg4LXJfaGobYJTY4JI58KiAKgmmgAKWdl5nYCeLqavRJGQNuYuZtZFGx+IkI4w4NS2xwbetNMunOjBu/hmKCI/w7tfiiyUd//4rbTeWt4izBY8YvGIN6vyKYmP/8X8wHKCeN+WRcKM70+tXKNGyevU9H2Dg5BsljnTf8YbsJ1TmMs74Ce2XlHisleguhyeg44rQOHZuw/6HTkhnnurK2d62q6yS7210SsAIaR+jXMQA+svkrLpsUY+F30Uw89uOdGAR6vo4FIME0EfVVeHTu6eKicfhSqOeXJhbftcd08sWEnNUL1C9fnprTgd83IMut8onVUF0hvqzZfHduPjbjwEXIcoYmy+P6tcJZHmeOv6VrvEdkHDJecjHuHeWANe79VG662qTjA/HCvumVv3qL+LrOcpqGps2ZGwQdFJ7PU4iuyRlBrwfO+xnPyr47s2cXVbWzAyznDiBGjCM3ksxjjqM62GE9C8f5U38kB3VjtabKp/nRdvMESPGDG90bWRLAt1Qk5DyLuazRR1YzdC1c+hZXvAWV8xA72S4A8B67vjVhbba3MMop293FeEXpe7zItMWrJG/LOH9ByOXmYnNJfjmfuX9KbrpgLOba4nZ+fl8Gbdv/ihv+6wFGKHCYrVwmhFC0J3V2bn2tIB1wCc1CST3d3X2OyxhguXcs4sm679UngzofuSeBewMFJboIQHbUh/m2JhW2hG9DIvG2t7yZIzKBTz9wBtnNC+2pCRYhSIuQ1j8xsz5VvqnyUIthvuoyyu7fNIrg/KQUVmGQaqkqZk/Vx5b33/gsEs8yX7SC1J+NV4icz6bvIE7C5G6McBaI8rVg56q5QBJWxn/87Q1sPK4+sQa8fLU5gXo4paaq4cOcQ4wR0VBHPGjKh+UlPCbA1nLXyEUX45qZ8J7/Ln4FPJE2TdzD0Z8MLSNQiykMMmSyOCiFfy84Rq60emYB2vD09KjYwsoIpeDcBDTElBbXxND72yhd9pC/1CMid/5HUMvAL27OtcIJDzNKpRPNqPOpyt2aPGz9QWIs9hQ9LiX5s8m9hjTUu/f7MyIatjjd+tSfQ3ufZxPpmJhTaBtZtKLUcfOCUqADuO+QoH8B9v6U+P0HV1GLQmtoNFTb3s74ivZgjES0qfK+8RdGgBbcCMSy8eBvh98+et1KIFqSe1KQPyXULBMTsIYnysIwiZBJYdI20vseV+wuJkcqGemehKjaAb9L57xZm3g2zX0bZ2xk/fU+bCo7TlnbW7JuF1YdURo/2Gw7VclDG1W7LOtas2LX4upifZ/23rzpsnY/ALfRgrcWP5hYmV9VxVOQA1fZvp9F2UNU+7d7xRyVm5wiLp3/0dlV7vdw1PMiZrbDAYzIVqEjRY2YU03sJhPnlwIPcZUG5ltL6S8XCxU1eYS5cjr34veBmXAvy7yN4ZjArIG0dfD/5UpBNlX1ZPoxJOwyqRi3wQWtOzd4oNKh0LkoTm8cwqgIfKhqqGOhwo71I+zXnMemTv2B2AUzABWyFztGgGULjDDzWYwJUVBTjKCn5K2QGMK1CQT7SzziOjo+BhAmqBjzuc3xYym2eedGeOIRJVyTwDw37iCMe4g5Vbnsb5ZBdxOAnMT7HU4DHpxWGuQ7GeiY30Cpbvzss55+5Km1YsbD5ea3NI9QNYIXol5apgSu9dZ8f8xS5dtHpido5BclDuLWY4lhik0tbJa07yJhH0BOyEut/GRbYTS6RfiTYWGMCkNpfSHi7HvdiTglEVHKZXaVhezH4kkXiIvKopYAlPusftpE4a5IZwvw1x/eLvoDIh/zpo9FiQInsTb2SAkKHV42XYBjpJDg4374XiVb3ws4qM0s9eSQ5HzsMU4OZJKuopFjBM+dAZEl8RUMx5uU2N486Kr141tVsGQfGjORYMCJAMsxELeNT4RmWjRcpdTGBwcx6XN9drWqPmJzcrGrH4+DRc7+n1w3kPZwu0BkNr6hQrqgo7JTB9A5kdJ/H7P4cWBMwsmuixAzJB3yrQpnGIq90lxAXLzDCdn1LPibsRt7rHNjgQBklRgPZ8vTbjXdgXrTWQsK5MdrXXQVPp0Rinq3frzZKJ0qD6Qhc40VzAraUXlob1gvkhK3vpmHgI6FRlQZNx6eRqkp0zy4AQlX813fAPtL3jMRaitGFFjo0zmErloC+h+YYdVQ6k4F/epxAoF0BmqEoKNTt6j4vQZNQ2BoqF9Vj53TOIoNmDiu9Xp15RkIgQIGcoLpfoIbenzpGUAtqFJp5W+LLnx38jHeECTJ/navKY1NWfN0sY1T8/pB8kIH3DU3DX+u6W3YwpypBMYOhbSxGjq84RZ84fWJow8pyHqn4S/9J15EcCMsXqrfwyd9mhiu3+rEo9pPpoJkdZqHjra4NvzFwuThNKy6hao/SlLw3ZADUcUp3w3SRVfW2rhl80zOgTYnKE0Hs2qp1J6H3xqPqIkvUDRMFDYyRbsFI3M9MEyovPk8rlw7/0a81cDVLmBsR2ze2pBuKb23fbeZC0uXoIvDppfTwIDxk1Oq2dGesGc+oJXWJLGkOha3CX+DUnzgAp9HGH9RsPZN63Hn4RMA5eSVhPHO+9RcRb/IOgtW31V1Q5IPGtoxPjC+MEJbVlIMYADd9aHYWUIQKopuPOHmoqSkubnAKnzgKHqgIOfW5RdAgotN6BN+O2ZYHkuemLnvQ8U9THVrS1RtLmKbcC7PeeDsYznvqzeg6VCNwmr0Yyx1wnLjyT84BZz3EJyCptD3yeueAyDWIs0L2qs/VQ3HUyqfrja0V1LdDzqAikeWuV4sc7RLIB69jEIBjCkyZedoUHqCrOvShVzyd73OdrJW0hPOuQv2qOoHDc9xVb6Yu6uq3Xqp2ZaH46A7lzevbxQEmfrzvAYSJuZ4WDk1Hz3QX1LVdiUK0EvlAGAYlG3Md30r7dcPN63yqBCIj25prpvZP0nI4+EgWoFG95V596CurXpKRBGRjQlHCvy5Ib/iW8nZJWwrET3mgd6mEhfP4KCuaLjopWs7h+MdXFdIv8dHQJgg1xi1eYqB0uDYjxwVmri0Sv5XKut/onqapC+FQiC2C1lvYJ9MVco6yDYsS3AANUfMtvtbYI2hfwZatiSsnoUeMZd34GVjkMMKA+XnjJpXgRW2SHTZplVowPmJsvXy6w3cfO1AK2dvtZEKTkC/TY9LFiKHCG0DnrMQdGm2lzlBHM9iEYynH2UcVMhUEjsc0oDBTgo2ZSQ1gzkAHeWeBXYFjYLuuf8yzTCy7/RFR81WDjXMbq2BOH5dURnxo6oivmxL3cKzKInlZkD31nvpHB9Kk7GfcfE1t+1V64b9LtgeJGlpRFxQCAqWJ5DoY77ski8gsOEOr2uywZaoO/NGa0X0y1pNQHBi3b2SUGNpcZxDT7rLbBf1FSnQ8guxGW3W+36BW0gBje4DOz6Ba6SVk0xiKgt+q2JOFyr4SYfnu+Ic1QZYIuwHBrgzr6UvOcSCzPTOo7D6IC4ISeS7zkl4h+2VoeHpnG/uWR3+ysNgPcOIXQbv0n4mr3BwQcdKJxgPSeyuP/z1Jjg4e9nUvoXegqQVIE30EHx5GHv+FAVUNTowYDJgyFhf5IvlYmEqRif6+WN1MkEJmDcQITx9FX23a4mxy1AQRsOHO/+eImX9l8EMJI3oPWzVXxSOeHU1dUWYr2uAA7AMb+vAEZSbU3qob9ibCyXeypEMpZ6863o6QPqlqGHZkuWABSTVNd4cOh9hv3qEpSx2Zy/DJMP6cItEmiBJ5PFqQnDEIt3NrA3COlOSgz43D7gpNFNJ5MBh4oFzhDPiglC2ypsNU4ISywY2erkyb1NC3Qh/IfWj0eDgZI4/ln8WPfBsT3meTjq1Uqt1E7Zl/qftqkx6aM9KueMCekSnMrcHj1CqTWWzEzPsZGcDe3Ue4Ws+XFYVxNbOFF8ezkvQGR6ZOtOLU2lQEnMBStx47vE6Pb7AYMBRj2OOfZXfisjJnpTfSNjo6sZ6qSvNxZNmDeS7Gk3yYyCk1HtKN2UnhMIjOXUzAqDv90lx9O/q/AT1ZMnit5XQe9wmQxnE/WSH0CqZ9/2Hy+Sfmpeg8RwsHI5Z8kC8H293m/LHVVM/BA7HaTJYg5Enk7M/xWpq0192ACfBai2LA/qrCjCr6Dh1BIMzMXINBmX96MJ5Hn2nxln/RXPFhwHxUmSV0EV2V0jm86/dxxuYSU1W7sVkEbN9EzkG0QFwPhyHKyb3t+Fj5WoUUTErcazE/N6EW6Lvp0d//SDPj7EV9UdJN+Amnf3Wwk3A0SlJ9Z00yvXZ7n3z70G47Hfsow8Wq1JXcfwnA+Yxa5mFsgV464KKP4T31wqIgzFPd3eCe3j5ory5fBF2hgCFyVFrLzI9eetNXvM7oQqyFgDo4CTp/hDV9NMX9JDHQ/nyHTLvZLNLF6ftn2OxjGm8+PqOwhxnPHWipkE/8wbtyri80Sr7pMNkQGMfo4ZYK9OcCC4ESVFFbLMIvlxSoRqWie0wxqnLfcLSXMSpMMQEJYDVObYsXIQNv4TGNwjq1kvT1UOkicTrG3IaBZ3XdScS3u8sgeZPVpOLkbiF940FjbCeNRINNvDbd01EPBrTCPpm12m43ze1bBB59Ia6Ovhnur/Nvx3IxwSWol+3H2qfCJR8df6aQf4v6WiONxkK+IqT4pKQrZK/LplgDI/PJZbOep8dtbV7oCr6CgfpWa8NczOkPx81iSHbsNhVSJBOtrLIMrL31LK9TqHqAbAHe0RLmmV806kRLDLNEhUEJfm9u0sxpkL93Zgd6rw+tqBfTMi59xqXHLXSHwSbSBl0EK0+loECOPtrl+/nsaFe197di4yUgoe4jKoAJDXc6DGDjrQOoFDWZJ9HXwt8xDrQP+7aRwWKWI1GF8s8O4KzxWBBcwnl3vnl1Oez3oh6Ea1vjR7/z7DDTrFtqU2W/KAEzAuXDNZ7MY73MF216dzdSbWmUp4lcm7keJfWaMHgut9x5C9mj66Z0lJ+yhsjVvyiWrfk1lzPOTdhG15Y7gQlXtacvI7qv/XNSscDwqkgwHT/gUsD5yB7LdRRvJxQGYINn9hTpodKFVSTPrtGvyQw+HlRFXIkodErAGu9Iy1YpfSPc3jkFh5CX3lPxv7aqjE/JAfTIpEjGb/H7MO0e2vsViSW1qa/Lmi4/n4DEI3g7lYrcanspDfEpKkdV1OjSLOy0BCUqVoECaB55vs06rXl4jqmLsPsFM/7vYJ0vrBhDCm/00A/H81l1uekJ/6Lml3Hb9+NKiLqATJmDpyzfYZFHumEjC662L0Bwkxi7E9U4cQA0XMVDuMYAIeLMPgQaMVOd8fmt5SflFIfuBoszeAw7ow5gXPE2Y/yBc/7jExARUf/BxIHQBF5Sn3i61w4z5xJdCyO1F1X3+3ax+JSvMeZ7S6QSKp1Fp/sjYz6Z+VgCZzibGeEoujryfMulH7Rai5kAft9ebcW50DyJr2uo2z97mTWIu45YsSnNSMrrNUuG1XsYBtD9TDYzQffKB87vWbkM4EbPAFgoBV4GQS+vtFDUqOFAoi1nTtmIOvg38N4hT2Sn8r8clmBCXspBlMBYTnrqFJGBT3wZOzAyJDre9dHH7+x7qaaKDOB4UQALD5ecS0DE4obubQEiuJZ0EpBVpLuYcce8Aa4PYd/V4DLDAJBYKQPCWTcrEaZ5HYbJi11Gd6hjGom1ii18VHYnG28NKpkz2UKVPxlhYSp8uZr367iOmoy7zsxehW9wzcy2zG0a80PBMCRQMb32hnaHeOR8fnNDzZhaNYhkOdDsBUZ3loDMa1YP0uS0cjUP3b/6DBlqmZOeNABDsLl5BI5QJups8uxAuWJdkUB/pO6Zax6tsg7fN5mjjDgMGngO+DPcKqiHIDbFIGudxtPTIyDi9SFMKBDcfdGQRv41q1AqmxgkVfJMnP8w/Bc7N9/TR6C7mGObFqFkIEom8sKi2xYqJLTCHK7cxzaZvqODo22c3wisBCP4HeAgcRbNPAsBkNRhSmD48dHupdBRw4mIvtS5oeF6zeT1KMCyhMnmhpkFAGWnGscoNkwvQ8ZM5lE/vgTHFYL99OuNxdFBxTEDd5v2qLR8y9WkXsWgG6kZNndFG+pO/UAkOCipqIhL3hq7cRSdrCq7YhUsTocEcnaFa6nVkhnSeRYUA1YO0z5itF9Sly3VlxYDw239TJJH6f3EUfYO5lb7bcFcz8Bp7Oo8QmnsUHOz/fagVUBtKEw1iT88j+aKkv8cscKNkMxjYr8344D1kFoZ7/td1W6LCNYN594301tUGRmFjAzeRg5vyoM1F6+bJZ/Q54jN/k8SFd3DxPTYaAUsivsBfgTn7Mx8H2SpPt4GOdYRnEJOH6jHM2p6SgB0gzIRq6fHxGMmSmqaPCmlfwxiuloaVIitLGN8wie2CDWhkzLoCJcODh7KIOAqbHEvXdUxaS4TTTs07Clzj/6GmVs9kiZDerMxEnhUB6QQPlcfqkG9882RqHoLiHGBoHfQuXIsAG8GTAtao2KVwRnvvam8jo1e312GQAKWEa4sUVEAMG4G6ckcONDwRcg1e2D3+ohXgY4UAWF8wHKQMrSnzCgfFpsxh+aHXMGtPQroQasRY4U6UdG0rz1Vjbka0MekOGRZQEvqQFlxseFor8zWFgHek3v29+WqN6gaK5gZOTOMZzpQIC1201LkMCXild3vWXSc5UX9xcFYfbRPzGFa1FDcPfPB/jUEq/FeGt419CI3YmBlVoHsa4KdcwQP5ZSwHHhFJ7/Ph/Rap/4vmG91eDwPP0lDfCDRCLszTqfzM71xpmiKi2HwS4WlqvGNwtvwF5Dqpn6KTq8ax00UMPkxDcZrEEEsIvHiUXXEphdb4GB4FymlPwBz4Gperqq5pW7TQ6/yNRhW8VT5NhuP0udlxo4gILq5ZxAZk8ZGh3g4CqxJlPKY7AQxupfUcVpWT5VItp1+30UqoyP4wWsRo3olRRgkWZZ2ZN6VC3OZFeXB8NbnUrSdikNptD1QiGuKkr8EmSR/AK9Rw+FF3s5uwuPbvHGiPeFOViltMK7AUaOsq9+x9cndk3iJEE5LKZRlWJbKOZweROzmPNVPkjE3K/TyA57Rs68TkZ3MR8akKpm7cFjnjPd/DdkWjgYoKHSr5Wu5ssoBYU4acRs5g2DHxUmdq8VXOXRbunD8QN0LhgkssgahcdoYsNvuXGUK/KXD/7oFb+VGdhqIn02veuM5bLudJOc2Ky0GMaG4W/xWBxIJcL7yliJOXOpx0AkBqUgzlDczmLT4iILXDxxtRR1oZa2JWFgiAb43obrJnG/TZC2KSK2wqOzRZTXavZZFMb1f3bXvVaNaK828w9TO610gk8JNf3gMfETzXXsbcvRGCG9JWQZ6+cDPqc4466Yo2RcKH+PILeKOqtnlbInR3MmBeGG3FH10yzkybuqEC2HSQwpA0An7d9+73BkDUTm30bZmoP/RGbgFN+GrCOfADgqr0WbI1a1okpFms8iHYw9hm0zUvlEMivBRxModrbJJ+9/p3jUdQQ9BCtQdxnOGrT5dzRUmw0593/mbRSdBg0nRvRZM5/E16m7ZHmDEtWhwvfdZCZ8J8M12W0yRMszXamWfQTwIZ4ayYktrnscQuWr8idp3PjT2eF/jmtdhIfcpMnb+IfZY2FebW6UY/AK3jP4u3Tu4zE4qlnQgLFbM19EBIsNf7KhjdbqQ/D6yiDb+NlEi2SKD+ivXVUK8ib0oBo366gXkR8ZxGjpJIDcEgZPa9TcYe0TIbiPl/rPUQDu3XBJ9X/GNq3FAUsKsll57DzaGMrjcT+gctp+9MLYXCq+sqP81eVQ0r9lt+gcQfZbACRbEjvlMskztZG8gbC8Qn9tt26Q7y7nDrbZq/LEz7kR6Jc6pg3N9rVX8Y5MJrGlML9p9lU4jbTkKqCveeZUJjHB03m2KRKR2TytoFkTXOLg7keU1s1lrPMQJpoOKLuAAC+y1HlJucU6ysB5hsXhvSPPLq5J7JtnqHKZ4vYjC4Vy8153QY+6780xDuGARsGbOs1WqzH0QS765rnSKEbbKlkO8oI/VDwUd0is13tKpqILu1mDJFNy/iJAWcvDgjxvusIT+PGz3ST/J9r9Mtfd0jpaGeiLYIqXc7DiHSS8TcjFVksi66PEkxW1z6ujbLLUGNNYnzOWpH8BZGK4bCK7iR+MbIv8ncDAz1u4StN3vTTzewr9IQjk9wxFxn+6N1ddKs0vffJiS08N3a4G1SVrlZ97Q/M+8G9fe5AP6d9/Qq4WRnORVhofPIKEdCr3llspUfE0oKIIYoByBRPh+bX1HLS3JWGJRhIvE1aW4NTd8ePi4Z+kXb+Z8snYfSNcqijhAgVsx4RCM54cXUiYkjeBmmC4ajOHrChoELscJJC7+9jjMjw5BagZKlgRMiSNYz7h7vvZIoQqbtQmspc0cUk1G/73iXtSpROl5wtLgQi0mW2Ex8i3WULhcggx6E1LMVHUsdc9GHI1PH3U2Ko0PyGdn9KdVOLm7FPBui0i9a0HpA60MsewVE4z8CAt5d401Gv6zXlIT5Ybit1VIA0FCs7wtvYreru1fUyW3oLAZ/+aTnZrOcYRNVA8spoRtlRoWflsRClFcgzkqiHOrf0/SVw+EpVaFlJ0g4Kxq1MMOmiQdpMNpte8lMMQqm6cIFXlnGbfJllysKDi+0JJMotkqgIxOSQgU9dn/lWkeVf8nUm3iwX2Nl3WDw9i6AUK3vBAbZZrcJpDQ/N64AVwjT07Jef30GSSmtNu2WlW7YoyW2FlWfZFQUwk867EdLYKk9VG6JgEnBiBxkY7LMo4YLQJJlAo9l/oTvJkSARDF/XtyAzM8O2t3eT/iXa6wDN3WewNmQHdPfsxChU/KtLG2Mn8i4ZqKdSlIaBZadxJmRzVS/o4yA65RTSViq60oa395Lqw0pzY4SipwE0SXXsKV+GZraGSkr/RW08wPRvqvSUkYBMA9lPx4m24az+IHmCbXA+0faxTRE9wuGeO06DIXa6QlKJ3puIyiuAVfPr736vzo2pBirS+Vxel3TMm3JKhz9o2ZoRvaFVpIkykb0Hcm4oHFBMcNSNj7/4GJt43ogonY2Vg4nsDQIWxAcorpXACzgBqQPjYsE/VUpXpwNManEru4NwMCFPkXvMoqvoeLN3qyu/N1eWEHttMD65v19l/0kH2mR35iv/FI+yjoHJ9gPMz67af3Mq/BoWXqu3rphiWMXVkmnPSEkpGpUI2h1MThideGFEOK6YZHPwYzMBvpNC7+ZHxPb7epfefGyIB4JzO9DTNEYnDLVVHdQyvOEVefrk6Uv5kTQYVYWWdqrdcIl7yljwwIWdfQ/y+2QB3eR/qxYObuYyB4gTbo2in4PzarU1sO9nETkmj9/AoxDA+JM3GMqQtJR4jtduHtnoCLxd1gQUscHRB/MoRYIEsP2pDZ9KvHgtlk1iTbWWbHhohwFEYX7y51fUV2nuUmnoUcqnWIQAAgl9LTVX+Bc0QGNEhChxHR4YjfE51PUdGfsSFE6ck7BL3/hTf9jLq4G1IafINxOLKeAtO7quulYvH5YOBc+zX7CrMgWnW47/jfRsWnJjYYoE7xMfWV2HN2iyIqLI");const t=()=>EP(e),r=()=>new Set(t()),n=(e,t)=>t.forEach((t=>e.add(t)));YP=new Map(SP(e)),XP=r(),eT=t(),tT=new Set(t().map((e=>eT[e]))),eT=new Set(eT),rT=r(),r();let i=AP(e),s=e();const o=()=>{let e=new Set;return t().forEach((t=>n(e,i[t]))),n(e,t()),e};nT=kP((t=>{let r=kP(e).map((e=>e+96));if(r.length){let n=t>=s;return r[0]-=32,r=TP(r),n&&(r=`Restricted[${r}]`),{N:r,P:o(),Q:o(),M:!e(),R:n}}})),iT=r(),sT=new Map;let a=t().concat(JP(iT)).sort(((e,t)=>e-t));a.forEach(((t,r)=>{let n=e(),i=a[r]=n?a[r-n]:{V:[],M:new Map};i.V.push(t),iT.has(t)||sT.set(t,i)}));for(let{V:e,M:t}of new Set(sT.values())){let r=[];for(let t of e){let e=nT.filter((e=>QP(e,t))),i=r.find((({G:t})=>e.some((e=>t.has(e)))));i||(i={G:new Set,V:[]},r.push(i)),i.V.push(t),n(i.G,e)}let i=r.flatMap((e=>JP(e.G)));for(let{G:e,V:n}of r){let r=new Set(i.filter((t=>!e.has(t))));for(let e of n)t.set(e,r)}}oT=new Set;let c=new Set;const u=e=>oT.has(e)?c.add(e):oT.add(e);for(let e of nT){for(let t of e.P)u(t);for(let t of e.Q)u(t)}for(let e of oT)sT.has(e)||c.has(e)||sT.set(e,1);n(oT,HP(oT)),aT=function(e){let t=[],r=EP(e);return function e({S:r,B:n},i,s){if(!(4&r&&s===i[i.length-1])){2&r&&(s=i[i.length-1]),1&r&&t.push(i);for(let t of n)for(let r of t.Q)e(t,[...i,r],s)}}(function t(n){return{S:e(),B:kP((()=>{let n=EP(e).map((e=>r[e]));if(n.length)return t(n)})),Q:n}}([]),[]),t}(e).map((e=>ZP.from(e))).sort(_P),cT=new Map;for(let e of aT){let t=[cT];for(let r of e){let e=t.map((e=>{let t=e.get(r);return t||(t=new Map,e.set(r,t)),t}));65039===r?t.push(...e):t=e}for(let r of t)r.V=e}}function lT(e){return(fT(e)?"":`${hT(dT([e]))} `)+PP(e)}function hT(e){return`"${e}"‎`}function dT(e,t=1/0,r=PP){let n=[];var i;i=e[0],uT(),eT.has(i)&&n.push("◌"),e.length>t&&(t>>=1,e=[...e.slice(0,t),8230,...e.slice(-t)]);let s=0,o=e.length;for(let t=0;t<o;t++){let i=e[t];fT(i)&&(n.push(TP(e.slice(s,t))),n.push(r(i)),s=t+1)}return n.push(TP(e.slice(s,o))),n.join("")}function fT(e){return uT(),rT.has(e)}function pT(e){return function(e){return e.map((({input:t,error:r,output:n})=>{if(r){let n=r.message;throw new Error(1==e.length?n:`Invalid label ${hT(dT(t,63))}: ${n}`)}return TP(n)})).join(WP)}(function(e,t,r){if(!e)return[];uT();let n=0;return e.split(WP).map((e=>{let i=function(e){let t=[];for(let r=0,n=e.length;r<n;){let n=e.codePointAt(r);r+=n<65536?1:2,t.push(n)}return t}(e),s={input:i,offset:n};n+=i.length+1;try{let e,n=s.tokens=function(e,t,r){let n=[],i=[];e=e.slice().reverse();for(;e.length;){let s=wT(e);if(s)i.length&&(n.push(t(i)),i=[]),n.push(r(s));else{let t=e.pop();if(oT.has(t))i.push(t);else{let e=YP.get(t);if(e)i.push(...e);else if(!XP.has(t))throw gT(t)}}}i.length&&n.push(t(i));return n}(i,t,r),o=n.length;if(!o)throw new Error("empty label");let a=s.output=n.flat();if(function(e){for(let t=e.lastIndexOf(95);t>0;)if(95!==e[--t])throw new Error("underscore allowed only at start")}(a),!(s.emoji=o>1||n[0].is_emoji)&&a.every((e=>e<128)))!function(e){if(e.length>=4&&45==e[2]&&45==e[3])throw new Error(`invalid label extension: "${TP(e.slice(0,4))}"`)}(a),e="ASCII";else{let t=n.flatMap((e=>e.is_emoji?[]:e));if(t.length){if(eT.has(a[0]))throw yT("leading combining mark");for(let e=1;e<o;e++){let t=n[e];if(!t.is_emoji&&eT.has(t[0]))throw yT(`emoji + combining mark: "${TP(n[e-1])} + ${dT([t[0]])}"`)}!function(e){let t=e[0],r=yP.get(t);if(r)throw yT(`leading ${r}`);let n=e.length,i=-1;for(let s=1;s<n;s++){t=e[s];let n=yP.get(t);if(n){if(i==s)throw yT(`${r} + ${n}`);i=s+1,r=n}}if(i==n)throw yT(`trailing ${r}`)}(a);let r=JP(new Set(t)),[i]=function(e){let t=nT;for(let r of e){let e=t.filter((e=>QP(e,r)));if(!e.length)throw nT.some((e=>QP(e,r)))?mT(t[0],r):gT(r);if(t=e,1==e.length)break}return t}(r);!function(e,t){for(let r of t)if(!QP(e,r))throw mT(e,r);if(e.M){let e=HP(t);for(let t=1,r=e.length;t<r;t++)if(tT.has(e[t])){let n=t+1;for(let i;n<r&&tT.has(i=e[n]);n++)for(let r=t;r<n;r++)if(e[r]==i)throw new Error(`duplicate non-spacing marks: ${lT(i)}`);if(n-t>4)throw new Error(`excessive non-spacing marks: ${hT(dT(e.slice(t-1,n)))} (${n-t}/4)`);t=n}}}(i,t),function(e,t){let r,n=[];for(let e of t){let t=sT.get(e);if(1===t)return;if(t){let n=t.M.get(e);if(r=r?r.filter((e=>n.has(e))):JP(n),!r.length)return}else n.push(e)}if(r)for(let t of r)if(n.every((e=>QP(t,e))))throw new Error(`whole-script confusable: ${e.N}/${t.N}`)}(i,r),e=i.N}else e="Emoji"}s.type=e}catch(e){s.error=e}return s}))}(e,$P,bT))}function gT(e){return new Error(`disallowed character: ${lT(e)}`)}function mT(e,t){let r=lT(t),n=nT.find((e=>e.P.has(t)));return n&&(r=`${n.N} ${r}`),new Error(`illegal mixture: ${e.N} + ${r}`)}function yT(e){return new Error(`illegal placement: ${e}`)}function bT(e){return e.filter((e=>65039!=e))}function wT(e,t){let r,n=cT,i=e.length;for(;i&&(n=n.get(e[--i]),n);){let{V:t}=n;t&&(r=t,e.length=i)}return r}const vT=new Uint8Array(32);function ET(e){return DA(0!==e.length,"invalid ENS name; empty component","comp",e),e}function AT(e){const t=ES(function(e){try{if(0===e.length)throw new Error("empty label");return pT(e)}catch(t){DA(!1,`invalid ENS name (${t.message})`,"name",e)}}(e)),r=[];if(0===e.length)return r;let n=0;for(let e=0;e<t.length;e++){46===t[e]&&(r.push(ET(t.slice(n,e))),n=e+1)}return DA(n<t.length,"invalid ENS name; empty component","name",e),r.push(ET(t.slice(n))),r}function ST(e){DA("string"==typeof e,"invalid ENS name; not a string","name",e),DA(e.length,"invalid ENS name (empty label)","name",e);let t=vT;const r=AT(e);for(;r.length;)t=xR($A([t,xR(r.pop())]));return HA(t)}function kT(e,t){const r=t;return DA(r<=255,"DNS encoded label cannot exceed 255","length",r),HA($A(AT(e).map((t=>{DA(t.length<=r,`label ${JSON.stringify(e)} exceeds ${r} bytes`,"name",e);const n=new Uint8Array(t.length+1);return n.set(t,1),n[0]=n.length-1,n}))))+"00"}function RT(e,t){return{address:GI(e),storageKeys:t.map(((e,t)=>(DA(KA(e,32),"invalid slot",`storageKeys[${t}]`,e),e.toLowerCase())))}}function CT(e){if(Array.isArray(e))return e.map(((t,r)=>Array.isArray(t)?(DA(2===t.length,"invalid slot set",`value[${r}]`,t),RT(t[0],t[1])):(DA(null!=t&&"object"==typeof t,"invalid address-slot set","value",e),RT(t.address,t.storageKeys))));DA(null!=e&&"object"==typeof e,"invalid access list","value",e);const t=Object.keys(e).map((t=>{const r=e[t].reduce(((e,t)=>(e[t]=!0,e)),{});return RT(t,Object.keys(r).sort())}));return t.sort(((e,t)=>e.address.localeCompare(t.address))),t}function IT(e){let t;return t="string"==typeof e?FI.computePublicKey(e,!1):e.publicKey,GI(xR("0x"+t.substring(4)).substring(26))}vT.fill(0);const PT=BigInt(0),TT=BigInt(2),_T=BigInt(27),NT=BigInt(28),MT=BigInt(35),xT=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),OT=131072;function DT(e,t){let r=e.toString(16);for(;r.length<2;)r="0"+r;return r+=AC(t).substring(4),"0x"+r}function BT(e){return"0x"===e?null:GI(e)}function LT(e,t){try{return CT(e)}catch(r){DA(!1,r.message,t,e)}}function FT(e,t){return"0x"===e?0:cS(e,t)}function UT(e,t){if("0x"===e)return PT;const r=iS(e,t);return DA(r<=xT,"value exceeds uint size",t,r),r}function jT(e,t){const r=iS(e,"value"),n=lS(r);return DA(n.length<=32,"value too large",`tx.${t}`,r),n}function qT(e){return CT(e).map((e=>[e.address,e.storageKeys]))}function zT(e,t){DA(Array.isArray(e),`invalid ${t}`,"value",e);for(let t=0;t<e.length;t++)DA(KA(e[t],32),"invalid ${ param } hash",`value[${t}]`,e[t]);return e}function KT(e,t){let r;try{if(r=FT(t[0],"yParity"),0!==r&&1!==r)throw new Error("bad yParity")}catch(e){DA(!1,"invalid yParity","yParity",t[0])}const n=ZA(t[1],32),i=ZA(t[2],32),s=LI.from({r:n,s:i,yParity:r});e.signature=s}class GT{#W;#J;#x;#Q;#Z;#Y;#X;#ee;#te;#re;#ne;#ie;#se;#oe;#ae;#ce;get type(){return this.#W}set type(e){switch(e){case null:this.#W=null;break;case 0:case"legacy":this.#W=0;break;case 1:case"berlin":case"eip-2930":this.#W=1;break;case 2:case"london":case"eip-1559":this.#W=2;break;case 3:case"cancun":case"eip-4844":this.#W=3;break;default:DA(!1,"unsupported transaction type","type",e)}}get typeName(){switch(this.type){case 0:return"legacy";case 1:return"eip-2930";case 2:return"eip-1559";case 3:return"eip-4844"}return null}get to(){const e=this.#J;return null==e&&3===this.type?CI:e}set to(e){this.#J=null==e?null:GI(e)}get nonce(){return this.#Q}set nonce(e){this.#Q=cS(e,"value")}get gasLimit(){return this.#Z}set gasLimit(e){this.#Z=iS(e)}get gasPrice(){const e=this.#Y;return null!=e||0!==this.type&&1!==this.type?e:PT}set gasPrice(e){this.#Y=null==e?null:iS(e,"gasPrice")}get maxPriorityFeePerGas(){const e=this.#X;return null==e?2===this.type||3===this.type?PT:null:e}set maxPriorityFeePerGas(e){this.#X=null==e?null:iS(e,"maxPriorityFeePerGas")}get maxFeePerGas(){const e=this.#ee;return null==e?2===this.type||3===this.type?PT:null:e}set maxFeePerGas(e){this.#ee=null==e?null:iS(e,"maxFeePerGas")}get data(){return this.#x}set data(e){this.#x=HA(e)}get value(){return this.#te}set value(e){this.#te=iS(e,"value")}get chainId(){return this.#re}set chainId(e){this.#re=iS(e)}get signature(){return this.#ne||null}set signature(e){this.#ne=null==e?null:LI.from(e)}get accessList(){const e=this.#ie||null;return null==e?1===this.type||2===this.type||3===this.type?[]:null:e}set accessList(e){this.#ie=null==e?null:CT(e)}get maxFeePerBlobGas(){const e=this.#se;return null==e&&3===this.type?PT:e}set maxFeePerBlobGas(e){this.#se=null==e?null:iS(e,"maxFeePerBlobGas")}get blobVersionedHashes(){let e=this.#oe;return null==e&&3===this.type?[]:e}set blobVersionedHashes(e){if(null!=e){DA(Array.isArray(e),"blobVersionedHashes must be an Array","value",e),e=e.slice();for(let t=0;t<e.length;t++)DA(KA(e[t],32),"invalid blobVersionedHash",`value[${t}]`,e[t])}this.#oe=e}get blobs(){return null==this.#ce?null:this.#ce.map((e=>Object.assign({},e)))}set blobs(e){if(null==e)return void(this.#ce=null);const t=[],r=[];for(let n=0;n<e.length;n++){const i=e[n];if(GA(i)){OA(this.#ae,"adding a raw blob requires a KZG library","UNSUPPORTED_OPERATION",{operation:"set blobs()"});let e=qA(i);if(DA(e.length<=OT,"blob is too large",`blobs[${n}]`,i),e.length!==OT){const t=new Uint8Array(OT);t.set(e),e=t}const s=this.#ae.blobToKzgCommitment(e),o=HA(this.#ae.computeBlobKzgProof(e,s));t.push({data:HA(e),commitment:HA(s),proof:o}),r.push(DT(1,s))}else{const e=HA(i.commitment);t.push({data:HA(i.data),commitment:e,proof:HA(i.proof)}),r.push(DT(1,e))}}this.#ce=t,this.#oe=r}get kzg(){return this.#ae}set kzg(e){this.#ae=e}constructor(){this.#W=null,this.#J=null,this.#Q=0,this.#Z=PT,this.#Y=null,this.#X=null,this.#ee=null,this.#x="0x",this.#te=PT,this.#re=PT,this.#ne=null,this.#ie=null,this.#se=null,this.#oe=null,this.#ce=null,this.#ae=null}get hash(){return null==this.signature?null:xR(this.#ue(!0,!1))}get unsignedHash(){return xR(this.unsignedSerialized)}get from(){return null==this.signature?null:function(e,t){return IT(FI.recoverPublicKey(e,t))}(this.unsignedHash,this.signature)}get fromPublicKey(){return null==this.signature?null:FI.recoverPublicKey(this.unsignedHash,this.signature)}isSigned(){return null!=this.signature}#ue(e,t){OA(!e||null!=this.signature,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});const r=e?this.signature:null;switch(this.inferType()){case 0:return function(e,t){const r=[jT(e.nonce,"nonce"),jT(e.gasPrice||0,"gasPrice"),jT(e.gasLimit,"gasLimit"),e.to||"0x",jT(e.value,"value"),e.data];let n=PT;if(e.chainId!=PT)n=iS(e.chainId,"tx.chainId"),DA(!t||null==t.networkV||t.legacyChainId===n,"tx.chainId/sig.v mismatch","sig",t);else if(e.signature){const t=e.signature.legacyChainId;null!=t&&(n=t)}if(!t)return n!==PT&&(r.push(lS(n)),r.push("0x"),r.push("0x")),tk(r);let i=BigInt(27+t.yParity);return n!==PT?i=LI.getChainIdV(n,t.v):BigInt(t.v)!==i&&DA(!1,"tx.chainId/sig.v mismatch","sig",t),r.push(lS(i)),r.push(lS(t.r)),r.push(lS(t.s)),tk(r)}(this,r);case 1:return function(e,t){const r=[jT(e.chainId,"chainId"),jT(e.nonce,"nonce"),jT(e.gasPrice||0,"gasPrice"),jT(e.gasLimit,"gasLimit"),e.to||"0x",jT(e.value,"value"),e.data,qT(e.accessList||[])];return t&&(r.push(jT(t.yParity,"recoveryParam")),r.push(lS(t.r)),r.push(lS(t.s))),$A(["0x01",tk(r)])}(this,r);case 2:return function(e,t){const r=[jT(e.chainId,"chainId"),jT(e.nonce,"nonce"),jT(e.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),jT(e.maxFeePerGas||0,"maxFeePerGas"),jT(e.gasLimit,"gasLimit"),e.to||"0x",jT(e.value,"value"),e.data,qT(e.accessList||[])];return t&&(r.push(jT(t.yParity,"yParity")),r.push(lS(t.r)),r.push(lS(t.s))),$A(["0x02",tk(r)])}(this,r);case 3:return function(e,t,r){const n=[jT(e.chainId,"chainId"),jT(e.nonce,"nonce"),jT(e.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),jT(e.maxFeePerGas||0,"maxFeePerGas"),jT(e.gasLimit,"gasLimit"),e.to||CI,jT(e.value,"value"),e.data,qT(e.accessList||[]),jT(e.maxFeePerBlobGas||0,"maxFeePerBlobGas"),zT(e.blobVersionedHashes||[],"blobVersionedHashes")];return t&&(n.push(jT(t.yParity,"yParity")),n.push(lS(t.r)),n.push(lS(t.s)),r)?$A(["0x03",tk([n,r.map((e=>e.data)),r.map((e=>e.commitment)),r.map((e=>e.proof))])]):$A(["0x03",tk(n)])}(this,r,t?this.blobs:null)}OA(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:".serialized"})}get serialized(){return this.#ue(!0,!0)}get unsignedSerialized(){return this.#ue(!1,!1)}inferType(){const e=this.inferTypes();return e.indexOf(2)>=0?2:e.pop()}inferTypes(){const e=null!=this.gasPrice,t=null!=this.maxFeePerGas||null!=this.maxPriorityFeePerGas,r=null!=this.accessList,n=null!=this.#se||this.#oe;null!=this.maxFeePerGas&&null!=this.maxPriorityFeePerGas&&OA(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this}),OA(!t||0!==this.type&&1!==this.type,"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas","BAD_DATA",{value:this}),OA(0!==this.type||!r,"legacy transaction cannot have accessList","BAD_DATA",{value:this});const i=[];return null!=this.type?i.push(this.type):t?i.push(2):e?(i.push(1),r||i.push(0)):r?(i.push(1),i.push(2)):(n&&this.to||(i.push(0),i.push(1),i.push(2)),i.push(3)),i.sort(),i}isLegacy(){return 0===this.type}isBerlin(){return 1===this.type}isLondon(){return 2===this.type}isCancun(){return 3===this.type}clone(){return GT.from(this)}toJSON(){const e=e=>null==e?null:e.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:e(this.gasLimit),gasPrice:e(this.gasPrice),maxPriorityFeePerGas:e(this.maxPriorityFeePerGas),maxFeePerGas:e(this.maxFeePerGas),value:e(this.value),chainId:e(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}static from(e){if(null==e)return new GT;if("string"==typeof e){const t=qA(e);if(t[0]>=127)return GT.from(function(e){const t=ZS(e);DA(Array.isArray(t)&&(9===t.length||6===t.length),"invalid field count for legacy transaction","data",e);const r={type:0,nonce:FT(t[0],"nonce"),gasPrice:UT(t[1],"gasPrice"),gasLimit:UT(t[2],"gasLimit"),to:BT(t[3]),value:UT(t[4],"value"),data:HA(t[5]),chainId:PT};if(6===t.length)return r;const n=UT(t[6],"v"),i=UT(t[7],"r"),s=UT(t[8],"s");if(i===PT&&s===PT)r.chainId=n;else{let e=(n-MT)/TT;e<PT&&(e=PT),r.chainId=e,DA(e!==PT||n===_T||n===NT,"non-canonical legacy v","v",t[6]),r.signature=LI.from({r:ZA(t[7],32),s:ZA(t[8],32),v:n})}return r}(t));switch(t[0]){case 1:return GT.from(function(e){const t=ZS(qA(e).slice(1));DA(Array.isArray(t)&&(8===t.length||11===t.length),"invalid field count for transaction type: 1","data",HA(e));const r={type:1,chainId:UT(t[0],"chainId"),nonce:FT(t[1],"nonce"),gasPrice:UT(t[2],"gasPrice"),gasLimit:UT(t[3],"gasLimit"),to:BT(t[4]),value:UT(t[5],"value"),data:HA(t[6]),accessList:LT(t[7],"accessList")};return 8===t.length||KT(r,t.slice(8)),r}(t));case 2:return GT.from(function(e){const t=ZS(qA(e).slice(1));DA(Array.isArray(t)&&(9===t.length||12===t.length),"invalid field count for transaction type: 2","data",HA(e));const r={type:2,chainId:UT(t[0],"chainId"),nonce:FT(t[1],"nonce"),maxPriorityFeePerGas:UT(t[2],"maxPriorityFeePerGas"),maxFeePerGas:UT(t[3],"maxFeePerGas"),gasPrice:null,gasLimit:UT(t[4],"gasLimit"),to:BT(t[5]),value:UT(t[6],"value"),data:HA(t[7]),accessList:LT(t[8],"accessList")};return 9===t.length||KT(r,t.slice(9)),r}(t));case 3:return GT.from(function(e){let t=ZS(qA(e).slice(1)),r="3",n=null;if(4===t.length&&Array.isArray(t[0])){r="3 (network format)";const e=t[1],i=t[2],s=t[3];DA(Array.isArray(e),"invalid network format: blobs not an array","fields[1]",e),DA(Array.isArray(i),"invalid network format: commitments not an array","fields[2]",i),DA(Array.isArray(s),"invalid network format: proofs not an array","fields[3]",s),DA(e.length===i.length,"invalid network format: blobs/commitments length mismatch","fields",t),DA(e.length===s.length,"invalid network format: blobs/proofs length mismatch","fields",t),n=[];for(let r=0;r<t[1].length;r++)n.push({data:e[r],commitment:i[r],proof:s[r]});t=t[0]}DA(Array.isArray(t)&&(11===t.length||14===t.length),`invalid field count for transaction type: ${r}`,"data",HA(e));const i={type:3,chainId:UT(t[0],"chainId"),nonce:FT(t[1],"nonce"),maxPriorityFeePerGas:UT(t[2],"maxPriorityFeePerGas"),maxFeePerGas:UT(t[3],"maxFeePerGas"),gasPrice:null,gasLimit:UT(t[4],"gasLimit"),to:BT(t[5]),value:UT(t[6],"value"),data:HA(t[7]),accessList:LT(t[8],"accessList"),maxFeePerBlobGas:UT(t[9],"maxFeePerBlobGas"),blobVersionedHashes:t[10]};n&&(i.blobs=n),DA(null!=i.to,`invalid address for transaction type: ${r}`,"data",e),DA(Array.isArray(i.blobVersionedHashes),"invalid blobVersionedHashes: must be an array","data",e);for(let t=0;t<i.blobVersionedHashes.length;t++)DA(KA(i.blobVersionedHashes[t],32),`invalid blobVersionedHash at index ${t}: must be length 32`,"data",e);return 11===t.length||KT(i,t.slice(11)),i}(t))}OA(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:"from"})}const t=new GT;return null!=e.type&&(t.type=e.type),null!=e.to&&(t.to=e.to),null!=e.nonce&&(t.nonce=e.nonce),null!=e.gasLimit&&(t.gasLimit=e.gasLimit),null!=e.gasPrice&&(t.gasPrice=e.gasPrice),null!=e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),null!=e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),null!=e.maxFeePerBlobGas&&(t.maxFeePerBlobGas=e.maxFeePerBlobGas),null!=e.data&&(t.data=e.data),null!=e.value&&(t.value=e.value),null!=e.chainId&&(t.chainId=e.chainId),null!=e.signature&&(t.signature=LI.from(e.signature)),null!=e.accessList&&(t.accessList=e.accessList),null!=e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes),null!=e.kzg&&(t.kzg=e.kzg),null!=e.blobs&&(t.blobs=e.blobs),null!=e.hash&&(DA(t.isSigned(),"unsigned transaction cannot define '.hash'","tx",e),DA(t.hash===e.hash,"hash mismatch","tx",e)),null!=e.from&&(DA(t.isSigned(),"unsigned transaction cannot define '.from'","tx",e),DA(t.from.toLowerCase()===(e.from||"").toLowerCase(),"from mismatch","tx",e)),t}}const VT=new Uint8Array(32);VT.fill(0);const HT=BigInt(-1),$T=BigInt(0),WT=BigInt(1),JT=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const QT=uS(WT,32),ZT=uS($T,32),YT={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},XT=["name","version","chainId","verifyingContract","salt"];function e_(e){return function(t){return DA("string"==typeof t,`invalid domain value for ${JSON.stringify(e)}`,`domain.${e}`,t),t}}const t_={name:e_("name"),version:e_("version"),chainId:function(e){const t=iS(e,"domain.chainId");return DA(t>=0,"invalid chain ID","domain.chainId",e),Number.isSafeInteger(t)?Number(t):hS(t)},verifyingContract:function(e){try{return GI(e).toLowerCase()}catch(e){}DA(!1,'invalid domain value "verifyingContract"',"domain.verifyingContract",e)},salt:function(e){const t=qA(e,"domain.salt");return DA(32===t.length,'invalid domain value "salt"',"domain.salt",e),HA(t)}};function r_(e){{const t=e.match(/^(u?)int(\d+)$/);if(t){const r=""===t[1],n=parseInt(t[2]);DA(n%8==0&&0!==n&&n<=256&&t[2]===String(n),"invalid numeric width","type",e);const i=nS(JT,r?n-1:n),s=r?(i+WT)*HT:$T;return function(t){const n=iS(t,"value");return DA(n>=s&&n<=i,`value out-of-bounds for ${e}`,"value",n),uS(r?rS(n,256):n,32)}}}{const t=e.match(/^bytes(\d+)$/);if(t){const r=parseInt(t[1]);return DA(0!==r&&r<=32&&t[1]===String(r),"invalid bytes width","type",e),function(t){return DA(qA(t).length===r,`invalid length for ${e}`,"value",t),function(e){const t=qA(e),r=t.length%32;return r?$A([t,VT.slice(r)]):HA(t)}(t)}}}switch(e){case"address":return function(e){return ZA(GI(e),32)};case"bool":return function(e){return e?QT:ZT};case"bytes":return function(e){return xR(e)};case"string":return function(e){return mP(e)}}return null}function n_(e,t){return`${e}(${t.map((({name:e,type:t})=>t+" "+e)).join(",")})`}function i_(e){const t=e.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return t?{base:t[1],index:t[2]+t[4],array:{base:t[1],prefix:t[1]+t[2],count:t[5]?parseInt(t[5]):-1}}:{base:e}}class s_{primaryType;#le;get types(){return JSON.parse(this.#le)}#he;#de;constructor(e){this.#he=new Map,this.#de=new Map;const t=new Map,r=new Map,n=new Map,i={};Object.keys(e).forEach((s=>{i[s]=e[s].map((({name:t,type:r})=>{let{base:n,index:i}=i_(r);return"int"!==n||e.int||(n="int256"),"uint"!==n||e.uint||(n="uint256"),{name:t,type:n+(i||"")}})),t.set(s,new Set),r.set(s,[]),n.set(s,new Set)})),this.#le=JSON.stringify(i);for(const n in i){const s=new Set;for(const o of i[n]){DA(!s.has(o.name),`duplicate variable name ${JSON.stringify(o.name)} in ${JSON.stringify(n)}`,"types",e),s.add(o.name);const i=i_(o.type).base;DA(i!==n,`circular type reference to ${JSON.stringify(i)}`,"types",e);r_(i)||(DA(r.has(i),`unknown type ${JSON.stringify(i)}`,"types",e),r.get(i).push(n),t.get(n).add(i))}}const s=Array.from(r.keys()).filter((e=>0===r.get(e).length));DA(0!==s.length,"missing primary type","types",e),DA(1===s.length,`ambiguous primary types or unused types: ${s.map((e=>JSON.stringify(e))).join(", ")}`,"types",e),TA(this,{primaryType:s[0]}),function i(s,o){DA(!o.has(s),`circular type reference to ${JSON.stringify(s)}`,"types",e),o.add(s);for(const e of t.get(s))if(r.has(e)){i(e,o);for(const t of o)n.get(t).add(e)}o.delete(s)}(this.primaryType,new Set);for(const[e,t]of n){const r=Array.from(t);r.sort(),this.#he.set(e,n_(e,i[e])+r.map((e=>n_(e,i[e]))).join(""))}}getEncoder(e){let t=this.#de.get(e);return t||(t=this.#fe(e),this.#de.set(e,t)),t}#fe(e){{const t=r_(e);if(t)return t}const t=i_(e).array;if(t){const e=t.prefix,r=this.getEncoder(e);return n=>{DA(-1===t.count||t.count===n.length,`array length mismatch; expected length ${t.count}`,"value",n);let i=n.map(r);return this.#he.has(e)&&(i=i.map(xR)),xR($A(i))}}const r=this.types[e];if(r){const t=mP(this.#he.get(e));return e=>{const n=r.map((({name:t,type:r})=>{const n=this.getEncoder(r)(e[t]);return this.#he.has(r)?xR(n):n}));return n.unshift(t),$A(n)}}DA(!1,`unknown type: ${e}`,"type",e)}encodeType(e){const t=this.#he.get(e);return DA(t,`unknown type: ${JSON.stringify(e)}`,"name",e),t}encodeData(e,t){return this.getEncoder(e)(t)}hashStruct(e,t){return xR(this.encodeData(e,t))}encode(e){return this.encodeData(this.primaryType,e)}hash(e){return this.hashStruct(this.primaryType,e)}_visit(e,t,r){if(r_(e))return r(e,t);const n=i_(e).array;if(n)return DA(-1===n.count||n.count===t.length,`array length mismatch; expected length ${n.count}`,"value",t),t.map((e=>this._visit(n.prefix,e,r)));const i=this.types[e];if(i)return i.reduce(((e,{name:n,type:i})=>(e[n]=this._visit(i,t[n],r),e)),{});DA(!1,`unknown type: ${e}`,"type",e)}visit(e,t){return this._visit(this.primaryType,e,t)}static from(e){return new s_(e)}static getPrimaryType(e){return s_.from(e).primaryType}static hashStruct(e,t,r){return s_.from(t).hashStruct(e,r)}static hashDomain(e){const t=[];for(const r in e){if(null==e[r])continue;const n=YT[r];DA(n,`invalid typed-data domain key: ${JSON.stringify(r)}`,"domain",e),t.push({name:r,type:n})}return t.sort(((e,t)=>XT.indexOf(e.name)-XT.indexOf(t.name))),s_.hashStruct("EIP712Domain",{EIP712Domain:t},e)}static encode(e,t,r){return $A(["0x1901",s_.hashDomain(e),s_.from(t).hash(r)])}static hash(e,t,r){return xR(s_.encode(e,t,r))}static async resolveNames(e,t,r,n){e=Object.assign({},e);for(const t in e)null==e[t]&&delete e[t];const i={};e.verifyingContract&&!KA(e.verifyingContract,20)&&(i[e.verifyingContract]="0x");const s=s_.from(t);s.visit(r,((e,t)=>("address"!==e||KA(t,20)||(i[t]="0x"),t)));for(const e in i)i[e]=await n(e);return e.verifyingContract&&i[e.verifyingContract]&&(e.verifyingContract=i[e.verifyingContract]),{domain:e,value:r=s.visit(r,((e,t)=>"address"===e&&i[t]?i[t]:t))}}static getPayload(e,t,r){s_.hashDomain(e);const n={},i=[];XT.forEach((t=>{const r=e[t];null!=r&&(n[t]=t_[t](r),i.push({name:t,type:YT[t]}))}));const s=s_.from(t);t=s.types;const o=Object.assign({},t);return DA(null==o.EIP712Domain,"types must not contain EIP712Domain type","types.EIP712Domain",t),o.EIP712Domain=i,s.encode(r),{types:o,domain:n,primaryType:s.primaryType,message:s.visit(r,((e,t)=>{if(e.match(/^bytes(\d*)/))return HA(qA(t));if(e.match(/^u?int/))return iS(t).toString();switch(e){case"address":return t.toLowerCase();case"bool":return!!t;case"string":return DA("string"==typeof t,"invalid string","value",t),t}DA(!1,"unsupported type","type",e)}))}}}function o_(e){const t=new Set;return e.forEach((e=>t.add(e))),Object.freeze(t)}const a_=o_("external public payable override".split(" ")),c_="constant external internal payable private public pure view override",u_=o_(c_.split(" ")),l_="constructor error event fallback function receive struct",h_=o_(l_.split(" ")),d_="calldata memory storage payable indexed",f_=o_(d_.split(" ")),p_=o_([l_,d_,"tuple returns",c_].join(" ").split(" ")),g_={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},m_=new RegExp("^(\\s*)"),y_=new RegExp("^([0-9]+)"),b_=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),w_=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),v_=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class E_{#B;#pe;get offset(){return this.#B}get length(){return this.#pe.length-this.#B}constructor(e){this.#B=0,this.#pe=e.slice()}clone(){return new E_(this.#pe)}reset(){this.#B=0}#ge(e=0,t=0){return new E_(this.#pe.slice(e,t).map((t=>Object.freeze(Object.assign({},t,{match:t.match-e,linkBack:t.linkBack-e,linkNext:t.linkNext-e})))))}popKeyword(e){const t=this.peek();if("KEYWORD"!==t.type||!e.has(t.text))throw new Error(`expected keyword ${t.text}`);return this.pop().text}popType(e){if(this.peek().type!==e){const t=this.peek();throw new Error(`expected ${e}; got ${t.type} ${JSON.stringify(t.text)}`)}return this.pop().text}popParen(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=this.#ge(this.#B+1,e.match+1);return this.#B=e.match+1,t}popParams(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=[];for(;this.#B<e.match-1;){const e=this.peek().linkNext;t.push(this.#ge(this.#B+1,e)),this.#B=e}return this.#B=e.match+1,t}peek(){if(this.#B>=this.#pe.length)throw new Error("out-of-bounds");return this.#pe[this.#B]}peekKeyword(e){const t=this.peekType("KEYWORD");return null!=t&&e.has(t)?t:null}peekType(e){if(0===this.length)return null;const t=this.peek();return t.type===e?t.text:null}pop(){const e=this.peek();return this.#B++,e}toString(){const e=[];for(let t=this.#B;t<this.#pe.length;t++){const r=this.#pe[t];e.push(`${r.type}:${r.text}`)}return`<TokenString ${e.join(" ")}>`}}function A_(e){const t=[],r=t=>{const r=s<e.length?JSON.stringify(e[s]):"$EOI";throw new Error(`invalid token ${r} at ${s}: ${t}`)};let n=[],i=[],s=0;for(;s<e.length;){let o=e.substring(s),a=o.match(m_);a&&(s+=a[1].length,o=e.substring(s));const c={depth:n.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:s,value:-1};t.push(c);let u=g_[o[0]]||"";if(u){if(c.type=u,c.text=o[0],s++,"OPEN_PAREN"===u)n.push(t.length-1),i.push(t.length-1);else if("CLOSE_PAREN"==u)0===n.length&&r("no matching open bracket"),c.match=n.pop(),t[c.match].match=t.length-1,c.depth--,c.linkBack=i.pop(),t[c.linkBack].linkNext=t.length-1;else if("COMMA"===u)c.linkBack=i.pop(),t[c.linkBack].linkNext=t.length-1,i.push(t.length-1);else if("OPEN_BRACKET"===u)c.type="BRACKET";else if("CLOSE_BRACKET"===u){let e=t.pop().text;if(t.length>0&&"NUMBER"===t[t.length-1].type){const r=t.pop().text;e=r+e,t[t.length-1].value=cS(r)}if(0===t.length||"BRACKET"!==t[t.length-1].type)throw new Error("missing opening bracket");t[t.length-1].text+=e}}else if(a=o.match(b_),a){if(c.text=a[1],s+=c.text.length,p_.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(v_)){c.type="TYPE";continue}c.type="ID"}else{if(a=o.match(y_),!a)throw new Error(`unexpected token ${JSON.stringify(o[0])} at position ${s}`);c.text=a[1],c.type="NUMBER",s+=c.text.length}}return new E_(t.map((e=>Object.freeze(e))))}function S_(e,t){let r=[];for(const n in t.keys())e.has(n)&&r.push(n);if(r.length>1)throw new Error(`conflicting types: ${r.join(", ")}`)}function k_(e,t){if(t.peekKeyword(h_)){const r=t.pop().text;if(r!==e)throw new Error(`expected ${e}, got ${r}`)}return t.popType("ID")}function R_(e,t){const r=new Set;for(;;){const n=e.peekType("KEYWORD");if(null==n||t&&!t.has(n))break;if(e.pop(),r.has(n))throw new Error(`duplicate keywords: ${JSON.stringify(n)}`);r.add(n)}return Object.freeze(r)}function C_(e){let t=R_(e,u_);return S_(t,o_("constant payable nonpayable".split(" "))),S_(t,o_("pure view payable nonpayable".split(" "))),t.has("view")?"view":t.has("pure")?"pure":t.has("payable")?"payable":t.has("nonpayable")?"nonpayable":t.has("constant")?"view":"nonpayable"}function I_(e,t){return e.popParams().map((e=>q_.from(e,t)))}function P_(e){if(e.peekType("AT")){if(e.pop(),e.peekType("NUMBER"))return iS(e.pop().text);throw new Error("invalid gas")}return null}function T_(e){if(e.length)throw new Error(`unexpected tokens at offset ${e.offset}: ${e.toString()}`)}const __=new RegExp(/^(.*)\[([0-9]*)\]$/);function N_(e){const t=e.match(v_);if(DA(t,"invalid type","type",e),"uint"===e)return"uint256";if("int"===e)return"int256";if(t[2]){const r=parseInt(t[2]);DA(0!==r&&r<=32,"invalid bytes length","type",e)}else if(t[3]){const r=parseInt(t[3]);DA(0!==r&&r<=256&&r%8==0,"invalid numeric width","type",e)}return e}const M_={},x_=Symbol.for("_ethers_internal"),O_="_ParamTypeInternal",D_="_ErrorInternal",B_="_EventInternal",L_="_ConstructorInternal",F_="_FallbackInternal",U_="_FunctionInternal",j_="_StructInternal";class q_{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(e,t,r,n,i,s,o,a){if(UA(e,M_,"ParamType"),Object.defineProperty(this,x_,{value:O_}),s&&(s=Object.freeze(s.slice())),"array"===n){if(null==o||null==a)throw new Error("")}else if(null!=o||null!=a)throw new Error("");if("tuple"===n){if(null==s)throw new Error("")}else if(null!=s)throw new Error("");TA(this,{name:t,type:r,baseType:n,indexed:i,components:s,arrayLength:o,arrayChildren:a})}format(e){if(null==e&&(e="sighash"),"json"===e){const t=this.name||"";if(this.isArray()){const e=JSON.parse(this.arrayChildren.format("json"));return e.name=t,e.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(e)}const r={type:"tuple"===this.baseType?"tuple":this.type,name:t};return"boolean"==typeof this.indexed&&(r.indexed=this.indexed),this.isTuple()&&(r.components=this.components.map((t=>JSON.parse(t.format(e))))),JSON.stringify(r)}let t="";return this.isArray()?(t+=this.arrayChildren.format(e),t+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?t+="("+this.components.map((t=>t.format(e))).join("full"===e?", ":",")+")":t+=this.type,"sighash"!==e&&(!0===this.indexed&&(t+=" indexed"),"full"===e&&this.name&&(t+=" "+this.name)),t}isArray(){return"array"===this.baseType}isTuple(){return"tuple"===this.baseType}isIndexable(){return null!=this.indexed}walk(e,t){if(this.isArray()){if(!Array.isArray(e))throw new Error("invalid array value");if(-1!==this.arrayLength&&e.length!==this.arrayLength)throw new Error("array is wrong length");const r=this;return e.map((e=>r.arrayChildren.walk(e,t)))}if(this.isTuple()){if(!Array.isArray(e))throw new Error("invalid tuple value");if(e.length!==this.components.length)throw new Error("array is wrong length");const r=this;return e.map(((e,n)=>r.components[n].walk(e,t)))}return t(this.type,e)}#me(e,t,r,n){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(-1!==this.arrayLength&&t.length!==this.arrayLength)throw new Error("array is wrong length");const i=this.arrayChildren,s=t.slice();return s.forEach(((t,n)=>{i.#me(e,t,r,(e=>{s[n]=e}))})),void n(s)}if(this.isTuple()){const i=this.components;let s;if(Array.isArray(t))s=t.slice();else{if(null==t||"object"!=typeof t)throw new Error("invalid tuple value");s=i.map((e=>{if(!e.name)throw new Error("cannot use object value with unnamed components");if(!(e.name in t))throw new Error(`missing value for component ${e.name}`);return t[e.name]}))}if(s.length!==this.components.length)throw new Error("array is wrong length");return s.forEach(((t,n)=>{i[n].#me(e,t,r,(e=>{s[n]=e}))})),void n(s)}const i=r(this.type,t);i.then?e.push(async function(){n(await i)}()):n(i)}async walkAsync(e,t){const r=[],n=[e];return this.#me(r,e,t,(e=>{n[0]=e})),r.length&&await Promise.all(r),n[0]}static from(e,t){if(q_.isParamType(e))return e;if("string"==typeof e)try{return q_.from(A_(e),t)}catch(t){DA(!1,"invalid param type","obj",e)}else if(e instanceof E_){let r="",n="",i=null;R_(e,o_(["tuple"])).has("tuple")||e.peekType("OPEN_PAREN")?(n="tuple",i=e.popParams().map((e=>q_.from(e))),r=`tuple(${i.map((e=>e.format())).join(",")})`):(r=N_(e.popType("TYPE")),n=r);let s=null,o=null;for(;e.length&&e.peekType("BRACKET");){const t=e.pop();s=new q_(M_,"",r,n,null,i,o,s),o=t.value,r+=t.text,n="array",i=null}let a=null;if(R_(e,f_).has("indexed")){if(!t)throw new Error("");a=!0}const c=e.peekType("ID")?e.pop().text:"";if(e.length)throw new Error("leftover tokens");return new q_(M_,c,r,n,a,i,o,s)}const r=e.name;DA(!r||"string"==typeof r&&r.match(w_),"invalid name","obj.name",r);let n=e.indexed;null!=n&&(DA(t,"parameter cannot be indexed","obj.indexed",e.indexed),n=!!n);let i=e.type,s=i.match(__);if(s){const t=parseInt(s[2]||"-1"),o=q_.from({type:s[1],components:e.components});return new q_(M_,r||"",i,"array",n,null,t,o)}if("tuple"===i||i.startsWith("tuple(")||i.startsWith("(")){const t=null!=e.components?e.components.map((e=>q_.from(e))):null;return new q_(M_,r||"",i,"tuple",n,t,null,null)}return i=N_(e.type),new q_(M_,r||"",i,i,n,null,null,null)}static isParamType(e){return e&&e[x_]===O_}}class z_{type;inputs;constructor(e,t,r){UA(e,M_,"Fragment"),TA(this,{type:t,inputs:r=Object.freeze(r.slice())})}static from(e){if("string"==typeof e){try{z_.from(JSON.parse(e))}catch(e){}return z_.from(A_(e))}if(e instanceof E_){switch(e.peekKeyword(h_)){case"constructor":return $_.from(e);case"error":return V_.from(e);case"event":return H_.from(e);case"fallback":case"receive":return W_.from(e);case"function":return J_.from(e);case"struct":return Q_.from(e)}}else if("object"==typeof e){switch(e.type){case"constructor":return $_.from(e);case"error":return V_.from(e);case"event":return H_.from(e);case"fallback":case"receive":return W_.from(e);case"function":return J_.from(e);case"struct":return Q_.from(e)}OA(!1,`unsupported type: ${e.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}DA(!1,"unsupported frgament object","obj",e)}static isConstructor(e){return $_.isFragment(e)}static isError(e){return V_.isFragment(e)}static isEvent(e){return H_.isFragment(e)}static isFunction(e){return J_.isFragment(e)}static isStruct(e){return Q_.isFragment(e)}}class K_ extends z_{name;constructor(e,t,r,n){super(e,t,n),DA("string"==typeof r&&r.match(w_),"invalid identifier","name",r),n=Object.freeze(n.slice()),TA(this,{name:r})}}function G_(e,t){return"("+t.map((t=>t.format(e))).join("full"===e?", ":",")+")"}class V_ extends K_{constructor(e,t,r){super(e,"error",t,r),Object.defineProperty(this,x_,{value:D_})}get selector(){return mP(this.format("sighash")).substring(0,10)}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map((t=>JSON.parse(t.format(e))))});const t=[];return"sighash"!==e&&t.push("error"),t.push(this.name+G_(e,this.inputs)),t.join(" ")}static from(e){if(V_.isFragment(e))return e;if("string"==typeof e)return V_.from(A_(e));if(e instanceof E_){const t=k_("error",e),r=I_(e);return T_(e),new V_(M_,t,r)}return new V_(M_,e.name,e.inputs?e.inputs.map(q_.from):[])}static isFragment(e){return e&&e[x_]===D_}}class H_ extends K_{anonymous;constructor(e,t,r,n){super(e,"event",t,r),Object.defineProperty(this,x_,{value:B_}),TA(this,{anonymous:n})}get topicHash(){return mP(this.format("sighash"))}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map((t=>JSON.parse(t.format(e))))});const t=[];return"sighash"!==e&&t.push("event"),t.push(this.name+G_(e,this.inputs)),"sighash"!==e&&this.anonymous&&t.push("anonymous"),t.join(" ")}static getTopicHash(e,t){t=(t||[]).map((e=>q_.from(e)));return new H_(M_,e,t,!1).topicHash}static from(e){if(H_.isFragment(e))return e;if("string"==typeof e)try{return H_.from(A_(e))}catch(t){DA(!1,"invalid event fragment","obj",e)}else if(e instanceof E_){const t=k_("event",e),r=I_(e,!0),n=!!R_(e,o_(["anonymous"])).has("anonymous");return T_(e),new H_(M_,t,r,n)}return new H_(M_,e.name,e.inputs?e.inputs.map((e=>q_.from(e,!0))):[],!!e.anonymous)}static isFragment(e){return e&&e[x_]===B_}}class $_ extends z_{payable;gas;constructor(e,t,r,n,i){super(e,t,r),Object.defineProperty(this,x_,{value:L_}),TA(this,{payable:n,gas:i})}format(e){if(OA(null!=e&&"sighash"!==e,"cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),"json"===e)return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map((t=>JSON.parse(t.format(e))))});const t=[`constructor${G_(e,this.inputs)}`];return this.payable&&t.push("payable"),null!=this.gas&&t.push(`@${this.gas.toString()}`),t.join(" ")}static from(e){if($_.isFragment(e))return e;if("string"==typeof e)try{return $_.from(A_(e))}catch(t){DA(!1,"invalid constuctor fragment","obj",e)}else if(e instanceof E_){R_(e,o_(["constructor"]));const t=I_(e),r=!!R_(e,a_).has("payable"),n=P_(e);return T_(e),new $_(M_,"constructor",t,r,n)}return new $_(M_,"constructor",e.inputs?e.inputs.map(q_.from):[],!!e.payable,null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[x_]===L_}}class W_ extends z_{payable;constructor(e,t,r){super(e,"fallback",t),Object.defineProperty(this,x_,{value:F_}),TA(this,{payable:r})}format(e){const t=0===this.inputs.length?"receive":"fallback";if("json"===e){const e=this.payable?"payable":"nonpayable";return JSON.stringify({type:t,stateMutability:e})}return`${t}()${this.payable?" payable":""}`}static from(e){if(W_.isFragment(e))return e;if("string"==typeof e)try{return W_.from(A_(e))}catch(t){DA(!1,"invalid fallback fragment","obj",e)}else if(e instanceof E_){const t=e.toString();DA(e.peekKeyword(o_(["fallback","receive"])),"type must be fallback or receive","obj",t);if("receive"===e.popKeyword(o_(["fallback","receive"]))){const t=I_(e);return DA(0===t.length,"receive cannot have arguments","obj.inputs",t),R_(e,o_(["payable"])),T_(e),new W_(M_,[],!0)}let r=I_(e);r.length?DA(1===r.length&&"bytes"===r[0].type,"invalid fallback inputs","obj.inputs",r.map((e=>e.format("minimal"))).join(", ")):r=[q_.from("bytes")];const n=C_(e);if(DA("nonpayable"===n||"payable"===n,"fallback cannot be constants","obj.stateMutability",n),R_(e,o_(["returns"])).has("returns")){const t=I_(e);DA(1===t.length&&"bytes"===t[0].type,"invalid fallback outputs","obj.outputs",t.map((e=>e.format("minimal"))).join(", "))}return T_(e),new W_(M_,r,"payable"===n)}if("receive"===e.type)return new W_(M_,[],!0);if("fallback"===e.type){const t=[q_.from("bytes")],r="payable"===e.stateMutability;return new W_(M_,t,r)}DA(!1,"invalid fallback description","obj",e)}static isFragment(e){return e&&e[x_]===F_}}class J_ extends K_{constant;outputs;stateMutability;payable;gas;constructor(e,t,r,n,i,s){super(e,"function",t,n),Object.defineProperty(this,x_,{value:U_});TA(this,{constant:"view"===r||"pure"===r,gas:s,outputs:i=Object.freeze(i.slice()),payable:"payable"===r,stateMutability:r})}get selector(){return mP(this.format("sighash")).substring(0,10)}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:"nonpayable"!==this.stateMutability?this.stateMutability:void 0,payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map((t=>JSON.parse(t.format(e)))),outputs:this.outputs.map((t=>JSON.parse(t.format(e))))});const t=[];return"sighash"!==e&&t.push("function"),t.push(this.name+G_(e,this.inputs)),"sighash"!==e&&("nonpayable"!==this.stateMutability&&t.push(this.stateMutability),this.outputs&&this.outputs.length&&(t.push("returns"),t.push(G_(e,this.outputs))),null!=this.gas&&t.push(`@${this.gas.toString()}`)),t.join(" ")}static getSelector(e,t){t=(t||[]).map((e=>q_.from(e)));return new J_(M_,e,"view",t,[],null).selector}static from(e){if(J_.isFragment(e))return e;if("string"==typeof e)try{return J_.from(A_(e))}catch(t){DA(!1,"invalid function fragment","obj",e)}else if(e instanceof E_){const t=k_("function",e),r=I_(e),n=C_(e);let i=[];R_(e,o_(["returns"])).has("returns")&&(i=I_(e));const s=P_(e);return T_(e),new J_(M_,t,n,r,i,s)}let t=e.stateMutability;return null==t&&(t="payable","boolean"==typeof e.constant?(t="view",e.constant||(t="payable","boolean"!=typeof e.payable||e.payable||(t="nonpayable"))):"boolean"!=typeof e.payable||e.payable||(t="nonpayable")),new J_(M_,e.name,t,e.inputs?e.inputs.map(q_.from):[],e.outputs?e.outputs.map(q_.from):[],null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[x_]===U_}}class Q_ extends K_{constructor(e,t,r){super(e,"struct",t,r),Object.defineProperty(this,x_,{value:j_})}format(){throw new Error("@TODO")}static from(e){if("string"==typeof e)try{return Q_.from(A_(e))}catch(t){DA(!1,"invalid struct fragment","obj",e)}else if(e instanceof E_){const t=k_("struct",e),r=I_(e);return T_(e),new Q_(M_,t,r)}return new Q_(M_,e.name,e.inputs?e.inputs.map(q_.from):[])}static isFragment(e){return e&&e[x_]===j_}}const Z_=new Map;Z_.set(0,"GENERIC_PANIC"),Z_.set(1,"ASSERT_FALSE"),Z_.set(17,"OVERFLOW"),Z_.set(18,"DIVIDE_BY_ZERO"),Z_.set(33,"ENUM_RANGE_ERROR"),Z_.set(34,"BAD_STORAGE_DATA"),Z_.set(49,"STACK_UNDERFLOW"),Z_.set(50,"ARRAY_RANGE_ERROR"),Z_.set(65,"OUT_OF_MEMORY"),Z_.set(81,"UNINITIALIZED_FUNCTION_CALL");const Y_=new RegExp(/^bytes([0-9]*)$/),X_=new RegExp(/^(u?int)([0-9]*)$/);let eN=null,tN=1024;class rN{#ye(e){if(e.isArray())return new nP(this.#ye(e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new gP(e.components.map((e=>this.#ye(e))),e.name);switch(e.baseType){case"address":return new XI(e.name);case"bool":return new iP(e.name);case"string":return new pP(e.name);case"bytes":return new oP(e.name);case"":return new uP(e.name)}let t=e.type.match(X_);if(t){let r=parseInt(t[2]||"256");return DA(0!==r&&r<=256&&r%8==0,"invalid "+t[1]+" bit length","param",e),new fP(r/8,"int"===t[1],e.name)}if(t=e.type.match(Y_),t){let r=parseInt(t[1]);return DA(0!==r&&r<=32,"invalid bytes length","param",e),new aP(r,e.name)}DA(!1,"invalid type","type",e.type)}getDefaultValue(e){const t=e.map((e=>this.#ye(q_.from(e))));return new gP(t,"_").defaultValue()}encode(e,t){BA(t.length,e.length,"types/values length mismatch");const r=e.map((e=>this.#ye(q_.from(e)))),n=new gP(r,"_"),i=new mk;return n.encode(i,t),i.data}decode(e,t,r){const n=e.map((e=>this.#ye(q_.from(e))));return new gP(n,"_").decode(new yk(t,r,tN))}static _setDefaultMaxInflation(e){DA("number"==typeof e&&Number.isInteger(e),"invalid defaultMaxInflation factor","value",e),tN=e}static defaultAbiCoder(){return null==eN&&(eN=new rN),eN}static getBuiltinCallException(e,t,r){return function(e,t,r,n){let i="missing revert data",s=null,o=null;if(r){i="execution reverted";const e=qA(r);if(r=HA(r),0===e.length)i+=" (no data present; likely require(false) occurred",s="require(false)";else if(e.length%32!=4)i+=" (could not decode reason; invalid data length)";else if("0x08c379a0"===HA(e.slice(0,4)))try{s=n.decode(["string"],e.slice(4))[0],o={signature:"Error(string)",name:"Error",args:[s]},i+=`: ${JSON.stringify(s)}`}catch(e){i+=" (could not decode reason; invalid string data)"}else if("0x4e487b71"===HA(e.slice(0,4)))try{const t=Number(n.decode(["uint256"],e.slice(4))[0]);o={signature:"Panic(uint256)",name:"Panic",args:[t]},s=`Panic due to ${Z_.get(t)||"UNKNOWN"}(${t})`,i+=`: ${s}`}catch(e){i+=" (could not decode panic code)"}else i+=" (unknown custom error)"}const a={to:t.to?GI(t.to):null,data:t.data||"0x"};return t.from&&(a.from=GI(t.from)),xA(i,"CALL_EXCEPTION",{action:e,data:r,reason:s,transaction:a,invocation:null,revert:o})}(e,t,r,rN.defaultAbiCoder())}}class nN{fragment;name;signature;topic;args;constructor(e,t,r){const n=e.name,i=e.format();TA(this,{fragment:e,name:n,signature:i,topic:t,args:r})}}class iN{fragment;name;args;signature;selector;value;constructor(e,t,r,n){const i=e.name,s=e.format();TA(this,{fragment:e,name:i,args:r,signature:s,selector:t,value:n})}}class sN{fragment;name;args;signature;selector;constructor(e,t,r){const n=e.name,i=e.format();TA(this,{fragment:e,name:n,args:r,signature:i,selector:t})}}class oN{hash;_isIndexed;static isIndexed(e){return!(!e||!e._isIndexed)}constructor(e){TA(this,{hash:e,_isIndexed:!0})}}const aN={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},cN={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:e=>`reverted with reason string ${JSON.stringify(e)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:e=>{let t="unknown panic code";return e>=0&&e<=255&&aN[e.toString()]&&(t=aN[e.toString()]),`reverted with panic code 0x${e.toString(16)} (${t})`}}};class uN{fragments;deploy;fallback;receive;#be;#we;#ve;#Ee;constructor(e){let t=[];t="string"==typeof e?JSON.parse(e):e,this.#ve=new Map,this.#be=new Map,this.#we=new Map;const r=[];for(const e of t)try{r.push(z_.from(e))}catch(t){console.log(`[Warning] Invalid Fragment ${JSON.stringify(e)}:`,t.message)}TA(this,{fragments:Object.freeze(r)});let n=null,i=!1;this.#Ee=this.getAbiCoder(),this.fragments.forEach(((e,t)=>{let r;switch(e.type){case"constructor":return this.deploy?void console.log("duplicate definition - constructor"):void TA(this,{deploy:e});case"fallback":return void(0===e.inputs.length?i=!0:(DA(!n||e.payable!==n.payable,"conflicting fallback fragments",`fragments[${t}]`,e),n=e,i=n.payable));case"function":r=this.#ve;break;case"event":r=this.#we;break;case"error":r=this.#be;break;default:return}const s=e.format();r.has(s)||r.set(s,e)})),this.deploy||TA(this,{deploy:$_.from("constructor()")}),TA(this,{fallback:n,receive:i})}format(e){const t=e?"minimal":"full",r=this.fragments.map((e=>e.format(t)));return r}formatJson(){const e=this.fragments.map((e=>e.format("json")));return JSON.stringify(e.map((e=>JSON.parse(e))))}getAbiCoder(){return rN.defaultAbiCoder()}#Ae(e,t,r){if(KA(e)){const t=e.toLowerCase();for(const e of this.#ve.values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const n=[];for(const[t,r]of this.#ve)t.split("(")[0]===e&&n.push(r);if(t){const e=t.length>0?t[t.length-1]:null;let r=t.length,i=!0;YI.isTyped(e)&&"overrides"===e.type&&(i=!1,r--);for(let e=n.length-1;e>=0;e--){const t=n[e].inputs.length;t===r||i&&t===r-1||n.splice(e,1)}for(let e=n.length-1;e>=0;e--){const r=n[e].inputs;for(let i=0;i<t.length;i++)if(YI.isTyped(t[i])){if(i>=r.length){if("overrides"===t[i].type)continue;n.splice(e,1);break}if(t[i].type!==r[i].baseType){n.splice(e,1);break}}}}if(1===n.length&&t&&t.length!==n[0].inputs.length){const e=t[t.length-1];(null==e||Array.isArray(e)||"object"!=typeof e)&&n.splice(0,1)}if(0===n.length)return null;if(n.length>1&&r){DA(!1,`ambiguous function description (i.e. matches ${n.map((e=>JSON.stringify(e.format()))).join(", ")})`,"key",e)}return n[0]}const n=this.#ve.get(J_.from(e).format());return n||null}getFunctionName(e){const t=this.#Ae(e,null,!1);return DA(t,"no matching function","key",e),t.name}hasFunction(e){return!!this.#Ae(e,null,!1)}getFunction(e,t){return this.#Ae(e,t||null,!0)}forEachFunction(e){const t=Array.from(this.#ve.keys());t.sort(((e,t)=>e.localeCompare(t)));for(let r=0;r<t.length;r++){const n=t[r];e(this.#ve.get(n),r)}}#Se(e,t,r){if(KA(e)){const t=e.toLowerCase();for(const e of this.#we.values())if(t===e.topicHash)return e;return null}if(-1===e.indexOf("(")){const n=[];for(const[t,r]of this.#we)t.split("(")[0]===e&&n.push(r);if(t){for(let e=n.length-1;e>=0;e--)n[e].inputs.length<t.length&&n.splice(e,1);for(let e=n.length-1;e>=0;e--){const r=n[e].inputs;for(let i=0;i<t.length;i++)if(YI.isTyped(t[i])&&t[i].type!==r[i].baseType){n.splice(e,1);break}}}if(0===n.length)return null;if(n.length>1&&r){DA(!1,`ambiguous event description (i.e. matches ${n.map((e=>JSON.stringify(e.format()))).join(", ")})`,"key",e)}return n[0]}const n=this.#we.get(H_.from(e).format());return n||null}getEventName(e){const t=this.#Se(e,null,!1);return DA(t,"no matching event","key",e),t.name}hasEvent(e){return!!this.#Se(e,null,!1)}getEvent(e,t){return this.#Se(e,t||null,!0)}forEachEvent(e){const t=Array.from(this.#we.keys());t.sort(((e,t)=>e.localeCompare(t)));for(let r=0;r<t.length;r++){const n=t[r];e(this.#we.get(n),r)}}getError(e,t){if(KA(e)){const t=e.toLowerCase();if(cN[t])return V_.from(cN[t].signature);for(const e of this.#be.values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const t=[];for(const[r,n]of this.#be)r.split("(")[0]===e&&t.push(n);if(0===t.length)return"Error"===e?V_.from("error Error(string)"):"Panic"===e?V_.from("error Panic(uint256)"):null;if(t.length>1){DA(!1,`ambiguous error description (i.e. ${t.map((e=>JSON.stringify(e.format()))).join(", ")})`,"name",e)}return t[0]}if("Error(string)"===(e=V_.from(e).format()))return V_.from("error Error(string)");if("Panic(uint256)"===e)return V_.from("error Panic(uint256)");const r=this.#be.get(e);return r||null}forEachError(e){const t=Array.from(this.#be.keys());t.sort(((e,t)=>e.localeCompare(t)));for(let r=0;r<t.length;r++){const n=t[r];e(this.#be.get(n),r)}}_decodeParams(e,t){return this.#Ee.decode(e,t)}_encodeParams(e,t){return this.#Ee.encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);DA(t,"unknown error","fragment",e),e=t}return DA(JA(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,"data",t),this._decodeParams(e.inputs,JA(t,4))}encodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);DA(t,"unknown error","fragment",e),e=t}return $A([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);DA(t,"unknown function","fragment",e),e=t}return DA(JA(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,"data",t),this._decodeParams(e.inputs,JA(t,4))}encodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);DA(t,"unknown function","fragment",e),e=t}return $A([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);DA(t,"unknown function","fragment",e),e=t}let r="invalid length for result data";const n=zA(t);if(n.length%32==0)try{return this.#Ee.decode(e.outputs,n)}catch(e){r="could not decode result data"}OA(!1,r,"BAD_DATA",{value:HA(n),info:{method:e.name,signature:e.format()}})}makeError(e,t){const r=qA(e,"data"),n=rN.getBuiltinCallException("call",t,r);if(n.message.startsWith("execution reverted (unknown custom error)")){const e=HA(r.slice(0,4)),t=this.getError(e);if(t)try{const e=this.#Ee.decode(t.inputs,r.slice(4));n.revert={name:t.name,signature:t.format(),args:e},n.reason=n.revert.signature,n.message=`execution reverted: ${n.reason}`}catch(e){n.message="execution reverted (coult not decode custom error)"}}const i=this.parseTransaction(t);return i&&(n.invocation={method:i.name,signature:i.signature,args:i.args}),n}encodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);DA(t,"unknown function","fragment",e),e=t}return HA(this.#Ee.encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if("string"==typeof e){const t=this.getEvent(e);DA(t,"unknown event","eventFragment",e),e=t}OA(t.length<=e.inputs.length,`too many arguments for ${e.format()}`,"UNEXPECTED_ARGUMENT",{count:t.length,expectedCount:e.inputs.length});const r=[];e.anonymous||r.push(e.topicHash);const n=(e,t)=>"string"===e.type?mP(t):"bytes"===e.type?xR(HA(t)):("bool"===e.type&&"boolean"==typeof t?t=t?"0x01":"0x00":e.type.match(/^u?int/)?t=uS(t):e.type.match(/^bytes/)?t=QA(t,32,!1):"address"===e.type&&this.#Ee.encode(["address"],[t]),ZA(HA(t),32));for(t.forEach(((t,i)=>{const s=e.inputs[i];s.indexed?null==t?r.push(null):"array"===s.baseType||"tuple"===s.baseType?DA(!1,"filtering with tuples or arrays not supported","contract."+s.name,t):Array.isArray(t)?r.push(t.map((e=>n(s,e)))):r.push(n(s,t)):DA(null==t,"cannot filter non-indexed parameters; must be null","contract."+s.name,t)}));r.length&&null===r[r.length-1];)r.pop();return r}encodeEventLog(e,t){if("string"==typeof e){const t=this.getEvent(e);DA(t,"unknown event","eventFragment",e),e=t}const r=[],n=[],i=[];return e.anonymous||r.push(e.topicHash),DA(t.length===e.inputs.length,"event arguments/values mismatch","values",t),e.inputs.forEach(((e,s)=>{const o=t[s];if(e.indexed)if("string"===e.type)r.push(mP(o));else if("bytes"===e.type)r.push(xR(o));else{if("tuple"===e.baseType||"array"===e.baseType)throw new Error("not implemented");r.push(this.#Ee.encode([e.type],[o]))}else n.push(e),i.push(o)})),{data:this.#Ee.encode(n,i),topics:r}}decodeEventLog(e,t,r){if("string"==typeof e){const t=this.getEvent(e);DA(t,"unknown event","eventFragment",e),e=t}if(null!=r&&!e.anonymous){const t=e.topicHash;DA(KA(r[0],32)&&r[0].toLowerCase()===t,"fragment/topic mismatch","topics[0]",r[0]),r=r.slice(1)}const n=[],i=[],s=[];e.inputs.forEach(((e,t)=>{e.indexed?"string"===e.type||"bytes"===e.type||"tuple"===e.baseType||"array"===e.baseType?(n.push(q_.from({type:"bytes32",name:e.name})),s.push(!0)):(n.push(e),s.push(!1)):(i.push(e),s.push(!1))}));const o=null!=r?this.#Ee.decode(n,$A(r)):null,a=this.#Ee.decode(i,t,!0),c=[],u=[];let l=0,h=0;return e.inputs.forEach(((e,t)=>{let r=null;if(e.indexed)if(null==o)r=new oN(null);else if(s[t])r=new oN(o[h++]);else try{r=o[h++]}catch(e){r=e}else try{r=a[l++]}catch(e){r=e}c.push(r),u.push(e.name||null)})),fk.fromItems(c,u)}parseTransaction(e){const t=qA(e.data,"tx.data"),r=iS(null!=e.value?e.value:0,"tx.value"),n=this.getFunction(HA(t.slice(0,4)));if(!n)return null;const i=this.#Ee.decode(n.inputs,t.slice(4));return new iN(n,n.selector,i,r)}parseCallResult(e){throw new Error("@TODO")}parseLog(e){const t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new nN(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){const t=HA(e),r=this.getError(JA(t,0,4));if(!r)return null;const n=this.#Ee.decode(r.inputs,JA(t,4));return new sN(r,r.selector,n)}static from(e){return e instanceof uN?e:"string"==typeof e?new uN(JSON.parse(e)):"function"==typeof e.formatJson?new uN(e.formatJson()):"function"==typeof e.format?new uN(e.format("json")):new uN(e)}}const lN=BigInt(0);function hN(e){return null==e?null:e}function dN(e){return null==e?null:e.toString()}class fN{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(e,t,r){TA(this,{gasPrice:hN(e),maxFeePerGas:hN(t),maxPriorityFeePerGas:hN(r)})}toJSON(){const{gasPrice:e,maxFeePerGas:t,maxPriorityFeePerGas:r}=this;return{_type:"FeeData",gasPrice:dN(e),maxFeePerGas:dN(t),maxPriorityFeePerGas:dN(r)}}}function pN(e){const t={};e.to&&(t.to=e.to),e.from&&(t.from=e.from),e.data&&(t.data=HA(e.data));const r="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const n of r)n in e&&null!=e[n]&&(t[n]=iS(e[n],`request.${n}`));const n="type,nonce".split(/,/);for(const r of n)r in e&&null!=e[r]&&(t[r]=cS(e[r],`request.${r}`));return e.accessList&&(t.accessList=CT(e.accessList)),"blockTag"in e&&(t.blockTag=e.blockTag),"enableCcipRead"in e&&(t.enableCcipRead=!!e.enableCcipRead),"customData"in e&&(t.customData=e.customData),"blobVersionedHashes"in e&&e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.slice()),"kzg"in e&&(t.kzg=e.kzg),"blobs"in e&&e.blobs&&(t.blobs=e.blobs.map((e=>GA(e)?HA(e):Object.assign({},e)))),t}class gN{provider;number;hash;timestamp;parentHash;parentBeaconBlockRoot;nonce;difficulty;gasLimit;gasUsed;stateRoot;receiptsRoot;blobGasUsed;excessBlobGas;miner;prevRandao;extraData;baseFeePerGas;#ke;constructor(e,t){this.#ke=e.transactions.map((e=>"string"!=typeof e?new bN(e,t):e)),TA(this,{provider:t,hash:hN(e.hash),number:e.number,timestamp:e.timestamp,parentHash:e.parentHash,parentBeaconBlockRoot:e.parentBeaconBlockRoot,nonce:e.nonce,difficulty:e.difficulty,gasLimit:e.gasLimit,gasUsed:e.gasUsed,blobGasUsed:e.blobGasUsed,excessBlobGas:e.excessBlobGas,miner:e.miner,prevRandao:hN(e.prevRandao),extraData:e.extraData,baseFeePerGas:hN(e.baseFeePerGas),stateRoot:e.stateRoot,receiptsRoot:e.receiptsRoot})}get transactions(){return this.#ke.map((e=>"string"==typeof e?e:e.hash))}get prefetchedTransactions(){const e=this.#ke.slice();return 0===e.length?[]:(OA("object"==typeof e[0],"transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),e)}toJSON(){const{baseFeePerGas:e,difficulty:t,extraData:r,gasLimit:n,gasUsed:i,hash:s,miner:o,prevRandao:a,nonce:c,number:u,parentHash:l,parentBeaconBlockRoot:h,stateRoot:d,receiptsRoot:f,timestamp:p,transactions:g}=this;return{_type:"Block",baseFeePerGas:dN(e),difficulty:dN(t),extraData:r,gasLimit:dN(n),gasUsed:dN(i),blobGasUsed:dN(this.blobGasUsed),excessBlobGas:dN(this.excessBlobGas),hash:s,miner:o,prevRandao:a,nonce:c,number:u,parentHash:l,timestamp:p,parentBeaconBlockRoot:h,stateRoot:d,receiptsRoot:f,transactions:g}}[Symbol.iterator](){let e=0;const t=this.transactions;return{next:()=>e<this.length?{value:t[e++],done:!1}:{value:void 0,done:!0}}}get length(){return this.#ke.length}get date(){return null==this.timestamp?null:new Date(1e3*this.timestamp)}async getTransaction(e){let t;if("number"==typeof e)t=this.#ke[e];else{const r=e.toLowerCase();for(const e of this.#ke){if("string"==typeof e){if(e!==r)continue;t=e;break}if(e.hash===r){t=e;break}}}if(null==t)throw new Error("no such tx");return"string"==typeof t?await this.provider.getTransaction(t):t}getPrefetchedTransaction(e){const t=this.prefetchedTransactions;if("number"==typeof e)return t[e];e=e.toLowerCase();for(const r of t)if(r.hash===e)return r;DA(!1,"no matching transaction","indexOrHash",e)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return{orphan:"drop-block",hash:(e=this).hash,number:e.number};var e}}class mN{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(e,t){this.provider=t;const r=Object.freeze(e.topics.slice());TA(this,{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,removed:e.removed,address:e.address,data:e.data,topics:r,index:e.index,transactionIndex:e.transactionIndex})}toJSON(){const{address:e,blockHash:t,blockNumber:r,data:n,index:i,removed:s,topics:o,transactionHash:a,transactionIndex:c}=this;return{_type:"log",address:e,blockHash:t,blockNumber:r,data:n,index:i,removed:s,topics:o,transactionHash:a,transactionIndex:c}}async getBlock(){const e=await this.provider.getBlock(this.blockHash);return OA(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransaction(){const e=await this.provider.getTransaction(this.transactionHash);return OA(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransactionReceipt(){const e=await this.provider.getTransactionReceipt(this.transactionHash);return OA(!!e,"failed to find transaction receipt","UNKNOWN_ERROR",{}),e}removedEvent(){return{orphan:"drop-log",log:{transactionHash:(e=this).transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,address:e.address,data:e.data,topics:Object.freeze(e.topics.slice()),index:e.index}};var e}}class yN{provider;to;from;contractAddress;hash;index;blockHash;blockNumber;logsBloom;gasUsed;blobGasUsed;cumulativeGasUsed;gasPrice;blobGasPrice;type;status;root;#Re;constructor(e,t){this.#Re=Object.freeze(e.logs.map((e=>new mN(e,t))));let r=lN;null!=e.effectiveGasPrice?r=e.effectiveGasPrice:null!=e.gasPrice&&(r=e.gasPrice),TA(this,{provider:t,to:e.to,from:e.from,contractAddress:e.contractAddress,hash:e.hash,index:e.index,blockHash:e.blockHash,blockNumber:e.blockNumber,logsBloom:e.logsBloom,gasUsed:e.gasUsed,cumulativeGasUsed:e.cumulativeGasUsed,blobGasUsed:e.blobGasUsed,gasPrice:r,blobGasPrice:e.blobGasPrice,type:e.type,status:e.status,root:e.root})}get logs(){return this.#Re}toJSON(){const{to:e,from:t,contractAddress:r,hash:n,index:i,blockHash:s,blockNumber:o,logsBloom:a,logs:c,status:u,root:l}=this;return{_type:"TransactionReceipt",blockHash:s,blockNumber:o,contractAddress:r,cumulativeGasUsed:dN(this.cumulativeGasUsed),from:t,gasPrice:dN(this.gasPrice),blobGasUsed:dN(this.blobGasUsed),blobGasPrice:dN(this.blobGasPrice),gasUsed:dN(this.gasUsed),hash:n,index:i,logs:c,logsBloom:a,root:l,status:u,to:e}}get length(){return this.logs.length}[Symbol.iterator](){let e=0;return{next:()=>e<this.length?{value:this.logs[e++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const e=await this.provider.getBlock(this.blockHash);if(null==e)throw new Error("TODO");return e}async getTransaction(){const e=await this.provider.getTransaction(this.hash);if(null==e)throw new Error("TODO");return e}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return vN(this)}reorderedEvent(e){return OA(!e||e.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),wN(this,e)}}class bN{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;gasPrice;maxPriorityFeePerGas;maxFeePerGas;maxFeePerBlobGas;data;value;chainId;signature;accessList;blobVersionedHashes;#Ce;constructor(e,t){this.provider=t,this.blockNumber=null!=e.blockNumber?e.blockNumber:null,this.blockHash=null!=e.blockHash?e.blockHash:null,this.hash=e.hash,this.index=e.index,this.type=e.type,this.from=e.from,this.to=e.to||null,this.gasLimit=e.gasLimit,this.nonce=e.nonce,this.data=e.data,this.value=e.value,this.gasPrice=e.gasPrice,this.maxPriorityFeePerGas=null!=e.maxPriorityFeePerGas?e.maxPriorityFeePerGas:null,this.maxFeePerGas=null!=e.maxFeePerGas?e.maxFeePerGas:null,this.maxFeePerBlobGas=null!=e.maxFeePerBlobGas?e.maxFeePerBlobGas:null,this.chainId=e.chainId,this.signature=e.signature,this.accessList=null!=e.accessList?e.accessList:null,this.blobVersionedHashes=null!=e.blobVersionedHashes?e.blobVersionedHashes:null,this.#Ce=-1}toJSON(){const{blockNumber:e,blockHash:t,index:r,hash:n,type:i,to:s,from:o,nonce:a,data:c,signature:u,accessList:l,blobVersionedHashes:h}=this;return{_type:"TransactionResponse",accessList:l,blockNumber:e,blockHash:t,blobVersionedHashes:h,chainId:dN(this.chainId),data:c,from:o,gasLimit:dN(this.gasLimit),gasPrice:dN(this.gasPrice),hash:n,maxFeePerGas:dN(this.maxFeePerGas),maxPriorityFeePerGas:dN(this.maxPriorityFeePerGas),maxFeePerBlobGas:dN(this.maxFeePerBlobGas),nonce:a,signature:u,to:s,index:r,type:i,value:dN(this.value)}}async getBlock(){let e=this.blockNumber;if(null==e){const t=await this.getTransaction();t&&(e=t.blockNumber)}if(null==e)return null;const t=this.provider.getBlock(e);if(null==t)throw new Error("TODO");return t}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(null==this.blockNumber){const{tx:e,blockNumber:t}=await PA({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return null==e||null==e.blockNumber?0:t-e.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(e,t){const r=null==e?1:e,n=null==t?0:t;let i=this.#Ce,s=-1,o=-1===i;const a=async()=>{if(o)return null;const{blockNumber:e,nonce:t}=await PA({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(t<this.nonce)return void(i=e);if(o)return null;const n=await this.getTransaction();if(!n||null==n.blockNumber)for(-1===s&&(s=i-3,s<this.#Ce&&(s=this.#Ce));s<=e;){if(o)return null;const t=await this.provider.getBlock(s,!0);if(null==t)return;for(const e of t)if(e===this.hash)return;for(let n=0;n<t.length;n++){const s=await t.getTransaction(n);if(s.from===this.from&&s.nonce===this.nonce){if(o)return null;const t=await this.provider.getTransactionReceipt(s.hash);if(null==t)return;if(e-t.blockNumber+1<r)return;let n="replaced";s.data===this.data&&s.to===this.to&&s.value===this.value?n="repriced":"0x"===s.data&&s.from===s.to&&s.value===lN&&(n="cancelled"),OA(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:"replaced"===n||"cancelled"===n,reason:n,replacement:s.replaceableTransaction(i),hash:s.hash,receipt:t})}}s++}},c=e=>{if(null==e||0!==e.status)return e;OA(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:e.to,from:e.from,data:""},receipt:e})},u=await this.provider.getTransactionReceipt(this.hash);if(0===r)return c(u);if(u){if(await u.confirmations()>=r)return c(u)}else if(await a(),0===r)return null;const l=new Promise(((e,t)=>{const s=[],u=()=>{s.forEach((e=>e()))};if(s.push((()=>{o=!0})),n>0){const e=setTimeout((()=>{u(),t(xA("wait for transaction timeout","TIMEOUT"))}),n);s.push((()=>{clearTimeout(e)}))}const l=async n=>{if(await n.confirmations()>=r){u();try{e(c(n))}catch(e){t(e)}}};if(s.push((()=>{this.provider.off(this.hash,l)})),this.provider.on(this.hash,l),i>=0){const e=async()=>{try{await a()}catch(e){if(NA(e,"TRANSACTION_REPLACED"))return u(),void t(e)}o||this.provider.once("block",e)};s.push((()=>{this.provider.off("block",e)})),this.provider.once("block",e)}}));return await l}isMined(){return null!=this.blockHash}isLegacy(){return 0===this.type}isBerlin(){return 1===this.type}isLondon(){return 2===this.type}isCancun(){return 3===this.type}removedEvent(){return OA(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),vN(this)}reorderedEvent(e){return OA(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),OA(!e||e.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),wN(this,e)}replaceableTransaction(e){DA(Number.isInteger(e)&&e>=0,"invalid startBlock","startBlock",e);const t=new bN(this,this.provider);return t.#Ce=e,t}}function wN(e,t){return{orphan:"reorder-transaction",tx:e,other:t}}function vN(e){return{orphan:"drop-transaction",tx:e}}class EN extends mN{interface;fragment;args;constructor(e,t,r){super(e,e.provider);TA(this,{args:t.decodeEventLog(r,e.data,e.topics),fragment:r,interface:t})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class AN extends mN{error;constructor(e,t){super(e,e.provider),TA(this,{error:t})}}class SN extends yN{#Ie;constructor(e,t,r){super(r,t),this.#Ie=e}get logs(){return super.logs.map((e=>{const t=e.topics.length?this.#Ie.getEvent(e.topics[0]):null;if(t)try{return new EN(e,this.#Ie,t)}catch(t){return new AN(e,t)}return e}))}}class kN extends bN{#Ie;constructor(e,t,r){super(r,t),this.#Ie=e}async wait(e,t){const r=await super.wait(e,t);return null==r?null:new SN(this.#Ie,this.provider,r)}}class RN extends bS{log;constructor(e,t,r,n){super(e,t,r),TA(this,{log:n})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class CN extends RN{constructor(e,t,r,n,i){super(e,t,r,new EN(i,e.interface,n));TA(this,{args:e.interface.decodeEventLog(n,this.log.data,this.log.topics),fragment:n})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const IN=BigInt(0);function PN(e){return e&&"function"==typeof e.call}function TN(e){return e&&"function"==typeof e.estimateGas}function _N(e){return e&&"function"==typeof e.resolveName}function NN(e){return e&&"function"==typeof e.sendTransaction}function MN(e){if(null!=e){if(_N(e))return e;if(e.provider)return e.provider}}class xN{#Pe;fragment;constructor(e,t,r){if(TA(this,{fragment:t}),t.inputs.length<r.length)throw new Error("too many arguments");const n=ON(e.runner,"resolveName"),i=_N(n)?n:null;this.#Pe=async function(){const n=await Promise.all(t.inputs.map(((e,t)=>null==r[t]?null:e.walkAsync(r[t],((e,t)=>"address"===e?Array.isArray(t)?Promise.all(t.map((e=>$I(e,i)))):$I(t,i):t)))));return e.interface.encodeFilterTopics(t,n)}()}getTopicFilter(){return this.#Pe}}function ON(e,t){return null==e?null:"function"==typeof e[t]?e:e.provider&&"function"==typeof e.provider[t]?e.provider:null}function DN(e){return null==e?null:e.provider||null}async function BN(e,t){const r=YI.dereference(e,"overrides");DA("object"==typeof r,"invalid overrides parameter","overrides",e);const n=pN(r);return DA(null==n.to||(t||[]).indexOf("to")>=0,"cannot override to","overrides.to",n.to),DA(null==n.data||(t||[]).indexOf("data")>=0,"cannot override data","overrides.data",n.data),n.from&&(n.from=n.from),n}function LN(e){const t=async function(t){const r=await BN(t,["data"]);r.to=await e.getAddress(),r.from&&(r.from=await $I(r.from,MN(e.runner)));const n=e.interface,i=iS(r.value||IN,"overrides.value")===IN,s="0x"===(r.data||"0x");!n.fallback||n.fallback.payable||!n.receive||s||i||DA(!1,"cannot send data to receive or send value to non-payable fallback","overrides",t),DA(n.fallback||s,"cannot send data to receive-only contract","overrides.data",r.data);return DA(n.receive||n.fallback&&n.fallback.payable||i,"cannot send value to non-payable fallback","overrides.value",r.value),DA(n.fallback||s,"cannot send data to receive-only contract","overrides.data",r.data),r},r=async function(r){const n=e.runner;OA(NN(n),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const i=await n.sendTransaction(await t(r)),s=DN(e.runner);return new kN(e.interface,s,i)},n=async e=>await r(e);return TA(n,{_contract:e,estimateGas:async function(r){const n=ON(e.runner,"estimateGas");return OA(TN(n),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await n.estimateGas(await t(r))},populateTransaction:t,send:r,staticCall:async function(r){const n=ON(e.runner,"call");OA(PN(n),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const i=await t(r);try{return await n.call(i)}catch(t){if(MA(t)&&t.data)throw e.interface.makeError(t.data,i);throw t}}}),n}function FN(e,t){const r=function(...r){const n=e.interface.getFunction(t,r);return OA(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:r}}),n},n=async function(...t){const n=r(...t);let i={};if(n.inputs.length+1===t.length&&(i=await BN(t.pop()),i.from&&(i.from=await $I(i.from,MN(e.runner)))),n.inputs.length!==t.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const s=await async function(e,t,r){const n=ON(e,"resolveName"),i=_N(n)?n:null;return await Promise.all(t.map(((e,t)=>e.walkAsync(r[t],((e,t)=>(t=YI.dereference(t,e),"address"===e?$I(t,i):t))))))}(e.runner,n.inputs,t);return Object.assign({},i,await PA({to:e.getAddress(),data:e.interface.encodeFunctionData(n,s)}))},i=async function(...e){const t=await o(...e);return 1===t.length?t[0]:t},s=async function(...t){const r=e.runner;OA(NN(r),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const i=await r.sendTransaction(await n(...t)),s=DN(e.runner);return new kN(e.interface,s,i)},o=async function(...t){const i=ON(e.runner,"call");OA(PN(i),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const s=await n(...t);let o="0x";try{o=await i.call(s)}catch(t){if(MA(t)&&t.data)throw e.interface.makeError(t.data,s);throw t}const a=r(...t);return e.interface.decodeFunctionResult(a,o)},a=async(...e)=>r(...e).constant?await i(...e):await s(...e);return TA(a,{name:e.interface.getFunctionName(t),_contract:e,_key:t,getFragment:r,estimateGas:async function(...t){const r=ON(e.runner,"estimateGas");return OA(TN(r),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await r.estimateGas(await n(...t))},populateTransaction:n,send:s,staticCall:i,staticCallResult:o}),Object.defineProperty(a,"fragment",{configurable:!1,enumerable:!0,get:()=>{const r=e.interface.getFunction(t);return OA(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),r}}),a}const UN=Symbol.for("_ethersInternal_contract"),jN=new WeakMap;function qN(e){return jN.get(e[UN])}async function zN(e,t){let r,n=null;if(Array.isArray(t)){const n=function(t){if(KA(t,32))return t;const r=e.interface.getEvent(t);return DA(r,"unknown fragment","name",t),r.topicHash};r=t.map((e=>null==e?null:Array.isArray(e)?e.map(n):n(e)))}else"*"===t?r=[null]:"string"==typeof t?KA(t,32)?r=[t]:(n=e.interface.getEvent(t),DA(n,"unknown fragment","event",t),r=[n.topicHash]):(i=t)&&"object"==typeof i&&"getTopicFilter"in i&&"function"==typeof i.getTopicFilter&&i.fragment?r=await t.getTopicFilter():"fragment"in t?(n=t.fragment,r=[n.topicHash]):DA(!1,"unknown event name","event",t);var i;r=r.map((e=>{if(null==e)return null;if(Array.isArray(e)){const t=Array.from(new Set(e.map((e=>e.toLowerCase()))).values());return 1===t.length?t[0]:(t.sort(),t)}return e.toLowerCase()}));return{fragment:n,tag:r.map((e=>null==e?"null":Array.isArray(e)?e.join("|"):e)).join("&"),topics:r}}async function KN(e,t){const{subs:r}=qN(e);return r.get((await zN(e,t)).tag)||null}async function GN(e,t,r){const n=DN(e.runner);OA(n,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:t});const{fragment:i,tag:s,topics:o}=await zN(e,r),{addr:a,subs:c}=qN(e);let u=c.get(s);if(!u){const t={address:a||e,topics:o},l=t=>{let n=i;if(null==n)try{n=e.interface.getEvent(t.topics[0])}catch(e){}if(n){const s=n,o=i?e.interface.decodeEventLog(i,t.data,t.topics):[];HN(e,r,o,(n=>new CN(e,n,r,s,t)))}else HN(e,r,[],(n=>new RN(e,n,r,t)))};let h=[];u={tag:s,listeners:[],start:()=>{h.length||h.push(n.on(t,l))},stop:async()=>{if(0==h.length)return;let e=h;h=[],await Promise.all(e),n.off(t,l)}},c.set(s,u)}return u}let VN=Promise.resolve();async function HN(e,t,r,n){try{await VN}catch(e){}const i=async function(e,t,r,n){await VN;const i=await KN(e,t);if(!i)return!1;const s=i.listeners.length;return i.listeners=i.listeners.filter((({listener:t,once:i})=>{const s=Array.from(r);n&&s.push(n(i?null:t));try{t.call(e,...s)}catch(e){}return!i})),0===i.listeners.length&&(i.stop(),qN(e).subs.delete(i.tag)),s>0}(e,t,r,n);return VN=i,await i}const $N=["then"];class WN{target;interface;runner;filters;[UN];fallback;constructor(e,t,r,n){DA("string"==typeof e||VI(e),"invalid value for Contract target","target",e),null==r&&(r=null);const i=uN.from(t);let s;TA(this,{target:e,runner:r,interface:i}),Object.defineProperty(this,UN,{value:{}});let o=null,a=null;if(n){const e=DN(r);a=new kN(this.interface,e,n)}let c=new Map;if("string"==typeof e)if(KA(e))o=e,s=Promise.resolve(e);else{const t=ON(r,"resolveName");if(!_N(t))throw xA("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});s=t.resolveName(e).then((t=>{if(null==t)throw xA("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:e});return qN(this).addr=t,t}))}else s=e.getAddress().then((e=>{if(null==e)throw new Error("TODO");return qN(this).addr=e,e}));var u,l;u=this,l={addrPromise:s,addr:o,deployTx:a,subs:c},jN.set(u[UN],l);const h=new Proxy({},{get:(e,t,r)=>{if("symbol"==typeof t||$N.indexOf(t)>=0)return Reflect.get(e,t,r);try{return this.getEvent(t)}catch(e){if(!NA(e,"INVALID_ARGUMENT")||"key"!==e.argument)throw e}},has:(e,t)=>$N.indexOf(t)>=0?Reflect.has(e,t):Reflect.has(e,t)||this.interface.hasEvent(String(t))});return TA(this,{filters:h}),TA(this,{fallback:i.receive||i.fallback?LN(this):null}),new Proxy(this,{get:(e,t,r)=>{if("symbol"==typeof t||t in e||$N.indexOf(t)>=0)return Reflect.get(e,t,r);try{return e.getFunction(t)}catch(e){if(!NA(e,"INVALID_ARGUMENT")||"key"!==e.argument)throw e}},has:(e,t)=>"symbol"==typeof t||t in e||$N.indexOf(t)>=0?Reflect.has(e,t):e.interface.hasFunction(t)})}connect(e){return new WN(this.target,this.interface,e)}attach(e){return new WN(e,this.interface,this.runner)}async getAddress(){return await qN(this).addrPromise}async getDeployedCode(){const e=DN(this.runner);OA(e,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const t=await e.getCode(await this.getAddress());return"0x"===t?null:t}async waitForDeployment(){const e=this.deploymentTransaction();if(e)return await e.wait(),this;if(null!=await this.getDeployedCode())return this;const t=DN(this.runner);return OA(null!=t,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise(((e,r)=>{const n=async()=>{try{if(null!=await this.getDeployedCode())return e(this);t.once("block",n)}catch(e){r(e)}};n()}))}deploymentTransaction(){return qN(this).deployTx}getFunction(e){"string"!=typeof e&&(e=e.format());return FN(this,e)}getEvent(e){return"string"!=typeof e&&(e=e.format()),function(e,t){const r=function(...r){const n=e.interface.getEvent(t,r);return OA(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:r}}),n},n=function(...t){return new xN(e,r(...t),t)};return TA(n,{name:e.interface.getEventName(t),_contract:e,_key:t,getFragment:r}),Object.defineProperty(n,"fragment",{configurable:!1,enumerable:!0,get:()=>{const r=e.interface.getEvent(t);return OA(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),r}}),n}(this,e)}async queryTransaction(e){throw new Error("@TODO")}async queryFilter(e,t,r){null==t&&(t=0),null==r&&(r="latest");const{addr:n,addrPromise:i}=qN(this),s=n||await i,{fragment:o,topics:a}=await zN(this,e),c={address:s,topics:a,fromBlock:t,toBlock:r},u=DN(this.runner);return OA(u,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await u.getLogs(c)).map((e=>{let t=o;if(null==t)try{t=this.interface.getEvent(e.topics[0])}catch(e){}if(t)try{return new EN(e,this.interface,t)}catch(t){return new AN(e,t)}return new mN(e,u)}))}async on(e,t){const r=await GN(this,"on",e);return r.listeners.push({listener:t,once:!1}),r.start(),this}async once(e,t){const r=await GN(this,"once",e);return r.listeners.push({listener:t,once:!0}),r.start(),this}async emit(e,...t){return await HN(this,e,t,null)}async listenerCount(e){if(e){const t=await KN(this,e);return t?t.listeners.length:0}const{subs:t}=qN(this);let r=0;for(const{listeners:e}of t.values())r+=e.length;return r}async listeners(e){if(e){const t=await KN(this,e);return t?t.listeners.map((({listener:e})=>e)):[]}const{subs:t}=qN(this);let r=[];for(const{listeners:e}of t.values())r=r.concat(e.map((({listener:e})=>e)));return r}async off(e,t){const r=await KN(this,e);if(!r)return this;if(t){const e=r.listeners.map((({listener:e})=>e)).indexOf(t);e>=0&&r.listeners.splice(e,1)}return null!=t&&0!==r.listeners.length||(r.stop(),qN(this).subs.delete(r.tag)),this}async removeAllListeners(e){if(e){const t=await KN(this,e);if(!t)return this;t.stop(),qN(this).subs.delete(t.tag)}else{const{subs:e}=qN(this);for(const{tag:t,stop:r}of e.values())r(),e.delete(t)}return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return await this.off(e,t)}static buildClass(e){return class extends WN{constructor(t,r=null){super(t,e,r)}}}static from(e,t,r){null==r&&(r=null);return new this(e,t,r)}}class JN extends(function(){return WN}()){}function QN(e){return e.match(/^ipfs:\/\/ipfs\//i)?e=e.substring(12):e.match(/^ipfs:\/\//i)?e=e.substring(7):DA(!1,"unsupported IPFS format","link",e),`https://gateway.ipfs.io/ipfs/${e}`}class ZN{name;constructor(e){TA(this,{name:e})}connect(e){return this}supportsCoinType(e){return!1}async encodeAddress(e,t){throw new Error("unsupported coin")}async decodeAddress(e,t){throw new Error("unsupported coin")}}const YN=new RegExp("^(ipfs)://(.*)$","i"),XN=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),YN,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];class eM{provider;address;name;#Te;#_e;constructor(e,t,r){TA(this,{provider:e,address:t,name:r}),this.#Te=null,this.#_e=new JN(t,["function supportsInterface(bytes4) view returns (bool)","function resolve(bytes, bytes) view returns (bytes)","function addr(bytes32) view returns (address)","function addr(bytes32, uint) view returns (bytes)","function text(bytes32, string) view returns (string)","function contenthash(bytes32) view returns (bytes)"],e)}async supportsWildcard(){return null==this.#Te&&(this.#Te=(async()=>{try{return await this.#_e.supportsInterface("0x9061b923")}catch(e){if(NA(e,"CALL_EXCEPTION"))return!1;throw this.#Te=null,e}})()),await this.#Te}async#Ne(e,t){t=(t||[]).slice();const r=this.#_e.interface;t.unshift(ST(this.name));let n=null;await this.supportsWildcard()&&(n=r.getFunction(e),OA(n,"missing fragment","UNKNOWN_ERROR",{info:{funcName:e}}),t=[kT(this.name,255),r.encodeFunctionData(n,t)],e="resolve(bytes,bytes)"),t.push({enableCcipRead:!0});try{const i=await this.#_e[e](...t);return n?r.decodeFunctionResult(n,i)[0]:i}catch(e){if(!NA(e,"CALL_EXCEPTION"))throw e}return null}async getAddress(e){if(null==e&&(e=60),60===e)try{const e=await this.#Ne("addr(bytes32)");return null==e||e===CI?null:e}catch(e){if(NA(e,"CALL_EXCEPTION"))return null;throw e}if(e>=0&&e<2147483648){let t=e+2147483648;const r=await this.#Ne("addr(bytes32,uint)",[t]);if(KA(r,20))return GI(r)}let t=null;for(const r of this.provider.plugins)if(r instanceof ZN&&r.supportsCoinType(e)){t=r;break}if(null==t)return null;const r=await this.#Ne("addr(bytes32,uint)",[e]);if(null==r||"0x"===r)return null;const n=await t.decodeAddress(e,r);if(null!=n)return n;OA(!1,"invalid coin data","UNSUPPORTED_OPERATION",{operation:`getAddress(${e})`,info:{coinType:e,data:r}})}async getText(e){const t=await this.#Ne("text(bytes32,string)",[e]);return null==t||"0x"===t?null:t}async getContentHash(){const e=await this.#Ne("contenthash(bytes32)");if(null==e||"0x"===e)return null;const t=e.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(t){const e="e3010170"===t[1]?"ipfs":"ipns",r=parseInt(t[4],16);if(t[5].length===2*r)return`${e}://${yS("0x"+t[2])}`}const r=e.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(r&&64===r[1].length)return`bzz://${r[1]}`;OA(!1,"invalid or unsupported content hash data","UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:e}})}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const e=[{type:"name",value:this.name}];try{const t=await this.getText("avatar");if(null==t)return e.push({type:"!avatar",value:""}),{url:null,linkage:e};e.push({type:"avatar",value:t});for(let r=0;r<XN.length;r++){const n=t.match(XN[r]);if(null==n)continue;const i=n[1].toLowerCase();switch(i){case"https":case"data":return e.push({type:"url",value:t}),{linkage:e,url:t};case"ipfs":{const r=QN(t);return e.push({type:"ipfs",value:t}),e.push({type:"url",value:r}),{linkage:e,url:r}}case"erc721":case"erc1155":{const r="erc721"===i?"tokenURI(uint256)":"uri(uint256)";e.push({type:i,value:t});const s=await this.getAddress();if(null==s)return e.push({type:"!owner",value:""}),{url:null,linkage:e};const o=(n[2]||"").split("/");if(2!==o.length)return e.push({type:`!${i}caip`,value:n[2]||""}),{url:null,linkage:e};const a=o[1],c=new JN(o[0],["function tokenURI(uint) view returns (string)","function ownerOf(uint) view returns (address)","function uri(uint) view returns (string)","function balanceOf(address, uint256) view returns (uint)"],this.provider);if("erc721"===i){const t=await c.ownerOf(a);if(s!==t)return e.push({type:"!owner",value:t}),{url:null,linkage:e};e.push({type:"owner",value:t})}else if("erc1155"===i){const t=await c.balanceOf(s,a);if(!t)return e.push({type:"!balance",value:"0"}),{url:null,linkage:e};e.push({type:"balance",value:t.toString()})}let u=await c[r](a);if(null==u||"0x"===u)return e.push({type:"!metadata-url",value:""}),{url:null,linkage:e};e.push({type:"metadata-url-base",value:u}),"erc1155"===i&&(u=u.replace("{id}",uS(a,32).substring(2)),e.push({type:"metadata-url-expanded",value:u})),u.match(/^ipfs:/i)&&(u=QN(u)),e.push({type:"metadata-url",value:u});let l={};const h=await new OS(u).send();h.assertOk();try{l=h.bodyJson}catch(t){try{e.push({type:"!metadata",value:h.bodyText})}catch(t){const r=h.body;return r&&e.push({type:"!metadata",value:HA(r)}),{url:null,linkage:e}}return{url:null,linkage:e}}if(!l)return e.push({type:"!metadata",value:""}),{url:null,linkage:e};e.push({type:"metadata",value:JSON.stringify(l)});let d=l.image;if("string"!=typeof d)return e.push({type:"!imageUrl",value:""}),{url:null,linkage:e};if(d.match(/^(https:\/\/|data:)/i));else{if(null==d.match(YN))return e.push({type:"!imageUrl-ipfs",value:d}),{url:null,linkage:e};e.push({type:"imageUrl-ipfs",value:d}),d=QN(d)}return e.push({type:"url",value:d}),{linkage:e,url:d}}}}}catch(e){}return{linkage:e,url:null}}static async getEnsAddress(e){const t=await e.getNetwork(),r=t.getPlugin("org.ethers.plugins.network.Ens");return OA(r,"network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getEnsAddress",info:{network:t}}),r.address}static async#Me(e,t){const r=await eM.getEnsAddress(e);try{const n=new JN(r,["function resolver(bytes32) view returns (address)"],e),i=await n.resolver(ST(t),{enableCcipRead:!0});return i===CI?null:i}catch(e){throw e}return null}static async fromName(e,t){let r=t;for(;;){if(""===r||"."===r)return null;if("eth"!==t&&"eth"===r)return null;const n=await eM.#Me(e,r);if(null!=n){const i=new eM(e,n,t);return r===t||await i.supportsWildcard()?i:null}r=r.split(".").slice(1).join(".")}}}const tM=BigInt(0);function rM(e,t){return function(r){return null==r?t:e(r)}}function nM(e,t){return r=>{if(t&&null==r)return null;if(!Array.isArray(r))throw new Error("not an array");return r.map((t=>e(t)))}}function iM(e,t){return r=>{const n={};for(const i in e){let s=i;if(t&&i in t&&!(s in r))for(const e of t[i])if(e in r){s=e;break}try{const t=e[i](r[s]);void 0!==t&&(n[i]=t)}catch(e){OA(!1,`invalid value for value.${i} (${e instanceof Error?e.message:"not-an-error"})`,"BAD_DATA",{value:r})}}return n}}function sM(e){return DA(KA(e,!0),"invalid data","value",e),e}function oM(e){return DA(KA(e,32),"invalid hash","value",e),e}const aM=iM({address:GI,blockHash:oM,blockNumber:cS,data:sM,index:cS,removed:rM((function(e){switch(e){case!0:case"true":return!0;case!1:case"false":return!1}DA(!1,`invalid boolean; ${JSON.stringify(e)}`,"value",e)}),!1),topics:nM(oM),transactionHash:oM,transactionIndex:cS},{index:["logIndex"]});const cM=iM({hash:rM(oM),parentHash:oM,parentBeaconBlockRoot:rM(oM,null),number:cS,timestamp:cS,nonce:rM(sM),difficulty:iS,gasLimit:iS,gasUsed:iS,stateRoot:rM(oM,null),receiptsRoot:rM(oM,null),blobGasUsed:rM(iS,null),excessBlobGas:rM(iS,null),miner:rM(GI),prevRandao:rM(oM,null),extraData:sM,baseFeePerGas:rM(iS)},{prevRandao:["mixHash"]});const uM=iM({transactionIndex:cS,blockNumber:cS,transactionHash:oM,address:GI,topics:nM(oM),data:sM,index:cS,blockHash:oM},{index:["logIndex"]});const lM=iM({to:rM(GI,null),from:rM(GI,null),contractAddress:rM(GI,null),index:cS,root:rM(HA),gasUsed:iS,blobGasUsed:rM(iS,null),logsBloom:rM(sM),blockHash:oM,hash:oM,logs:nM((function(e){return uM(e)})),blockNumber:cS,cumulativeGasUsed:iS,effectiveGasPrice:rM(iS),blobGasPrice:rM(iS,null),status:rM(cS),type:rM(cS,0)},{effectiveGasPrice:["gasPrice"],hash:["transactionHash"],index:["transactionIndex"]});function hM(e){e.to&&iS(e.to)===tM&&(e.to="0x0000000000000000000000000000000000000000");const t=iM({hash:oM,index:rM(cS,void 0),type:e=>"0x"===e||null==e?0:cS(e),accessList:rM(CT,null),blobVersionedHashes:rM(nM(oM,!0),null),blockHash:rM(oM,null),blockNumber:rM(cS,null),transactionIndex:rM(cS,null),from:GI,gasPrice:rM(iS),maxPriorityFeePerGas:rM(iS),maxFeePerGas:rM(iS),maxFeePerBlobGas:rM(iS,null),gasLimit:iS,to:rM(GI,null),value:iS,nonce:cS,data:sM,creates:rM(GI,null),chainId:rM(iS,null)},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(e);if(null==t.to&&null==t.creates&&(t.creates=function(e){const t=GI(e.from);let r=iS(e.nonce,"tx.nonce").toString(16);return r="0"===r?"0x":r.length%2?"0x0"+r:"0x"+r,GI(JA(xR(tk([t,r])),12))}(t)),1!==e.type&&2!==e.type||null!=e.accessList||(t.accessList=[]),e.signature?t.signature=LI.from(e.signature):t.signature=LI.from(e),null==t.chainId){const e=t.signature.legacyChainId;null!=e&&(t.chainId=e)}return t.blockHash&&iS(t.blockHash)===tM&&(t.blockHash=null),t}class dM{name;constructor(e){TA(this,{name:e})}clone(){return new dM(this.name)}}class fM extends dM{effectiveBlock;txBase;txCreate;txDataZero;txDataNonzero;txAccessListStorageKey;txAccessListAddress;constructor(e,t){null==e&&(e=0),super(`org.ethers.network.plugins.GasCost#${e||0}`);const r={effectiveBlock:e};function n(e,n){let i=(t||{})[e];null==i&&(i=n),DA("number"==typeof i,`invalud value for ${e}`,"costs",t),r[e]=i}n("txBase",21e3),n("txCreate",32e3),n("txDataZero",4),n("txDataNonzero",16),n("txAccessListStorageKey",1900),n("txAccessListAddress",2400),TA(this,r)}clone(){return new fM(this.effectiveBlock,this)}}class pM extends dM{address;targetNetwork;constructor(e,t){super("org.ethers.plugins.network.Ens"),TA(this,{address:e||"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",targetNetwork:null==t?1:t})}clone(){return new pM(this.address,this.targetNetwork)}}class gM extends dM{#c;#xe;get url(){return this.#c}get processFunc(){return this.#xe}constructor(e,t){super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"),this.#c=e,this.#xe=t}clone(){return this}}const mM=new Map;class yM{#Oe;#re;#De;constructor(e,t){this.#Oe=e,this.#re=iS(t),this.#De=new Map}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return this.#Oe}set name(e){this.#Oe=e}get chainId(){return this.#re}set chainId(e){this.#re=iS(e,"chainId")}matches(e){if(null==e)return!1;if("string"==typeof e){try{return this.chainId===iS(e)}catch(e){}return this.name===e}if("number"==typeof e||"bigint"==typeof e){try{return this.chainId===iS(e)}catch(e){}return!1}if("object"==typeof e){if(null!=e.chainId){try{return this.chainId===iS(e.chainId)}catch(e){}return!1}return null!=e.name&&this.name===e.name}return!1}get plugins(){return Array.from(this.#De.values())}attachPlugin(e){if(this.#De.get(e.name))throw new Error(`cannot replace existing plugin: ${e.name} `);return this.#De.set(e.name,e.clone()),this}getPlugin(e){return this.#De.get(e)||null}getPlugins(e){return this.plugins.filter((t=>t.name.split("#")[0]===e))}clone(){const e=new yM(this.name,this.chainId);return this.plugins.forEach((t=>{e.attachPlugin(t.clone())})),e}computeIntrinsicGas(e){const t=this.getPlugin("org.ethers.plugins.network.GasCost")||new fM;let r=t.txBase;if(null==e.to&&(r+=t.txCreate),e.data)for(let n=2;n<e.data.length;n+=2)"00"===e.data.substring(n,n+2)?r+=t.txDataZero:r+=t.txDataNonzero;if(e.accessList){const n=CT(e.accessList);for(const e in n)r+=t.txAccessListAddress+t.txAccessListStorageKey*n[e].storageKeys.length}return r}static from(e){if(function(){if(vM)return;function e(e,t,r){const n=function(){const n=new yM(e,t);return null!=r.ensNetwork&&n.attachPlugin(new pM(null,r.ensNetwork)),n.attachPlugin(new fM),(r.plugins||[]).forEach((e=>{n.attachPlugin(e)})),n};yM.register(e,n),yM.register(t,n),r.altNames&&r.altNames.forEach((e=>{yM.register(e,n)}))}vM=!0,e("mainnet",1,{ensNetwork:1,altNames:["homestead"]}),e("ropsten",3,{ensNetwork:3}),e("rinkeby",4,{ensNetwork:4}),e("goerli",5,{ensNetwork:5}),e("kovan",42,{ensNetwork:42}),e("sepolia",11155111,{ensNetwork:11155111}),e("holesky",17e3,{ensNetwork:17e3}),e("classic",61,{}),e("classicKotti",6,{}),e("arbitrum",42161,{ensNetwork:1}),e("arbitrum-goerli",421613,{}),e("arbitrum-sepolia",421614,{}),e("base",8453,{ensNetwork:1}),e("base-goerli",84531,{}),e("base-sepolia",84532,{}),e("bnb",56,{ensNetwork:1}),e("bnbt",97,{}),e("linea",59144,{ensNetwork:1}),e("linea-goerli",59140,{}),e("linea-sepolia",59141,{}),e("matic",137,{ensNetwork:1,plugins:[wM("https://gasstation.polygon.technology/v2")]}),e("matic-amoy",80002,{}),e("matic-mumbai",80001,{altNames:["maticMumbai","maticmum"],plugins:[wM("https://gasstation-testnet.polygon.technology/v2")]}),e("optimism",10,{ensNetwork:1,plugins:[]}),e("optimism-goerli",420,{}),e("optimism-sepolia",11155420,{}),e("xdai",100,{ensNetwork:1})}(),null==e)return yM.from("mainnet");if("number"==typeof e&&(e=BigInt(e)),"string"==typeof e||"bigint"==typeof e){const t=mM.get(e);if(t)return t();if("bigint"==typeof e)return new yM("unknown",e);DA(!1,"unknown network","network",e)}if("function"==typeof e.clone){return e.clone()}if("object"==typeof e){DA("string"==typeof e.name&&"number"==typeof e.chainId,"invalid network object name or chainId","network",e);const t=new yM(e.name,e.chainId);return(e.ensAddress||null!=e.ensNetwork)&&t.attachPlugin(new pM(e.ensAddress,e.ensNetwork)),t}DA(!1,"invalid network","network",e)}static register(e,t){"number"==typeof e&&(e=BigInt(e));const r=mM.get(e);r&&DA(!1,`conflicting network for ${JSON.stringify(r.name)}`,"nameOrChainId",e),mM.set(e,t)}}function bM(e,t){const r=String(e);if(!r.match(/^[0-9.]+$/))throw new Error(`invalid gwei value: ${e}`);const n=r.split(".");if(1===n.length&&n.push(""),2!==n.length)throw new Error(`invalid gwei value: ${e}`);for(;n[1].length<t;)n[1]+="0";if(n[1].length>9){let e=BigInt(n[1].substring(0,9));n[1].substring(9).match(/^0+$/)||e++,n[1]=e.toString()}return BigInt(n[0]+n[1])}function wM(e){return new gM(e,(async(e,t,r)=>{let n;r.setHeader("User-Agent","ethers");try{const[t,i]=await Promise.all([r.send(),e()]);n=t;const s=n.bodyJson.standard;return{gasPrice:i.gasPrice,maxFeePerGas:bM(s.maxFee,9),maxPriorityFeePerGas:bM(s.maxPriorityFee,9)}}catch(e){OA(!1,`error encountered with polygon gas station (${JSON.stringify(r.url)})`,"SERVER_ERROR",{request:r,response:n,error:e})}}))}let vM=!1;function EM(e){return JSON.parse(JSON.stringify(e))}class AM{#Be;#Le;#Fe;#Ue;constructor(e){this.#Be=e,this.#Le=null,this.#Fe=4e3,this.#Ue=-2}get pollingInterval(){return this.#Fe}set pollingInterval(e){this.#Fe=e}async#je(){try{const e=await this.#Be.getBlockNumber();if(-2===this.#Ue)return void(this.#Ue=e);if(e!==this.#Ue){for(let t=this.#Ue+1;t<=e;t++){if(null==this.#Le)return;await this.#Be.emit("block",t)}this.#Ue=e}}catch(e){}null!=this.#Le&&(this.#Le=this.#Be._setTimeout(this.#je.bind(this),this.#Fe))}start(){this.#Le||(this.#Le=this.#Be._setTimeout(this.#je.bind(this),this.#Fe),this.#je())}stop(){this.#Le&&(this.#Be._clearTimeout(this.#Le),this.#Le=null)}pause(e){this.stop(),e&&(this.#Ue=-2)}resume(){this.start()}}class SM{#Be;#je;#qe;constructor(e){this.#Be=e,this.#qe=!1,this.#je=e=>{this._poll(e,this.#Be)}}async _poll(e,t){throw new Error("sub-classes must override this")}start(){this.#qe||(this.#qe=!0,this.#je(-2),this.#Be.on("block",this.#je))}stop(){this.#qe&&(this.#qe=!1,this.#Be.off("block",this.#je))}pause(e){this.stop()}resume(){this.start()}}class kM extends SM{#ze;#Ke;constructor(e,t){super(e),this.#ze=t,this.#Ke=-2}pause(e){e&&(this.#Ke=-2),super.pause(e)}async _poll(e,t){const r=await t.getBlock(this.#ze);null!=r&&(-2===this.#Ke?this.#Ke=r.number:r.number>this.#Ke&&(t.emit(this.#ze,r.number),this.#Ke=r.number))}}class RM extends SM{#Pe;constructor(e,t){super(e),this.#Pe=EM(t)}async _poll(e,t){throw new Error("@TODO")}}class CM extends SM{#Ge;constructor(e,t){super(e),this.#Ge=t}async _poll(e,t){const r=await t.getTransactionReceipt(this.#Ge);r&&t.emit(this.#Ge,r)}}class IM{#Be;#Pe;#Le;#qe;#Ue;constructor(e,t){this.#Be=e,this.#Pe=EM(t),this.#Le=this.#je.bind(this),this.#qe=!1,this.#Ue=-2}async#je(e){if(-2===this.#Ue)return;const t=EM(this.#Pe);t.fromBlock=this.#Ue+1,t.toBlock=e;const r=await this.#Be.getLogs(t);if(0!==r.length)for(const e of r)this.#Be.emit(this.#Pe,e),this.#Ue=e.blockNumber;else this.#Ue<e-60&&(this.#Ue=e-60)}start(){this.#qe||(this.#qe=!0,-2===this.#Ue&&this.#Be.getBlockNumber().then((e=>{this.#Ue=e})),this.#Be.on("block",this.#Le))}stop(){this.#qe&&(this.#qe=!1,this.#Be.off("block",this.#Le))}pause(e){this.stop(),e&&(this.#Ue=-2)}resume(){this.start()}}const PM=BigInt(2);function TM(e){return e&&"function"==typeof e.then}function _M(e,t){return e+":"+JSON.stringify(t,((e,t)=>{if(null==t)return"null";if("bigint"==typeof t)return`bigint:${t.toString()}`;if("string"==typeof t)return t.toLowerCase();if("object"==typeof t&&!Array.isArray(t)){const e=Object.keys(t);return e.sort(),e.reduce(((e,r)=>(e[r]=t[r],e)),{})}return t}))}class NM{name;constructor(e){TA(this,{name:e})}start(){}stop(){}pause(e){}resume(){}}function MM(e){return(e=Array.from(new Set(e).values())).sort(),e}async function xM(e,t){if(null==e)throw new Error("invalid event");if(Array.isArray(e)&&(e={topics:e}),"string"==typeof e)switch(e){case"block":case"debug":case"error":case"finalized":case"network":case"pending":case"safe":return{type:e,tag:e}}if(KA(e,32)){const t=e.toLowerCase();return{type:"transaction",tag:_M("tx",{hash:t}),hash:t}}if(e.orphan){const t=e;return{type:"orphan",tag:_M("orphan",t),filter:(r=t,JSON.parse(JSON.stringify(r)))}}var r;if(e.address||e.topics){const r=e,n={topics:(r.topics||[]).map((e=>null==e?null:Array.isArray(e)?MM(e.map((e=>e.toLowerCase()))):e.toLowerCase()))};if(r.address){const e=[],i=[],s=r=>{KA(r)?e.push(r):i.push((async()=>{e.push(await $I(r,t))})())};Array.isArray(r.address)?r.address.forEach(s):s(r.address),i.length&&await Promise.all(i),n.address=MM(e.map((e=>e.toLowerCase())))}return{filter:n,tag:_M("event",n),type:"event"}}DA(!1,"unknown ProviderEvent","event",e)}function OM(){return(new Date).getTime()}const DM={cacheTimeout:250,pollingInterval:4e3};class BM{#Ve;#De;#He;#$e;#We;#Je;#Qe;#Ze;#Ye;#Xe;#et;#$;constructor(e,t){if(this.#$=Object.assign({},DM,t||{}),"any"===e)this.#Je=!0,this.#We=null;else if(e){const t=yM.from(e);this.#Je=!1,this.#We=Promise.resolve(t),setTimeout((()=>{this.emit("network",t,null)}),0)}else this.#Je=!1,this.#We=null;this.#Ze=-1,this.#Qe=new Map,this.#Ve=new Map,this.#De=new Map,this.#He=null,this.#$e=!1,this.#Ye=1,this.#Xe=new Map,this.#et=!1}get pollingInterval(){return this.#$.pollingInterval}get provider(){return this}get plugins(){return Array.from(this.#De.values())}attachPlugin(e){if(this.#De.get(e.name))throw new Error(`cannot replace existing plugin: ${e.name} `);return this.#De.set(e.name,e.connect(this)),this}getPlugin(e){return this.#De.get(e)||null}get disableCcipRead(){return this.#et}set disableCcipRead(e){this.#et=!!e}async#tt(e){const t=this.#$.cacheTimeout;if(t<0)return await this._perform(e);const r=_M(e.method,e);let n=this.#Qe.get(r);return n||(n=this._perform(e),this.#Qe.set(r,n),setTimeout((()=>{this.#Qe.get(r)===n&&this.#Qe.delete(r)}),t)),await n}async ccipReadFetch(e,t,r){if(this.disableCcipRead||0===r.length||null==e.to)return null;const n=e.to.toLowerCase(),i=t.toLowerCase(),s=[];for(let t=0;t<r.length;t++){const o=r[t],a=o.replace("{sender}",n).replace("{data}",i),c=new OS(a);-1===o.indexOf("{data}")&&(c.body={data:i,sender:n}),this.emit("debug",{action:"sendCcipReadFetchRequest",request:c,index:t,urls:r});let u,l="unknown error";try{u=await c.send()}catch(e){s.push(e.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:c,result:{error:e}});continue}try{const e=u.bodyJson;if(e.data)return this.emit("debug",{action:"receiveCcipReadFetchResult",request:c,result:e}),e.data;e.message&&(l=e.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:c,result:e})}catch(e){}OA(u.statusCode<400||u.statusCode>=500,`response not found during CCIP fetch: ${l}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:e,info:{url:o,errorMessage:l}}),s.push(l)}OA(!1,`error encountered during CCIP fetch: ${s.map((e=>JSON.stringify(e))).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:e,info:{urls:r,errorMessages:s}})}_wrapBlock(e,t){return new gN(function(e){const t=cM(e);return t.transactions=e.transactions.map((e=>"string"==typeof e?e:hM(e))),t}(e),this)}_wrapLog(e,t){return new mN(function(e){return aM(e)}(e),this)}_wrapTransactionReceipt(e,t){return new yN(function(e){return lM(e)}(e),this)}_wrapTransactionResponse(e,t){return new bN(hM(e),this)}_detectNetwork(){OA(!1,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(e){OA(!1,`unsupported method: ${e.method}`,"UNSUPPORTED_OPERATION",{operation:e.method,info:e})}async getBlockNumber(){const e=cS(await this.#tt({method:"getBlockNumber"}),"%response");return this.#Ze>=0&&(this.#Ze=e),e}_getAddress(e){return $I(e,this)}_getBlockTag(e){if(null==e)return"latest";switch(e){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return e}return KA(e)?KA(e,32)?e:hS(e):("bigint"==typeof e&&(e=cS(e,"blockTag")),"number"==typeof e?e>=0?hS(e):this.#Ze>=0?hS(this.#Ze+e):this.getBlockNumber().then((t=>hS(t+e))):void DA(!1,"invalid blockTag","blockTag",e))}_getFilter(e){const t=(e.topics||[]).map((e=>null==e?null:Array.isArray(e)?MM(e.map((e=>e.toLowerCase()))):e.toLowerCase())),r="blockHash"in e?e.blockHash:void 0,n=(e,n,i)=>{let s;switch(e.length){case 0:break;case 1:s=e[0];break;default:e.sort(),s=e}if(r&&(null!=n||null!=i))throw new Error("invalid filter");const o={};return s&&(o.address=s),t.length&&(o.topics=t),n&&(o.fromBlock=n),i&&(o.toBlock=i),r&&(o.blockHash=r),o};let i,s,o=[];if(e.address)if(Array.isArray(e.address))for(const t of e.address)o.push(this._getAddress(t));else o.push(this._getAddress(e.address));return"fromBlock"in e&&(i=this._getBlockTag(e.fromBlock)),"toBlock"in e&&(s=this._getBlockTag(e.toBlock)),o.filter((e=>"string"!=typeof e)).length||null!=i&&"string"!=typeof i||null!=s&&"string"!=typeof s?Promise.all([Promise.all(o),i,s]).then((e=>n(e[0],e[1],e[2]))):n(o,i,s)}_getTransactionRequest(e){const t=pN(e),r=[];if(["to","from"].forEach((e=>{if(null==t[e])return;const n=$I(t[e],this);TM(n)?r.push(async function(){t[e]=await n}()):t[e]=n})),null!=t.blockTag){const e=this._getBlockTag(t.blockTag);TM(e)?r.push(async function(){t.blockTag=await e}()):t.blockTag=e}return r.length?async function(){return await Promise.all(r),t}():t}async getNetwork(){if(null==this.#We){const e=(async()=>{try{const e=await this._detectNetwork();return this.emit("network",e,null),e}catch(t){throw this.#We===e&&(this.#We=null),t}})();return this.#We=e,(await e).clone()}const e=this.#We,[t,r]=await Promise.all([e,this._detectNetwork()]);return t.chainId!==r.chainId&&(this.#Je?(this.emit("network",r,t),this.#We===e&&(this.#We=Promise.resolve(r))):OA(!1,`network changed: ${t.chainId} => ${r.chainId} `,"NETWORK_ERROR",{event:"changed"})),t.clone()}async getFeeData(){const e=await this.getNetwork(),t=async()=>{const{_block:t,gasPrice:r,priorityFee:n}=await PA({_block:this.#rt("latest",!1),gasPrice:(async()=>{try{return iS(await this.#tt({method:"getGasPrice"}),"%response")}catch(e){}return null})(),priorityFee:(async()=>{try{return iS(await this.#tt({method:"getPriorityFee"}),"%response")}catch(e){}return null})()});let i=null,s=null;const o=this._wrapBlock(t,e);return o&&o.baseFeePerGas&&(s=null!=n?n:BigInt("1000000000"),i=o.baseFeePerGas*PM+s),new fN(r,i,s)},r=e.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");if(r){const e=new OS(r.url),n=await r.processFunc(t,this,e);return new fN(n.gasPrice,n.maxFeePerGas,n.maxPriorityFeePerGas)}return await t()}async estimateGas(e){let t=this._getTransactionRequest(e);return TM(t)&&(t=await t),iS(await this.#tt({method:"estimateGas",transaction:t}),"%response")}async#nt(e,t,r){OA(r<10,"CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},e,{blockTag:t,enableCcipRead:!0})});const n=pN(e);try{return HA(await this._perform({method:"call",transaction:n,blockTag:t}))}catch(e){if(!this.disableCcipRead&&MA(e)&&e.data&&r>=0&&"latest"===t&&null!=n.to&&"0x556f1830"===JA(e.data,0,4)){const i=e.data,s=await $I(n.to,this);let o;try{o=function(e){const t={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};OA(WA(e)>=160,"insufficient OffchainLookup data","OFFCHAIN_FAULT",{reason:"insufficient OffchainLookup data"});const r=JA(e,0,32);OA(JA(r,0,12)===JA(KM,0,12),"corrupt OffchainLookup sender","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup sender"}),t.sender=JA(r,12);try{const r=[],n=cS(JA(e,32,64)),i=cS(JA(e,n,n+32)),s=JA(e,n+32);for(let e=0;e<i;e++){const t=LM(s,32*e);if(null==t)throw new Error("abort");r.push(t)}t.urls=r}catch(e){OA(!1,"corrupt OffchainLookup urls","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup urls"})}try{const r=FM(e,64);if(null==r)throw new Error("abort");t.calldata=r}catch(e){OA(!1,"corrupt OffchainLookup calldata","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup calldata"})}OA(JA(e,100,128)===JA(KM,0,28),"corrupt OffchainLookup callbaackSelector","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup callbaackSelector"}),t.selector=JA(e,96,100);try{const r=FM(e,128);if(null==r)throw new Error("abort");t.extraData=r}catch(e){OA(!1,"corrupt OffchainLookup extraData","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup extraData"})}return t.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map((e=>t[e])),t}(JA(e.data,4))}catch(e){OA(!1,e.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:n,info:{data:i}})}OA(o.sender.toLowerCase()===s.toLowerCase(),"CCIP Read sender mismatch","CALL_EXCEPTION",{action:"call",data:i,reason:"OffchainLookup",transaction:n,invocation:null,revert:{signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",name:"OffchainLookup",args:o.errorArgs}});const a=await this.ccipReadFetch(n,o.calldata,o.urls);OA(null!=a,"CCIP Read failed to fetch data","OFFCHAIN_FAULT",{reason:"FETCH_FAILED",transaction:n,info:{data:e.data,errorArgs:o.errorArgs}});const c={to:s,data:$A([o.selector,zM([a,o.extraData])])};this.emit("debug",{action:"sendCcipReadCall",transaction:c});try{const e=await this.#nt(c,t,r+1);return this.emit("debug",{action:"receiveCcipReadCallResult",transaction:Object.assign({},c),result:e}),e}catch(e){throw this.emit("debug",{action:"receiveCcipReadCallError",transaction:Object.assign({},c),error:e}),e}}throw e}}async#it(e){const{value:t}=await PA({network:this.getNetwork(),value:e});return t}async call(e){const{tx:t,blockTag:r}=await PA({tx:this._getTransactionRequest(e),blockTag:this._getBlockTag(e.blockTag)});return await this.#it(this.#nt(t,r,e.enableCcipRead?0:-1))}async#st(e,t,r){let n=this._getAddress(t),i=this._getBlockTag(r);return"string"==typeof n&&"string"==typeof i||([n,i]=await Promise.all([n,i])),await this.#it(this.#tt(Object.assign(e,{address:n,blockTag:i})))}async getBalance(e,t){return iS(await this.#st({method:"getBalance"},e,t),"%response")}async getTransactionCount(e,t){return cS(await this.#st({method:"getTransactionCount"},e,t),"%response")}async getCode(e,t){return HA(await this.#st({method:"getCode"},e,t))}async getStorage(e,t,r){const n=iS(t,"position");return HA(await this.#st({method:"getStorage",position:n},e,r))}async broadcastTransaction(e){const{blockNumber:t,hash:r,network:n}=await PA({blockNumber:this.getBlockNumber(),hash:this._perform({method:"broadcastTransaction",signedTransaction:e}),network:this.getNetwork()}),i=GT.from(e);if(i.hash!==r)throw new Error("@TODO: the returned hash did not match");return this._wrapTransactionResponse(i,n).replaceableTransaction(t)}async#rt(e,t){if(KA(e,32))return await this.#tt({method:"getBlock",blockHash:e,includeTransactions:t});let r=this._getBlockTag(e);return"string"!=typeof r&&(r=await r),await this.#tt({method:"getBlock",blockTag:r,includeTransactions:t})}async getBlock(e,t){const{network:r,params:n}=await PA({network:this.getNetwork(),params:this.#rt(e,!!t)});return null==n?null:this._wrapBlock(n,r)}async getTransaction(e){const{network:t,params:r}=await PA({network:this.getNetwork(),params:this.#tt({method:"getTransaction",hash:e})});return null==r?null:this._wrapTransactionResponse(r,t)}async getTransactionReceipt(e){const{network:t,params:r}=await PA({network:this.getNetwork(),params:this.#tt({method:"getTransactionReceipt",hash:e})});if(null==r)return null;if(null==r.gasPrice&&null==r.effectiveGasPrice){const t=await this.#tt({method:"getTransaction",hash:e});if(null==t)throw new Error("report this; could not find tx or effectiveGasPrice");r.effectiveGasPrice=t.gasPrice}return this._wrapTransactionReceipt(r,t)}async getTransactionResult(e){const{result:t}=await PA({network:this.getNetwork(),result:this.#tt({method:"getTransactionResult",hash:e})});return null==t?null:HA(t)}async getLogs(e){let t=this._getFilter(e);TM(t)&&(t=await t);const{network:r,params:n}=await PA({network:this.getNetwork(),params:this.#tt({method:"getLogs",filter:t})});return n.map((e=>this._wrapLog(e,r)))}_getProvider(e){OA(!1,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(e){return await eM.fromName(this,e)}async getAvatar(e){const t=await this.getResolver(e);return t?await t.getAvatar():null}async resolveName(e){const t=await this.getResolver(e);return t?await t.getAddress():null}async lookupAddress(e){const t=ST((e=GI(e)).substring(2).toLowerCase()+".addr.reverse");try{const r=await eM.getEnsAddress(this),n=new JN(r,["function resolver(bytes32) view returns (address)"],this),i=await n.resolver(t);if(null==i||i===CI)return null;const s=new JN(i,["function name(bytes32) view returns (string)"],this),o=await s.name(t);return await this.resolveName(o)!==e?null:o}catch(e){if(NA(e,"BAD_DATA")&&"0x"===e.value)return null;if(NA(e,"CALL_EXCEPTION"))return null;throw e}return null}async waitForTransaction(e,t,r){const n=null!=t?t:1;return 0===n?this.getTransactionReceipt(e):new Promise((async(t,i)=>{let s=null;const o=async r=>{try{const i=await this.getTransactionReceipt(e);if(null!=i&&r-i.blockNumber+1>=n)return t(i),void(s&&(clearTimeout(s),s=null))}catch(e){console.log("EEE",e)}this.once("block",o)};null!=r&&(s=setTimeout((()=>{null!=s&&(s=null,this.off("block",o),i(xA("timeout","TIMEOUT",{reason:"timeout"})))}),r)),o(await this.getBlockNumber())}))}async waitForBlock(e){OA(!1,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(e){const t=this.#Xe.get(e);t&&(t.timer&&clearTimeout(t.timer),this.#Xe.delete(e))}_setTimeout(e,t){null==t&&(t=0);const r=this.#Ye++,n=()=>{this.#Xe.delete(r),e()};if(this.paused)this.#Xe.set(r,{timer:null,func:n,time:t});else{const e=setTimeout(n,t);this.#Xe.set(r,{timer:e,func:n,time:OM()})}return r}_forEachSubscriber(e){for(const t of this.#Ve.values())e(t.subscriber)}_getSubscriber(e){switch(e.type){case"debug":case"error":case"network":return new NM(e.type);case"block":{const e=new AM(this);return e.pollingInterval=this.pollingInterval,e}case"safe":case"finalized":return new kM(this,e.type);case"event":return new IM(this,e.filter);case"transaction":return new CM(this,e.hash);case"orphan":return new RM(this,e.filter)}throw new Error(`unsupported event: ${e.type}`)}_recoverSubscriber(e,t){for(const r of this.#Ve.values())if(r.subscriber===e){r.started&&r.subscriber.stop(),r.subscriber=t,r.started&&t.start(),null!=this.#He&&t.pause(this.#He);break}}async#ot(e,t){let r=await xM(e,this);return"event"===r.type&&t&&t.length>0&&!0===t[0].removed&&(r=await xM({orphan:"drop-log",log:t[0]},this)),this.#Ve.get(r.tag)||null}async#at(e){const t=await xM(e,this),r=t.tag;let n=this.#Ve.get(r);if(!n){n={subscriber:this._getSubscriber(t),tag:r,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},this.#Ve.set(r,n)}return n}async on(e,t){const r=await this.#at(e);return r.listeners.push({listener:t,once:!1}),r.started||(r.subscriber.start(),r.started=!0,null!=this.#He&&r.subscriber.pause(this.#He)),this}async once(e,t){const r=await this.#at(e);return r.listeners.push({listener:t,once:!0}),r.started||(r.subscriber.start(),r.started=!0,null!=this.#He&&r.subscriber.pause(this.#He)),this}async emit(e,...t){const r=await this.#ot(e,t);if(!r||0===r.listeners.length)return!1;const n=r.listeners.length;return r.listeners=r.listeners.filter((({listener:r,once:n})=>{const i=new bS(this,n?null:r,e);try{r.call(this,...t,i)}catch(e){}return!n})),0===r.listeners.length&&(r.started&&r.subscriber.stop(),this.#Ve.delete(r.tag)),n>0}async listenerCount(e){if(e){const t=await this.#ot(e);return t?t.listeners.length:0}let t=0;for(const{listeners:e}of this.#Ve.values())t+=e.length;return t}async listeners(e){if(e){const t=await this.#ot(e);return t?t.listeners.map((({listener:e})=>e)):[]}let t=[];for(const{listeners:e}of this.#Ve.values())t=t.concat(e.map((({listener:e})=>e)));return t}async off(e,t){const r=await this.#ot(e);if(!r)return this;if(t){const e=r.listeners.map((({listener:e})=>e)).indexOf(t);e>=0&&r.listeners.splice(e,1)}return t&&0!==r.listeners.length||(r.started&&r.subscriber.stop(),this.#Ve.delete(r.tag)),this}async removeAllListeners(e){if(e){const{tag:t,started:r,subscriber:n}=await this.#at(e);r&&n.stop(),this.#Ve.delete(t)}else for(const[e,{started:t,subscriber:r}]of this.#Ve)t&&r.stop(),this.#Ve.delete(e);return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return this.off(e,t)}get destroyed(){return this.#$e}destroy(){this.removeAllListeners();for(const e of this.#Xe.keys())this._clearTimeout(e);this.#$e=!0}get paused(){return null!=this.#He}set paused(e){!!e!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(e){if(this.#Ze=-1,null!=this.#He){if(this.#He==!!e)return;OA(!1,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber((t=>t.pause(e))),this.#He=!!e;for(const e of this.#Xe.values())e.timer&&clearTimeout(e.timer),e.time=OM()-e.time}resume(){if(null!=this.#He){this._forEachSubscriber((e=>e.resume())),this.#He=null;for(const e of this.#Xe.values()){let t=e.time;t<0&&(t=0),e.time=OM(),setTimeout(e.func,t)}}}}function LM(e,t){try{const r=FM(e,t);if(r)return AS(r)}catch(e){}return null}function FM(e,t){if("0x"===e)return null;try{const r=cS(JA(e,t,t+32)),n=cS(JA(e,r,r+32));return JA(e,r+32,r+32+n)}catch(e){}return null}function UM(e){const t=lS(e);if(t.length>32)throw new Error("internal; should not happen");const r=new Uint8Array(32);return r.set(t,32-t.length),r}function jM(e){if(e.length%32==0)return e;const t=new Uint8Array(32*Math.ceil(e.length/32));return t.set(e),t}const qM=new Uint8Array([]);function zM(e){const t=[];let r=0;for(let n=0;n<e.length;n++)t.push(qM),r+=32;for(let n=0;n<e.length;n++){const i=qA(e[n]);t[n]=UM(r),t.push(UM(i.length)),t.push(jM(i)),r+=32+32*Math.ceil(i.length/32)}return $A(t)}const KM="0x0000000000000000000000000000000000000000000000000000000000000000";function GM(e,t){if(e.provider)return e.provider;OA(!1,"missing provider","UNSUPPORTED_OPERATION",{operation:t})}async function VM(e,t){let r=pN(t);if(null!=r.to&&(r.to=$I(r.to,e)),null!=r.from){const t=r.from;r.from=Promise.all([e.getAddress(),$I(t,e)]).then((([e,t])=>(DA(e.toLowerCase()===t.toLowerCase(),"transaction from mismatch","tx.from",t),e)))}else r.from=e.getAddress();return await PA(r)}class HM{provider;constructor(e){TA(this,{provider:e||null})}async getNonce(e){return GM(this,"getTransactionCount").getTransactionCount(await this.getAddress(),e)}async populateCall(e){return await VM(this,e)}async populateTransaction(e){const t=GM(this,"populateTransaction"),r=await VM(this,e);null==r.nonce&&(r.nonce=await this.getNonce("pending")),null==r.gasLimit&&(r.gasLimit=await this.estimateGas(r));const n=await this.provider.getNetwork();if(null!=r.chainId){DA(iS(r.chainId)===n.chainId,"transaction chainId mismatch","tx.chainId",e.chainId)}else r.chainId=n.chainId;const i=null!=r.maxFeePerGas||null!=r.maxPriorityFeePerGas;if(null==r.gasPrice||2!==r.type&&!i?0!==r.type&&1!==r.type||!i||DA(!1,"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","tx",e):DA(!1,"eip-1559 transaction do not support gasPrice","tx",e),2!==r.type&&null!=r.type||null==r.maxFeePerGas||null==r.maxPriorityFeePerGas)if(0===r.type||1===r.type){const e=await t.getFeeData();OA(null!=e.gasPrice,"network does not support gasPrice","UNSUPPORTED_OPERATION",{operation:"getGasPrice"}),null==r.gasPrice&&(r.gasPrice=e.gasPrice)}else{const e=await t.getFeeData();if(null==r.type)if(null!=e.maxFeePerGas&&null!=e.maxPriorityFeePerGas)if(r.type=2,null!=r.gasPrice){const e=r.gasPrice;delete r.gasPrice,r.maxFeePerGas=e,r.maxPriorityFeePerGas=e}else null==r.maxFeePerGas&&(r.maxFeePerGas=e.maxFeePerGas),null==r.maxPriorityFeePerGas&&(r.maxPriorityFeePerGas=e.maxPriorityFeePerGas);else null!=e.gasPrice?(OA(!i,"network does not support EIP-1559","UNSUPPORTED_OPERATION",{operation:"populateTransaction"}),null==r.gasPrice&&(r.gasPrice=e.gasPrice),r.type=0):OA(!1,"failed to get consistent fee data","UNSUPPORTED_OPERATION",{operation:"signer.getFeeData"});else 2!==r.type&&3!==r.type||(null==r.maxFeePerGas&&(r.maxFeePerGas=e.maxFeePerGas),null==r.maxPriorityFeePerGas&&(r.maxPriorityFeePerGas=e.maxPriorityFeePerGas))}else r.type=2;return await PA(r)}async estimateGas(e){return GM(this,"estimateGas").estimateGas(await this.populateCall(e))}async call(e){return GM(this,"call").call(await this.populateCall(e))}async resolveName(e){const t=GM(this,"resolveName");return await t.resolveName(e)}async sendTransaction(e){const t=GM(this,"sendTransaction"),r=await this.populateTransaction(e);delete r.from;const n=GT.from(r);return await t.broadcastTransaction(await this.signTransaction(n))}}class $M extends HM{address;constructor(e,t){super(t),TA(this,{address:e})}async getAddress(){return this.address}connect(e){return new $M(this.address,e)}#ct(e,t){OA(!1,`VoidSigner cannot sign ${e}`,"UNSUPPORTED_OPERATION",{operation:t})}async signTransaction(e){this.#ct("transactions","signTransaction")}async signMessage(e){this.#ct("messages","signMessage")}async signTypedData(e,t,r){this.#ct("typed-data","signTypedData")}}class WM{#Be;#ut;#Le;#qe;#lt;#ht;constructor(e){this.#Be=e,this.#ut=null,this.#Le=this.#je.bind(this),this.#qe=!1,this.#lt=null,this.#ht=!1}_subscribe(e){throw new Error("subclasses must override this")}_emitResults(e,t){throw new Error("subclasses must override this")}_recover(e){throw new Error("subclasses must override this")}async#je(e){try{null==this.#ut&&(this.#ut=this._subscribe(this.#Be));let e=null;try{e=await this.#ut}catch(e){if(!NA(e,"UNSUPPORTED_OPERATION")||"eth_newFilter"!==e.operation)throw e}if(null==e)return this.#ut=null,void this.#Be._recoverSubscriber(this,this._recover(this.#Be));const t=await this.#Be.getNetwork();if(this.#lt||(this.#lt=t),this.#lt.chainId!==t.chainId)throw new Error("chaid changed");if(this.#ht)return;const r=await this.#Be.send("eth_getFilterChanges",[e]);await this._emitResults(this.#Be,r)}catch(e){console.log("@TODO",e)}this.#Be.once("block",this.#Le)}#dt(){const e=this.#ut;e&&(this.#ut=null,e.then((e=>{this.#Be.destroyed||this.#Be.send("eth_uninstallFilter",[e])})))}start(){this.#qe||(this.#qe=!0,this.#je(-2))}stop(){this.#qe&&(this.#qe=!1,this.#ht=!0,this.#dt(),this.#Be.off("block",this.#Le))}pause(e){e&&this.#dt(),this.#Be.off("block",this.#Le)}resume(){this.start()}}class JM extends WM{#ft;constructor(e,t){var r;super(e),this.#ft=(r=t,JSON.parse(JSON.stringify(r)))}_recover(e){return new IM(e,this.#ft)}async _subscribe(e){return await e.send("eth_newFilter",[this.#ft])}async _emitResults(e,t){for(const r of t)e.emit(this.#ft,e._wrapLog(r,e._network))}}class QM extends WM{async _subscribe(e){return await e.send("eth_newPendingTransactionFilter",[])}async _emitResults(e,t){for(const r of t)e.emit("pending",r)}}const ZM="bigint,boolean,function,number,string,symbol".split(/,/g);function YM(e){if(null==e||ZM.indexOf(typeof e)>=0)return e;if("function"==typeof e.getAddress)return e;if(Array.isArray(e))return e.map(YM);if("object"==typeof e)return Object.keys(e).reduce(((t,r)=>(t[r]=e[r],t)),{});throw new Error(`should not happen: ${e} (${typeof e})`)}function XM(e){return new Promise((t=>{setTimeout(t,e)}))}function ex(e){return e?e.toLowerCase():e}function tx(e){return e&&"number"==typeof e.pollingInterval}const rx={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3};class nx extends HM{address;constructor(e,t){super(e),TA(this,{address:t=GI(t)})}connect(e){OA(!1,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(e){return await this.populateCall(e)}async sendUncheckedTransaction(e){const t=YM(e),r=[];if(t.from){const n=t.from;r.push((async()=>{const r=await $I(n,this.provider);DA(null!=r&&r.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",e),t.from=r})())}else t.from=this.address;if(null==t.gasLimit&&r.push((async()=>{t.gasLimit=await this.provider.estimateGas({...t,from:this.address})})()),null!=t.to){const e=t.to;r.push((async()=>{t.to=await $I(e,this.provider)})())}r.length&&await Promise.all(r);const n=this.provider.getRpcTransaction(t);return this.provider.send("eth_sendTransaction",[n])}async sendTransaction(e){const t=await this.provider.getBlockNumber(),r=await this.sendUncheckedTransaction(e);return await new Promise(((e,n)=>{const i=[1e3,100];let s=0;const o=async()=>{try{const n=await this.provider.getTransaction(r);if(null!=n)return void e(n.replaceableTransaction(t))}catch(e){if(NA(e,"CANCELLED")||NA(e,"BAD_DATA")||NA(e,"NETWORK_ERROR")||NA(e,"UNSUPPORTED_OPERATION"))return null==e.info&&(e.info={}),e.info.sendTransactionHash=r,void n(e);if(NA(e,"INVALID_ARGUMENT")&&(s++,null==e.info&&(e.info={}),e.info.sendTransactionHash=r,s>10))return void n(e);this.provider.emit("error",xA("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:e}))}this.provider._setTimeout((()=>{o()}),i.pop()||4e3)};o()}))}async signTransaction(e){const t=YM(e);if(t.from){const r=await $I(t.from,this.provider);DA(null!=r&&r.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",e),t.from=r}else t.from=this.address;const r=this.provider.getRpcTransaction(t);return await this.provider.send("eth_signTransaction",[r])}async signMessage(e){const t="string"==typeof e?ES(e):e;return await this.provider.send("personal_sign",[HA(t),this.address.toLowerCase()])}async signTypedData(e,t,r){const n=YM(r),i=await s_.resolveNames(e,t,n,(async e=>{const t=await $I(e);return DA(null!=t,"TypedData does not support null address","value",e),t}));return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(s_.getPayload(i.domain,t,i.value))])}async unlock(e){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),e,null])}async _legacySignMessage(e){const t="string"==typeof e?ES(e):e;return await this.provider.send("eth_sign",[this.address.toLowerCase(),HA(t)])}}class ix extends BM{#$;#pt;#gt;#mt;#yt;#lt;#bt;#wt(){if(this.#mt)return;const e=1===this._getOption("batchMaxCount")?0:this._getOption("batchStallTime");this.#mt=setTimeout((()=>{this.#mt=null;const e=this.#gt;for(this.#gt=[];e.length;){const t=[e.shift()];for(;e.length&&t.length!==this.#$.batchMaxCount;){t.push(e.shift());if(JSON.stringify(t.map((e=>e.payload))).length>this.#$.batchMaxSize){e.unshift(t.pop());break}}(async()=>{const e=1===t.length?t[0].payload:t.map((e=>e.payload));this.emit("debug",{action:"sendRpcPayload",payload:e});try{const r=await this._send(e);this.emit("debug",{action:"receiveRpcResult",result:r});for(const{resolve:e,reject:n,payload:i}of t){if(this.destroyed){n(xA("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:i.method}));continue}const t=r.filter((e=>e.id===i.id))[0];if(null!=t)"error"in t?n(this.getRpcError(i,t)):e(t.result);else{const e=xA("missing response for request","BAD_DATA",{value:r,info:{payload:i}});this.emit("error",e),n(e)}}}catch(e){this.emit("debug",{action:"receiveRpcError",error:e});for(const{reject:r}of t)r(e)}})()}}),e)}constructor(e,t){super(e,t),this.#pt=1,this.#$=Object.assign({},rx,t||{}),this.#gt=[],this.#mt=null,this.#lt=null,this.#bt=null;{let e=null;const t=new Promise((t=>{e=t}));this.#yt={promise:t,resolve:e}}const r=this._getOption("staticNetwork");"boolean"==typeof r?(DA(!r||"any"!==e,"staticNetwork cannot be used on special network 'any'","options",t),r&&null!=e&&(this.#lt=yM.from(e))):r&&(DA(null==e||r.matches(e),"staticNetwork MUST match network object","options",t),this.#lt=r)}_getOption(e){return this.#$[e]}get _network(){return OA(this.#lt,"network is not available yet","NETWORK_ERROR"),this.#lt}async _perform(e){if("call"===e.method||"estimateGas"===e.method){let t=e.transaction;if(t&&null!=t.type&&iS(t.type)&&null==t.maxFeePerGas&&null==t.maxPriorityFeePerGas){const r=await this.getFeeData();null==r.maxFeePerGas&&null==r.maxPriorityFeePerGas&&(e=Object.assign({},e,{transaction:Object.assign({},t,{type:void 0})}))}}const t=this.getRpcRequest(e);return null!=t?await this.send(t.method,t.args):super._perform(e)}async _detectNetwork(){const e=this._getOption("staticNetwork");if(e){if(!0!==e)return e;if(this.#lt)return this.#lt}return this.#bt?await this.#bt:this.ready?(this.#bt=(async()=>{try{const e=yM.from(iS(await this.send("eth_chainId",[])));return this.#bt=null,e}catch(e){throw this.#bt=null,e}})(),await this.#bt):(this.#bt=(async()=>{const e={id:this.#pt++,method:"eth_chainId",params:[],jsonrpc:"2.0"};let t;this.emit("debug",{action:"sendRpcPayload",payload:e});try{t=(await this._send(e))[0],this.#bt=null}catch(e){throw this.#bt=null,this.emit("debug",{action:"receiveRpcError",error:e}),e}if(this.emit("debug",{action:"receiveRpcResult",result:t}),"result"in t)return yM.from(iS(t.result));throw this.getRpcError(e,t)})(),await this.#bt)}_start(){null!=this.#yt&&null!=this.#yt.resolve&&(this.#yt.resolve(),this.#yt=null,(async()=>{for(;null==this.#lt&&!this.destroyed;)try{this.#lt=await this._detectNetwork()}catch(e){if(this.destroyed)break;console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"),this.emit("error",xA("failed to bootstrap network detection","NETWORK_ERROR",{event:"initial-network-discovery",info:{error:e}})),await XM(1e3)}this.#wt()})())}async _waitUntilReady(){if(null!=this.#yt)return await this.#yt.promise}_getSubscriber(e){return"pending"===e.type?new QM(this):"event"===e.type?this._getOption("polling")?new IM(this,e.filter):new JM(this,e.filter):"orphan"===e.type&&"drop-log"===e.filter.orphan?new NM("orphan"):super._getSubscriber(e)}get ready(){return null==this.#yt}getRpcTransaction(e){const t={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach((r=>{if(null==e[r])return;let n=r;"gasLimit"===r&&(n="gas"),t[n]=hS(iS(e[r],`tx.${r}`))})),["from","to","data"].forEach((r=>{null!=e[r]&&(t[r]=HA(e[r]))})),e.accessList&&(t.accessList=CT(e.accessList)),e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.map((e=>e.toLowerCase()))),t}getRpcRequest(e){switch(e.method){case"chainId":return{method:"eth_chainId",args:[]};case"getBlockNumber":return{method:"eth_blockNumber",args:[]};case"getGasPrice":return{method:"eth_gasPrice",args:[]};case"getPriorityFee":return{method:"eth_maxPriorityFeePerGas",args:[]};case"getBalance":return{method:"eth_getBalance",args:[ex(e.address),e.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[ex(e.address),e.blockTag]};case"getCode":return{method:"eth_getCode",args:[ex(e.address),e.blockTag]};case"getStorage":return{method:"eth_getStorageAt",args:[ex(e.address),"0x"+e.position.toString(16),e.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[e.signedTransaction]};case"getBlock":if("blockTag"in e)return{method:"eth_getBlockByNumber",args:[e.blockTag,!!e.includeTransactions]};if("blockHash"in e)return{method:"eth_getBlockByHash",args:[e.blockHash,!!e.includeTransactions]};break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[e.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[e.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(e.transaction),e.blockTag]};case"estimateGas":return{method:"eth_estimateGas",args:[this.getRpcTransaction(e.transaction)]};case"getLogs":return e.filter&&null!=e.filter.address&&(Array.isArray(e.filter.address)?e.filter.address=e.filter.address.map(ex):e.filter.address=ex(e.filter.address)),{method:"eth_getLogs",args:[e.filter]}}return null}getRpcError(e,t){const{method:r}=e,{error:n}=t;if("eth_estimateGas"===r&&n.message){const t=n.message;if(!t.match(/revert/i)&&t.match(/insufficient funds/i))return xA("insufficient funds","INSUFFICIENT_FUNDS",{transaction:e.params[0],info:{payload:e,error:n}})}if("eth_call"===r||"eth_estimateGas"===r){const t=ax(n),i=rN.getBuiltinCallException("eth_call"===r?"call":"estimateGas",e.params[0],t?t.data:null);return i.info={error:n,payload:e},i}const i=JSON.stringify(function(e){const t=[];return cx(e,t),t}(n));if("string"==typeof n.message&&n.message.match(/user denied|ethers-user-denied/i)){return xA("user rejected action","ACTION_REJECTED",{action:{eth_sign:"signMessage",personal_sign:"signMessage",eth_signTypedData_v4:"signTypedData",eth_signTransaction:"signTransaction",eth_sendTransaction:"sendTransaction",eth_requestAccounts:"requestAccess",wallet_requestAccounts:"requestAccess"}[r]||"unknown",reason:"rejected",info:{payload:e,error:n}})}if("eth_sendRawTransaction"===r||"eth_sendTransaction"===r){const t=e.params[0];if(i.match(/insufficient funds|base fee exceeds gas limit/i))return xA("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:t,info:{error:n}});if(i.match(/nonce/i)&&i.match(/too low/i))return xA("nonce has already been used","NONCE_EXPIRED",{transaction:t,info:{error:n}});if(i.match(/replacement transaction/i)&&i.match(/underpriced/i))return xA("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:t,info:{error:n}});if(i.match(/only replay-protected/i))return xA("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:r,info:{transaction:t,info:{error:n}}})}let s=!!i.match(/the method .* does not exist/i);return s||n&&n.details&&n.details.startsWith("Unauthorized method:")&&(s=!0),s?xA("unsupported operation","UNSUPPORTED_OPERATION",{operation:e.method,info:{error:n,payload:e}}):xA("could not coalesce error","UNKNOWN_ERROR",{error:n,payload:e})}send(e,t){if(this.destroyed)return Promise.reject(xA("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:e}));const r=this.#pt++,n=new Promise(((n,i)=>{this.#gt.push({resolve:n,reject:i,payload:{method:e,params:t,id:r,jsonrpc:"2.0"}})}));return this.#wt(),n}async getSigner(e){null==e&&(e=0);const t=this.send("eth_accounts",[]);if("number"==typeof e){const r=await t;if(e>=r.length)throw new Error("no such account");return new nx(this,r[e])}const{accounts:r}=await PA({network:this.getNetwork(),accounts:t});e=GI(e);for(const t of r)if(GI(t)===e)return new nx(this,e);throw new Error("invalid account")}async listAccounts(){return(await this.send("eth_accounts",[])).map((e=>new nx(this,e)))}destroy(){this.#mt&&(clearTimeout(this.#mt),this.#mt=null);for(const{payload:e,reject:t}of this.#gt)t(xA("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:e.method}));this.#gt=[],super.destroy()}}class sx extends ix{#vt;constructor(e,t){super(e,t);let r=this._getOption("pollingInterval");null==r&&(r=rx.pollingInterval),this.#vt=r}_getSubscriber(e){const t=super._getSubscriber(e);return tx(t)&&(t.pollingInterval=this.#vt),t}get pollingInterval(){return this.#vt}set pollingInterval(e){if(!Number.isInteger(e)||e<0)throw new Error("invalid interval");this.#vt=e,this._forEachSubscriber((e=>{tx(e)&&(e.pollingInterval=this.#vt)}))}}class ox extends sx{#Et;constructor(e,t,r){null==e&&(e="http://localhost:8545"),super(t,r),this.#Et="string"==typeof e?new OS(e):e.clone()}_getConnection(){return this.#Et.clone()}async send(e,t){return await this._start(),await super.send(e,t)}async _send(e){const t=this._getConnection();t.body=JSON.stringify(e),t.setHeader("content-type","application/json");const r=await t.send();r.assertOk();let n=r.bodyJson;return Array.isArray(n)||(n=[n]),n}}function ax(e){if(null==e)return null;if("string"==typeof e.message&&e.message.match(/revert/i)&&KA(e.data))return{message:e.message,data:e.data};if("object"==typeof e){for(const t in e){const r=ax(e[t]);if(r)return r}return null}if("string"==typeof e)try{return ax(JSON.parse(e))}catch(e){}return null}function cx(e,t){if(null!=e){if("string"==typeof e.message&&t.push(e.message),"object"==typeof e)for(const r in e)cx(e[r],t);if("string"==typeof e)try{return cx(JSON.parse(e),t)}catch(e){}}}const ux=BigInt("1"),lx=BigInt("2");function hx(){return(new Date).getTime()}function dx(e){return JSON.stringify(e,((e,t)=>"bigint"==typeof t?{type:"bigint",value:t.toString()}:t))}const fx={stallTimeout:400,priority:1,weight:1},px={blockNumber:-2,requests:0,lateResponses:0,errorResponses:0,outOfSync:-1,unsupportedEvents:0,rollingDuration:0,score:0,_network:null,_updateNumber:null,_totalTime:0,_lastFatalError:null,_lastFatalErrorTimestamp:0};function gx(e){if(null==e)return"null";if(Array.isArray(e))return"["+e.map(gx).join(",")+"]";if("object"==typeof e&&"function"==typeof e.toJSON)return gx(e.toJSON());switch(typeof e){case"boolean":case"symbol":return e.toString();case"bigint":case"number":return BigInt(e).toString();case"string":return JSON.stringify(e);case"object":{const t=Object.keys(e);return t.sort(),"{"+t.map((t=>`${JSON.stringify(t)}:${gx(e[t])}`)).join(",")+"}"}}throw console.log("Could not serialize",e),new Error("Hmm...")}function mx(e){if("error"in e){const t=e.error;return{tag:gx(t),value:t}}const t=e.result;return{tag:gx(t),value:t}}function yx(e,t){const r=new Map;for(const{value:e,tag:n,weight:i}of t){const t=r.get(n)||{value:e,weight:0};t.weight+=i,r.set(n,t)}let n=null;for(const t of r.values())t.weight>=e&&(!n||t.weight>n.weight)&&(n=t);if(n)return n.value}function bx(e,t){let r=0;const n=new Map;let i=null;const s=[];for(const{value:e,tag:o,weight:a}of t)if(e instanceof Error){const t=n.get(o)||{value:e,weight:0};t.weight+=a,n.set(o,t),(null==i||t.weight>i.weight)&&(i=t)}else s.push(BigInt(e)),r+=a;if(r<e)return i&&i.weight>=e?i.value:void 0;s.sort(((e,t)=>e<t?-1:t>e?1:0));const o=Math.floor(s.length/2);return s.length%2?s[o]:(s[o-1]+s[o]+ux)/lx}function wx(e,t){const r=yx(e,t);if(void 0!==r)return r;for(const e of t)if(e.value)return e.value}class vx extends BM{quorum;eventQuorum;eventWorkers;#At;#St;#kt;constructor(e,t,r){super(t,r),this.#At=e.map((e=>e instanceof BM?Object.assign({provider:e},fx,px):Object.assign({},fx,e,px))),this.#St=-2,this.#kt=null,r&&null!=r.quorum?this.quorum=r.quorum:this.quorum=Math.ceil(this.#At.reduce(((e,t)=>e+=t.weight),0)/2),this.eventQuorum=1,this.eventWorkers=1,DA(this.quorum<=this.#At.reduce(((e,t)=>e+t.weight),0),"quorum exceed provider weight","quorum",this.quorum)}get providerConfigs(){return this.#At.map((e=>{const t=Object.assign({},e);for(const e in t)"_"===e[0]&&delete t[e];return t}))}async _detectNetwork(){return yM.from(iS(await this._perform({method:"chainId"})))}async _translatePerform(e,t){switch(t.method){case"broadcastTransaction":return await e.broadcastTransaction(t.signedTransaction);case"call":return await e.call(Object.assign({},t.transaction,{blockTag:t.blockTag}));case"chainId":return(await e.getNetwork()).chainId;case"estimateGas":return await e.estimateGas(t.transaction);case"getBalance":return await e.getBalance(t.address,t.blockTag);case"getBlock":{const r="blockHash"in t?t.blockHash:t.blockTag;return await e.getBlock(r,t.includeTransactions)}case"getBlockNumber":return await e.getBlockNumber();case"getCode":return await e.getCode(t.address,t.blockTag);case"getGasPrice":return(await e.getFeeData()).gasPrice;case"getPriorityFee":return(await e.getFeeData()).maxPriorityFeePerGas;case"getLogs":return await e.getLogs(t.filter);case"getStorage":return await e.getStorage(t.address,t.position,t.blockTag);case"getTransaction":return await e.getTransaction(t.hash);case"getTransactionCount":return await e.getTransactionCount(t.address,t.blockTag);case"getTransactionReceipt":return await e.getTransactionReceipt(t.hash);case"getTransactionResult":return await e.getTransactionResult(t.hash)}}#Rt(e){const t=Array.from(e).map((e=>e.config)),r=this.#At.slice();!function(e){for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*(t+1)),n=e[t];e[t]=e[r],e[r]=n}}(r),r.sort(((e,t)=>e.priority-t.priority));for(const e of r)if(!e._lastFatalError&&-1===t.indexOf(e))return e;return null}#Ct(e,t){const r=this.#Rt(e);if(null==r)return null;const n={config:r,result:null,didBump:!1,perform:null,staller:null},i=hx();return n.perform=(async()=>{try{r.requests++;const e=await this._translatePerform(r.provider,t);n.result={result:e}}catch(e){r.errorResponses++,n.result={error:e}}const e=hx()-i;r._totalTime+=e,r.rollingDuration=.95*r.rollingDuration+.05*e,n.perform=null})(),n.staller=(async()=>{var e;await(e=r.stallTimeout,new Promise((t=>{setTimeout(t,e)}))),n.staller=null})(),e.add(n),n}async#It(){let e=this.#kt;if(!e){const t=[];this.#At.forEach((e=>{t.push((async()=>{await async function(e,t){for(;(e.blockNumber<0||e.blockNumber<t)&&(e._updateNumber||(e._updateNumber=(async()=>{try{const t=await e.provider.getBlockNumber();t>e.blockNumber&&(e.blockNumber=t)}catch(t){e.blockNumber=-2,e._lastFatalError=t,e._lastFatalErrorTimestamp=hx()}e._updateNumber=null})()),await e._updateNumber,e.outOfSync++,!e._lastFatalError););}(e,0),e._lastFatalError||(e._network=await e.provider.getNetwork())})())})),this.#kt=e=(async()=>{await Promise.all(t);let e=null;for(const t of this.#At){if(t._lastFatalError)continue;const r=t._network;null==e?e=r.chainId:r.chainId!==e&&OA(!1,"cannot mix providers on different networks","UNSUPPORTED_OPERATION",{operation:"new FallbackProvider"})}})()}await e}async#Pt(e,t){const r=[];for(const t of e)if(null!=t.result){const{tag:e,value:n}=mx(t.result);r.push({tag:e,value:n,weight:t.config.weight})}if(!(r.reduce(((e,t)=>e+t.weight),0)<this.quorum)){switch(t.method){case"getBlockNumber":{-2===this.#St&&(this.#St=Math.ceil(cS(bx(this.quorum,this.#At.filter((e=>!e._lastFatalError)).map((e=>({value:e.blockNumber,tag:cS(e.blockNumber).toString(),weight:e.weight})))))));const e=function(e,t){if(1===e)return cS(bx(e,t),"%internal");const r=new Map,n=(e,t)=>{const n=r.get(e)||{result:e,weight:0};n.weight+=t,r.set(e,n)};for(const{weight:e,value:r}of t){const t=cS(r);n(t-1,e),n(t,e),n(t+1,e)}let i,s=0;for(const{weight:t,result:n}of r.values())t>=e&&(t>s||null!=i&&t===s&&n>i)&&(s=t,i=n);return i}(this.quorum,r);if(void 0===e)return;return e>this.#St&&(this.#St=e),this.#St}case"getGasPrice":case"getPriorityFee":case"estimateGas":return bx(this.quorum,r);case"getBlock":return"blockTag"in t&&"pending"===t.blockTag?wx(this.quorum,r):yx(this.quorum,r);case"call":case"chainId":case"getBalance":case"getTransactionCount":case"getCode":case"getStorage":case"getTransaction":case"getTransactionReceipt":case"getLogs":return yx(this.quorum,r);case"broadcastTransaction":return wx(this.quorum,r)}OA(!1,"unsupported method","UNSUPPORTED_OPERATION",{operation:`_perform(${dx(t.method)})`})}}async#Tt(e,t){if(0===e.size)throw new Error("no runners?!");const r=[];let n=0;for(const t of e)t.perform&&r.push(t.perform),t.staller?r.push(t.staller):t.didBump||(t.didBump=!0,n++);const i=await this.#Pt(e,t);if(void 0!==i){if(i instanceof Error)throw i;return i}for(let r=0;r<n;r++)this.#Ct(e,t);return OA(r.length>0,"quorum not met","SERVER_ERROR",{request:"%sub-requests",info:{request:t,results:Array.from(e).map((e=>dx(e.result)))}}),await Promise.race(r),await this.#Tt(e,t)}async _perform(e){if("broadcastTransaction"===e.method){const t=this.#At.map((e=>null)),r=this.#At.map((async({provider:r,weight:n},i)=>{try{const s=await r._perform(e);t[i]=Object.assign(mx({result:s}),{weight:n})}catch(e){t[i]=Object.assign(mx({error:e}),{weight:n})}}));for(;;){const e=t.filter((e=>null!=e));for(const{value:t}of e)if(!(t instanceof Error))return t;const n=yx(this.quorum,t.filter((e=>null!=e)));if(NA(n,"INSUFFICIENT_FUNDS"))throw n;const i=r.filter(((e,r)=>null==t[r]));if(0===i.length)break;await Promise.race(i)}const n=wx(this.quorum,t);if(OA(void 0!==n,"problem multi-broadcasting","SERVER_ERROR",{request:"%sub-requests",info:{request:e,results:t.map(dx)}}),n instanceof Error)throw n;return n}await this.#It();const t=new Set;let r=0;for(;;){const n=this.#Ct(t,e);if(null==n)break;if(r+=n.config.weight,r>=this.quorum)break}const n=await this.#Tt(t,e);for(const e of t)e.perform&&null==e.result&&e.config.lateResponses++;return n}async destroy(){for(const{provider:e}of this.#At)e.destroy();super.destroy()}}class Ex extends sx{#E;constructor(e,t,r){const n=Object.assign({},null!=r?r:{},{batchMaxCount:1});DA(e&&e.request,"invalid EIP-1193 provider","ethereum",e),super(t,n),this.#E=async(t,r)=>{const n={method:t,params:r};this.emit("debug",{action:"sendEip1193Request",payload:n});try{const t=await e.request(n);return this.emit("debug",{action:"receiveEip1193Result",result:t}),t}catch(e){const t=new Error(e.message);throw t.code=e.code,t.data=e.data,t.payload=n,this.emit("debug",{action:"receiveEip1193Error",error:t}),t}}}async send(e,t){return await this._start(),await super.send(e,t)}async _send(e){DA(!Array.isArray(e),"EIP-1193 does not support batch request","payload",e);try{const t=await this.#E(e.method,e.params||[]);return[{id:e.id,result:t}]}catch(t){return[{id:e.id,error:{code:t.code,data:t.data,message:t.message}}]}}getRpcError(e,t){switch((t=JSON.parse(JSON.stringify(t))).error.code||-1){case 4001:t.error.message=`ethers-user-denied: ${t.error.message}`;break;case 4200:t.error.message=`ethers-unsupported: ${t.error.message}`}return super.getRpcError(e,t)}async hasSigner(e){null==e&&(e=0);const t=await this.send("eth_accounts",[]);return"number"==typeof e?t.length>e:(e=e.toLowerCase(),0!==t.filter((t=>t.toLowerCase()===e)).length)}async getSigner(e){if(null==e&&(e=0),!await this.hasSigner(e))try{await this.#E("eth_requestAccounts",[])}catch(e){const t=e.payload;throw this.getRpcError(t,{id:t.id,error:e})}return await super.getSigner(e)}}class Ax extends HM{address;#_t;constructor(e,t){super(t),DA(e&&"function"==typeof e.sign,"invalid private key","privateKey","[ REDACTED ]"),this.#_t=e;TA(this,{address:IT(this.signingKey.publicKey)})}get signingKey(){return this.#_t}get privateKey(){return this.signingKey.privateKey}async getAddress(){return this.address}connect(e){return new Ax(this.#_t,e)}async signTransaction(e){e=pN(e);const{to:t,from:r}=await PA({to:e.to?$I(e.to,this.provider):void 0,from:e.from?$I(e.from,this.provider):void 0});null!=t&&(e.to=t),null!=r&&(e.from=r),null!=e.from&&(DA(GI(e.from)===this.address,"transaction from address mismatch","tx.from",e.from),delete e.from);const n=GT.from(e);return n.signature=this.signingKey.sign(n.unsignedHash),n.serialized}async signMessage(e){return this.signMessageSync(e)}signMessageSync(e){return this.signingKey.sign(function(e){return"string"==typeof e&&(e=ES(e)),xR($A([ES("Ethereum Signed Message:\n"),ES(String(e.length)),e]))}(e)).serialized}async signTypedData(e,t,r){const n=await s_.resolveNames(e,t,r,(async e=>{OA(null!=this.provider,"cannot resolve ENS names without a provider","UNSUPPORTED_OPERATION",{operation:"resolveName",info:{name:e}});const t=await this.provider.resolveName(e);return OA(null!=t,"unconfigured ENS name","UNCONFIGURED_NAME",{value:e}),t}));return this.signingKey.sign(s_.hash(n.domain,t,n.value)).serialized}}const Sx=" !#$%&'()*+,-./<=>?@[]^_`{|}~",kx=/^[a-z]*$/i;function Rx(e,t){let r=97;return e.reduce(((e,n)=>(n===t?r++:n.match(kx)?e.push(String.fromCharCode(r)+n):(r=97,e.push(n)),e)),[])}function Cx(e){return DA("0"===e[0],"unsupported auwl data","data",e),function(e,t){for(let r=28;r>=0;r--)e=e.split(Sx[r]).join(t.substring(2*r,2*r+2));const r=[],n=e.replace(/(:|([0-9])|([A-Z][a-z]*))/g,((e,t,n,i)=>{if(n)for(let e=parseInt(n);e>=0;e--)r.push(";");else r.push(t.toLowerCase());return""}));if(n)throw new Error(`leftovers: ${JSON.stringify(n)}`);return Rx(Rx(r,";"),":")}(e.substring(59),e.substring(1,59))}class Ix{locale;constructor(e){TA(this,{locale:e})}split(e){return e.toLowerCase().split(/\s+/g)}join(e){return e.join(" ")}}class Px extends Ix{#x;#Nt;constructor(e,t,r){super(e),this.#x=t,this.#Nt=r,this.#Mt=null}get _data(){return this.#x}_decodeWords(){return Cx(this.#x)}#Mt;#xt(){if(null==this.#Mt){const e=this._decodeWords();if(mP(e.join("\n")+"\n")!==this.#Nt)throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`);this.#Mt=e}return this.#Mt}getWord(e){const t=this.#xt();return DA(e>=0&&e<t.length,`invalid word index: ${e}`,"index",e),t[e]}getWordIndex(e){return this.#xt().indexOf(e)}}let Tx=null;class _x extends Px{constructor(){super("en","0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN<aNn RRelyRga(R*lSeS-SketTt!3A^AnAutyCau'ComeEfF%eG(Ha=H(dLie=LowLtN^Nef./TrayTt Twe&Y#d3Cyc!DKeNdOlogyRdR`Tt _{AdeAmeAnketA,EakE[IndOodO[omOu'UeUrUsh_rdAtDyIlMbNeNusOkO,Rd R(gRrowSsTtomUn)XY_{etA(AndA[A=EadEezeI{Id+IefIghtIngIskOccoliOk&OnzeOomO` OwnUsh2Bb!DdyD+tFf$oIldLbLkL!tNd!Nk Rd&Rg R,SS(e[SyTt Y Zz:Bba+B(B!CtusGeKe~LmM aMpNN$N)lNdyNn#NoeNvasNy#Pab!P.$Pta(RRb#RdRgoRpetRryRtSeShS(o/!Su$TT$ogT^Teg%yTt!UghtU'Ut]Ve3Il(gL yM|NsusNturyRe$Rta(_irAlkAmp]An+AosApt Ar+A'AtEapE{Ee'EfErryE,I{&IefIldIm}yOi)Oo'R#-U{!UnkUrn0G?Nnam#Rc!Tiz&TyVil_imApArifyAwAyE<ErkEv I{I|IffImbIn-IpO{OgO'O`OudOwnUbUmpU, Ut^_^A,C#utDeFfeeIlInL!@L%LumnMb(eMeMf%tM-Mm#Mp<yNc tNdu@NfirmNg*[N}@Nsid NtrolNv()OkOlPp PyR$ReRnR*@/Tt#U^UntryUp!Ur'Us(V Yo>_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M<dMi'Ni$Nti,NyP?tP&dPos.P`PutyRi=ScribeS tSignSkSpair/royTailTe@VelopVi)Vo>3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-Eg<tEm|Eph<tEvat%I>Se0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-P<dPe@Pi*Pla(Po'P*[T&dTra0EEbrow:Br-CeCultyDeIntI`~L'MeMilyMousNNcyNtasyRmSh]TT$Th TigueUltV%.e3Atu*Bru?yD $EEdElMa!N)/iv$T^V W3B Ct]EldGu*LeLmLt N$NdNeNg NishReRmR,Sc$ShTT}[X_gAmeAshAtAv%EeIghtIpOatO{O%Ow UidUshY_mCusGIlLd~owOdOtR)Re,R+tRkRtu}RumRw?dSsil/ UndX_gi!AmeEqu|EshI&dIn+OgOntO,OwnOz&U.2ElNNnyRna)RyTu*:D+tInLaxy~ yMePRa+Rba+Rd&Rl-Rm|SSpTeTh U+Ze3N $NiusN*Nt!Nu(e/u*2O,0AntFtGg!Ng RaffeRlVe_dAn)A*A[IdeImp'ObeOomOryO=OwUe_tDde[LdOdO'RillaSpelSsipV nWn_bA)A(AntApeA[Av.yEatE&IdIefItOc yOupOwUnt_rdE[IdeIltIt?N3M:B.IrLfMm M, NdPpyRb%RdRshR=,TVeWkZ?d3AdAl`ArtAvyD+hogIght~oLmetLpNRo3Dd&Gh~NtPRe/%y5BbyCkeyLdLeLiday~owMeNeyOdPeRnRr%R'Sp.$/TelUrV 5BGeM<Mb!M%Nd*dNgryNtRd!RryRtSb<d3Brid:1EOn0EaEntifyLe2N%e4LLeg$L}[0A+Ita>M&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryF<tFl-tF%mHa!H .Iti$Je@JuryMa>N Noc|PutQuiryS<eSe@SideSpi*/$lTa@T e,ToVe,V.eVol=3On0L<dOla>Sue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurE<Tob 0Or1FF Fi)T&2L1Ay0DI=Ymp-0It0CeEI#L(eLy1EnEraIn]Po'T]1An+B.Ch?dD D(?yG<I|Ig($Ph<0Tr-h0H 0Tdo%T TputTside0AlEnEr0NN 0Yg&0/ 0O}:CtDd!GeIrLa)LmNdaNelN-N` P RadeR|RkRrotRtySsT^ThTi|TrolTt nU'VeYm|3A)AnutArAs<tL-<NN$tyNcilOp!Pp Rfe@Rm.Rs#T2O}OtoRa'Ys-$0AnoCn-Ctu*E)GGe#~LotNkO} Pe/olT^Zza_)A}tA,-A>AyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOg<OtOwUsh0AllArtI!OkeOo`0A{AkeApIffOw0ApCc Ci$CkDaFtL?Ldi LidLut]L=Me#eNgOnRryRtUlUndUpUr)U`0A)A*Ati$AwnEakEci$EedEllEndH eI)Id IkeInIr.L.OilOns%O#OrtOtRayReadR(gY0Ua*UeezeUir*l_b!AdiumAffA+AirsAmpAndArtA>AyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NN<tNnisNtRm/Xt_nkAtEmeEnE%yE*EyIngIsOughtReeRi=RowUmbUnd 0CketDeG LtMb MeNyPRedSsueT!5A,BaccoDayDdl EGe` I!tK&MatoM%rowNeNgueNightOlO`PP-Pp!R^RnadoRtoi'SsT$Uri,W?dW WnY_{AdeAff-Ag-A(Ansf ApAshA=lAyEatEeEndI$IbeI{Igg ImIpOphyOub!U{UeUlyUmpetU,U`Y2BeIt]Mb!NaN}lRkeyRnRt!1El=EntyI)InI,O1PeP-$:5Ly5B*lla0Ab!Awa*C!Cov D DoFairFoldHappyIf%mIqueItIv 'KnownLo{TilUsu$Veil1Da>GradeHoldOnP Set1B<Ge0A+EEdEfulE![U$0Il.y:C<tCuumGueLidL!yL=NNishP%Rious/Ult3H-!L=tNd%Ntu*NueRbRifyRs]RyS'lT <3Ab!Br<tCiousCt%yDeoEw~a+Nta+Ol(Rtu$RusSaS.Su$T$Vid5C$I)IdLc<oLumeTeYa+:GeG#ItLk~LnutNtRfa*RmRri%ShSp/eT VeY3Al`Ap#ArA'lA` BDd(gEk&dIrdLcome/T_!AtEatEelEnE*IpIsp 0DeD`FeLd~NNdowNeNgNkNn Nt ReSdomSeShT}[5LfM<Nd OdOlRdRkRldRryR`_pE{E,!I,I>Ong::Rd3Ar~ow9UUngU`:3BraRo9NeO","0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60")}static wordlist(){return null==Tx&&(Tx=new _x),Tx}}function Nx(e){return(1<<e)-1<<8-e&255}function Mx(e,t){FA("NFKD"),null==t&&(t=_x.wordlist());const r=t.split(e);DA(r.length%3==0&&r.length>=12&&r.length<=24,"invalid mnemonic length","mnemonic","[ REDACTED ]");const n=new Uint8Array(Math.ceil(11*r.length/8));let i=0;for(let e=0;e<r.length;e++){let s=t.getWordIndex(r[e].normalize("NFKD"));DA(s>=0,`invalid mnemonic word at index ${e}`,"mnemonic","[ REDACTED ]");for(let e=0;e<11;e++)s&1<<10-e&&(n[i>>3]|=1<<7-i%8),i++}const s=32*r.length/3,o=Nx(r.length/3);return DA((qA(AC(n.slice(0,s/8)))[0]&o)===(n[n.length-1]&o),"invalid mnemonic checksum","mnemonic","[ REDACTED ]"),HA(n.slice(0,s/8))}function xx(e,t){DA(e.length%4==0&&e.length>=16&&e.length<=32,"invalid entropy size","entropy","[ REDACTED ]"),null==t&&(t=_x.wordlist());const r=[0];let n=11;for(let t=0;t<e.length;t++)n>8?(r[r.length-1]<<=8,r[r.length-1]|=e[t],n-=8):(r[r.length-1]<<=n,r[r.length-1]|=e[t]>>8-n,r.push(e[t]&((1<<8-n)-1&255)),n+=3);const i=e.length/4,s=parseInt(AC(e).substring(2,4),16)&Nx(i);return r[r.length-1]<<=i,r[r.length-1]|=s>>8-i,t.join(r.map((e=>t.getWord(e))))}const Ox={};class Dx{phrase;password;wordlist;entropy;constructor(e,t,r,n,i){null==n&&(n=""),null==i&&(i=_x.wordlist()),UA(e,Ox,"Mnemonic"),TA(this,{phrase:r,password:n,wordlist:i,entropy:t})}computeSeed(){const e=ES("mnemonic"+this.password,"NFKD");return tC(ES(this.phrase,"NFKD"),e,2048,64,"sha512")}static fromPhrase(e,t,r){const n=Mx(e,r);return e=xx(qA(n),r),new Dx(Ox,n,e,t,r)}static fromEntropy(e,t,r){const n=qA(e,"entropy"),i=xx(n,r);return new Dx(Ox,HA(n),i,t,r)}static entropyToPhrase(e,t){return xx(qA(e,"entropy"),t)}static phraseToEntropy(e,t){return Mx(e,t)}static isValidMnemonic(e,t){try{return Mx(e,t),!0}catch(e){}return!1}}
62
- /*! MIT License. Copyright 2015-2022 Richard Moore <me@ricmoo.com>. See LICENSE.txt. */var Bx,Lx,Fx,Ux=window&&window.__classPrivateFieldGet||function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)},jx=window&&window.__classPrivateFieldSet||function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r};const qx={16:10,24:12,32:14},zx=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],Kx=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],Gx=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],Vx=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],Hx=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],$x=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],Wx=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],Jx=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],Qx=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],Zx=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],Yx=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],Xx=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],eO=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],tO=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],rO=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function nO(e){const t=[];for(let r=0;r<e.length;r+=4)t.push(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]);return t}class iO{get key(){return Ux(this,Bx,"f").slice()}constructor(e){if(Bx.set(this,void 0),Lx.set(this,void 0),Fx.set(this,void 0),!(this instanceof iO))throw Error("AES must be instanitated with `new`");jx(this,Bx,new Uint8Array(e),"f");const t=qx[this.key.length];if(null==t)throw new TypeError("invalid key size (must be 16, 24 or 32 bytes)");jx(this,Fx,[],"f"),jx(this,Lx,[],"f");for(let e=0;e<=t;e++)Ux(this,Fx,"f").push([0,0,0,0]),Ux(this,Lx,"f").push([0,0,0,0]);const r=4*(t+1),n=this.key.length/4,i=nO(this.key);let s;for(let e=0;e<n;e++)s=e>>2,Ux(this,Fx,"f")[s][e%4]=i[e],Ux(this,Lx,"f")[t-s][e%4]=i[e];let o,a=0,c=n;for(;c<r;){if(o=i[n-1],i[0]^=Kx[o>>16&255]<<24^Kx[o>>8&255]<<16^Kx[255&o]<<8^Kx[o>>24&255]^zx[a]<<24,a+=1,8!=n)for(let e=1;e<n;e++)i[e]^=i[e-1];else{for(let e=1;e<n/2;e++)i[e]^=i[e-1];o=i[n/2-1],i[n/2]^=Kx[255&o]^Kx[o>>8&255]<<8^Kx[o>>16&255]<<16^Kx[o>>24&255]<<24;for(let e=n/2+1;e<n;e++)i[e]^=i[e-1]}let e,s,u=0;for(;u<n&&c<r;)e=c>>2,s=c%4,Ux(this,Fx,"f")[e][s]=i[u],Ux(this,Lx,"f")[t-e][s]=i[u++],c++}for(let e=1;e<t;e++)for(let t=0;t<4;t++)o=Ux(this,Lx,"f")[e][t],Ux(this,Lx,"f")[e][t]=Xx[o>>24&255]^eO[o>>16&255]^tO[o>>8&255]^rO[255&o]}encrypt(e){if(16!=e.length)throw new TypeError("invalid plaintext size (must be 16 bytes)");const t=Ux(this,Fx,"f").length-1,r=[0,0,0,0];let n=nO(e);for(let e=0;e<4;e++)n[e]^=Ux(this,Fx,"f")[0][e];for(let e=1;e<t;e++){for(let t=0;t<4;t++)r[t]=Vx[n[t]>>24&255]^Hx[n[(t+1)%4]>>16&255]^$x[n[(t+2)%4]>>8&255]^Wx[255&n[(t+3)%4]]^Ux(this,Fx,"f")[e][t];n=r.slice()}const i=new Uint8Array(16);let s=0;for(let e=0;e<4;e++)s=Ux(this,Fx,"f")[t][e],i[4*e]=255&(Kx[n[e]>>24&255]^s>>24),i[4*e+1]=255&(Kx[n[(e+1)%4]>>16&255]^s>>16),i[4*e+2]=255&(Kx[n[(e+2)%4]>>8&255]^s>>8),i[4*e+3]=255&(Kx[255&n[(e+3)%4]]^s);return i}decrypt(e){if(16!=e.length)throw new TypeError("invalid ciphertext size (must be 16 bytes)");const t=Ux(this,Lx,"f").length-1,r=[0,0,0,0];let n=nO(e);for(let e=0;e<4;e++)n[e]^=Ux(this,Lx,"f")[0][e];for(let e=1;e<t;e++){for(let t=0;t<4;t++)r[t]=Jx[n[t]>>24&255]^Qx[n[(t+3)%4]>>16&255]^Zx[n[(t+2)%4]>>8&255]^Yx[255&n[(t+1)%4]]^Ux(this,Lx,"f")[e][t];n=r.slice()}const i=new Uint8Array(16);let s=0;for(let e=0;e<4;e++)s=Ux(this,Lx,"f")[t][e],i[4*e]=255&(Gx[n[e]>>24&255]^s>>24),i[4*e+1]=255&(Gx[n[(e+3)%4]>>16&255]^s>>16),i[4*e+2]=255&(Gx[n[(e+2)%4]>>8&255]^s>>8),i[4*e+3]=255&(Gx[255&n[(e+1)%4]]^s);return i}}Bx=new WeakMap,Lx=new WeakMap,Fx=new WeakMap;class sO{constructor(e,t,r){if(r&&!(this instanceof r))throw new Error(`${e} must be instantiated with "new"`);Object.defineProperties(this,{aes:{enumerable:!0,value:new iO(t)},name:{enumerable:!0,value:e}})}}var oO,aO,cO=window&&window.__classPrivateFieldSet||function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r},uO=window&&window.__classPrivateFieldGet||function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class lO extends sO{constructor(e,t){if(super("ECC",e,lO),oO.set(this,void 0),aO.set(this,void 0),t){if(t.length%16)throw new TypeError("invalid iv size (must be 16 bytes)");cO(this,oO,new Uint8Array(t),"f")}else cO(this,oO,new Uint8Array(16),"f");cO(this,aO,this.iv,"f")}get iv(){return new Uint8Array(uO(this,oO,"f"))}encrypt(e){if(e.length%16)throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)");const t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=16){for(let t=0;t<16;t++)uO(this,aO,"f")[t]^=e[r+t];cO(this,aO,this.aes.encrypt(uO(this,aO,"f")),"f"),t.set(uO(this,aO,"f"),r)}return t}decrypt(e){if(e.length%16)throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)");const t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=16){const n=this.aes.decrypt(e.subarray(r,r+16));for(let i=0;i<16;i++)t[r+i]=n[i]^uO(this,aO,"f")[i],uO(this,aO,"f")[i]=e[r+i]}return t}}oO=new WeakMap,aO=new WeakMap;var hO,dO,fO,pO=window&&window.__classPrivateFieldSet||function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r},gO=window&&window.__classPrivateFieldGet||function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class mO extends sO{constructor(e,t){super("CTR",e,mO),hO.set(this,void 0),dO.set(this,void 0),fO.set(this,void 0),pO(this,fO,new Uint8Array(16),"f"),gO(this,fO,"f").fill(0),pO(this,hO,gO(this,fO,"f"),"f"),pO(this,dO,16,"f"),null==t&&(t=1),"number"==typeof t?this.setCounterValue(t):this.setCounterBytes(t)}get counter(){return new Uint8Array(gO(this,fO,"f"))}setCounterValue(e){if(!Number.isInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new TypeError("invalid counter initial integer value");for(let t=15;t>=0;--t)gO(this,fO,"f")[t]=e%256,e=Math.floor(e/256)}setCounterBytes(e){if(16!==e.length)throw new TypeError("invalid counter initial Uint8Array value length");gO(this,fO,"f").set(e)}increment(){for(let e=15;e>=0;e--){if(255!==gO(this,fO,"f")[e]){gO(this,fO,"f")[e]++;break}gO(this,fO,"f")[e]=0}}encrypt(e){var t,r;const n=new Uint8Array(e);for(let e=0;e<n.length;e++)16===gO(this,dO,"f")&&(pO(this,hO,this.aes.encrypt(gO(this,fO,"f")),"f"),pO(this,dO,0,"f"),this.increment()),n[e]^=gO(this,hO,"f")[(pO(this,dO,(r=gO(this,dO,"f"),t=r++,r),"f"),t)];return n}decrypt(e){return this.encrypt(e)}}function yO(e){return"string"!=typeof e||e.startsWith("0x")||(e="0x"+e),zA(e)}function bO(e,t){for(e=String(e);e.length<t;)e="0"+e;return e}function wO(e){return"string"==typeof e?ES(e,"NFKC"):zA(e)}function vO(e,t){const r=t.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);DA(null!=r,"invalid path","path",t);const n=r[1],i=r[3],s="!"===r[4];let o=e;for(const e of n.toLowerCase().split(".")){if(Array.isArray(o)){if(!e.match(/^[0-9]+$/))break;o=o[parseInt(e)]}else if("object"==typeof o){let t=null;for(const r in o)if(r.toLowerCase()===e){t=o[r];break}o=t}else o=null;if(null==o)break}if(DA(!s||null!=o,"missing required value","path",n),i&&null!=o){if("int"===i){if("string"==typeof o&&o.match(/^-?[0-9]+$/))return parseInt(o);if(Number.isSafeInteger(o))return o}if("number"===i&&"string"==typeof o&&o.match(/^-?[0-9.]*$/))return parseFloat(o);if("data"===i&&"string"==typeof o)return yO(o);if("array"===i&&Array.isArray(o))return o;if(i===typeof o)return o;DA(!1,`wrong type found for ${i} `,"path",n)}return o}hO=new WeakMap,dO=new WeakMap,fO=new WeakMap;const EO="m/44'/60'/0'/0/0";function AO(e){try{const t=JSON.parse(e);if(3===(null!=t.version?parseInt(t.version):0))return!0}catch(e){}return!1}function SO(e,t){const r=qA(t),n=vO(e,"crypto.ciphertext:data!");DA(HA(xR($A([r.slice(16,32),n]))).substring(2)===vO(e,"crypto.mac:string!").toLowerCase(),"incorrect password","password","[ REDACTED ]");const i=function(e,t,r){if("aes-128-ctr"===vO(e,"crypto.cipher:string")){const n=vO(e,"crypto.cipherparams.iv:data!");return HA(new mO(t,n).decrypt(r))}OA(!1,"unsupported cipher","UNSUPPORTED_OPERATION",{operation:"decrypt"})}(e,r.slice(0,16),n),s=IT(i);if(e.address){let t=e.address.toLowerCase();t.startsWith("0x")||(t="0x"+t),DA(GI(t)===s,"keystore address/privateKey mismatch","address",e.address)}const o={address:s,privateKey:i};if("0.1"===vO(e,"x-ethers.version:string")){const t=r.slice(32,64),n=vO(e,"x-ethers.mnemonicCiphertext:data!"),i=vO(e,"x-ethers.mnemonicCounter:data!"),s=new mO(t,i);o.mnemonic={path:vO(e,"x-ethers.path:string")||EO,locale:vO(e,"x-ethers.locale:string")||"en",entropy:HA(qA(s.decrypt(n)))}}return o}function kO(e){const t=vO(e,"crypto.kdf:string");if(t&&"string"==typeof t){if("scrypt"===t.toLowerCase()){const r=vO(e,"crypto.kdfparams.salt:data!"),n=vO(e,"crypto.kdfparams.n:int!"),i=vO(e,"crypto.kdfparams.r:int!"),s=vO(e,"crypto.kdfparams.p:int!");DA(n>0&&!(n&n-1),"invalid kdf.N","kdf.N",n),DA(i>0&&s>0,"invalid kdf","kdf",t);const o=vO(e,"crypto.kdfparams.dklen:int!");return DA(32===o,"invalid kdf.dklen","kdf.dflen",o),{name:"scrypt",salt:r,N:n,r:i,p:s,dkLen:64}}if("pbkdf2"===t.toLowerCase()){const t=vO(e,"crypto.kdfparams.salt:data!"),r=vO(e,"crypto.kdfparams.prf:string!"),n=r.split("-").pop();DA("sha256"===n||"sha512"===n,"invalid kdf.pdf","kdf.pdf",r);const i=vO(e,"crypto.kdfparams.c:int!"),s=vO(e,"crypto.kdfparams.dklen:int!");return DA(32===s,"invalid kdf.dklen","kdf.dklen",s),{name:"pbkdf2",salt:t,count:i,dkLen:s,algorithm:n}}}DA(!1,"unsupported key-derivation function","kdf",t)}function RO(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}function CO(e){const t=null!=e.salt?qA(e.salt,"options.salt"):sC(32);let r=1<<17,n=8,i=1;return e.scrypt&&(e.scrypt.N&&(r=e.scrypt.N),e.scrypt.r&&(n=e.scrypt.r),e.scrypt.p&&(i=e.scrypt.p)),DA("number"==typeof r&&r>0&&Number.isSafeInteger(r)&&(BigInt(r)&BigInt(r-1))===BigInt(0),"invalid scrypt N parameter","options.N",r),DA("number"==typeof n&&n>0&&Number.isSafeInteger(n),"invalid scrypt r parameter","options.r",n),DA("number"==typeof i&&i>0&&Number.isSafeInteger(i),"invalid scrypt p parameter","options.p",i),{name:"scrypt",dkLen:32,salt:t,N:r,r:n,p:i}}function IO(e,t,r,n){const i=qA(r.privateKey,"privateKey"),s=null!=n.iv?qA(n.iv,"options.iv"):sC(16);DA(16===s.length,"invalid options.iv length","options.iv",n.iv);const o=null!=n.uuid?qA(n.uuid,"options.uuid"):sC(16);DA(16===o.length,"invalid options.uuid length","options.uuid",n.iv);const a=e.slice(0,16),c=e.slice(16,32),u=qA(new mO(a,s).encrypt(i)),l=xR($A([c,u])),h={address:r.address.substring(2).toLowerCase(),id:nk(o),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:HA(s).substring(2)},ciphertext:HA(u).substring(2),kdf:"scrypt",kdfparams:{salt:HA(t.salt).substring(2),n:t.N,dklen:32,p:t.p,r:t.r},mac:l.substring(2)}};if(r.mnemonic){const t=null!=n.client?n.client:`ethers/${CA}`,i=r.mnemonic.path||EO,s=r.mnemonic.locale||"en",o=e.slice(32,64),a=qA(r.mnemonic.entropy,"account.mnemonic.entropy"),c=sC(16),u=qA(new mO(o,c).encrypt(a)),l=new Date,d="UTC--"+(l.getUTCFullYear()+"-"+bO(l.getUTCMonth()+1,2)+"-"+bO(l.getUTCDate(),2)+"T"+bO(l.getUTCHours(),2)+"-"+bO(l.getUTCMinutes(),2)+"-"+bO(l.getUTCSeconds(),2)+".0Z")+"--"+h.address;h["x-ethers"]={client:t,gethFilename:d,path:i,locale:s,mnemonicCounter:HA(c).substring(2),mnemonicCiphertext:HA(u).substring(2),version:"0.1"}}return JSON.stringify(h)}function PO(e,t,r){null==r&&(r={});const n=wO(t),i=CO(r);return IO(qA(bC(n,i.salt,i.N,i.r,i.p,64)),i,e,r)}async function TO(e,t,r){null==r&&(r={});const n=wO(t),i=CO(r);return IO(qA(await yC(n,i.salt,i.N,i.r,i.p,64,r.progressCallback)),i,e,r)}const _O="m/44'/60'/0'/0/0",NO=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]),MO=2147483648,xO=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");function OO(e,t){let r="";for(;e;)r="0123456789abcdef"[e%16]+r,e=Math.trunc(e/16);for(;r.length<2*t;)r="0"+r;return"0x"+r}function DO(e){const t=qA(e);return yS($A([t,JA(AC(AC(t)),0,4)]))}const BO={};function LO(e,t,r,n){const i=new Uint8Array(37);e&MO?(OA(null!=n,"cannot derive child of neutered node","UNSUPPORTED_OPERATION",{operation:"deriveChild"}),i.set(qA(n),1)):i.set(qA(r));for(let t=24;t>=0;t-=8)i[33+(t>>3)]=e>>24-t&255;const s=qA(pR("sha512",t,i));return{IL:s.slice(0,32),IR:s.slice(32)}}function FO(e,t){const r=t.split("/");DA(r.length>0,"invalid path","path",t),"m"===r[0]&&(DA(0===e.depth,`cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${e.depth}`,"path",t),r.shift());let n=e;for(let e=0;e<r.length;e++){const t=r[e];if(t.match(/^[0-9]+'$/)){const r=parseInt(t.substring(0,t.length-1));DA(r<MO,"invalid path index",`path[${e}]`,t),n=n.deriveChild(MO+r)}else if(t.match(/^[0-9]+$/)){const r=parseInt(t);DA(r<MO,"invalid path index",`path[${e}]`,t),n=n.deriveChild(r)}else DA(!1,"invalid path component",`path[${e}]`,t)}return n}class UO extends Ax{publicKey;fingerprint;parentFingerprint;mnemonic;chainCode;path;index;depth;constructor(e,t,r,n,i,s,o,a,c){super(t,c),UA(e,BO,"HDNodeWallet"),TA(this,{publicKey:t.compressedPublicKey});TA(this,{parentFingerprint:r,fingerprint:JA(ZR(AC(this.publicKey)),0,4),chainCode:n,path:i,index:s,depth:o}),TA(this,{mnemonic:a})}connect(e){return new UO(BO,this.signingKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.mnemonic,e)}#Ot(){const e={address:this.address,privateKey:this.privateKey},t=this.mnemonic;return this.path&&t&&"en"===t.wordlist.locale&&""===t.password&&(e.mnemonic={path:this.path,locale:"en",entropy:t.entropy}),e}async encrypt(e,t){return await TO(this.#Ot(),e,{progressCallback:t})}encryptSync(e){return PO(this.#Ot(),e)}get extendedKey(){return OA(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),DO($A(["0x0488ADE4",OO(this.depth,1),this.parentFingerprint,OO(this.index,4),this.chainCode,$A(["0x00",this.privateKey])]))}hasPath(){return null!=this.path}neuter(){return new jO(BO,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.provider)}deriveChild(e){const t=cS(e,"index");DA(t<=4294967295,"invalid index","index",t);let r=this.path;r&&(r+="/"+(2147483647&t),t&MO&&(r+="'"));const{IR:n,IL:i}=LO(t,this.chainCode,this.publicKey,this.privateKey),s=new FI(uS((aS(i)+BigInt(this.privateKey))%xO,32));return new UO(BO,s,this.fingerprint,HA(n),r,t,this.depth+1,this.mnemonic,this.provider)}derivePath(e){return FO(this,e)}static#Dt(e,t){DA(GA(e),"invalid seed","seed","[REDACTED]");const r=qA(e,"seed");DA(r.length>=16&&r.length<=64,"invalid seed","seed","[REDACTED]");const n=qA(pR("sha512",NO,r)),i=new FI(HA(n.slice(0,32)));return new UO(BO,i,"0x00000000",HA(n.slice(32)),"m",0,0,t,null)}static fromExtendedKey(e){const t=lS(function(e){let t=gS;for(let r=0;r<e.length;r++)t*=mS,t+=pS(e[r]);return t}(e));DA(82===t.length||DO(t.slice(0,78))===e,"invalid extended key","extendedKey","[ REDACTED ]");const r=t[4],n=HA(t.slice(5,9)),i=parseInt(HA(t.slice(9,13)).substring(2),16),s=HA(t.slice(13,45)),o=t.slice(45,78);switch(HA(t.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const e=HA(o);return new jO(BO,IT(e),e,n,s,null,i,r,null)}case"0x0488ade4":case"0x04358394 ":if(0!==o[0])break;return new UO(BO,new FI(o.slice(1)),n,s,null,i,r,null,null)}DA(!1,"invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(e,t,r){null==e&&(e=""),null==t&&(t=_O),null==r&&(r=_x.wordlist());const n=Dx.fromEntropy(sC(16),e,r);return UO.#Dt(n.computeSeed(),n).derivePath(t)}static fromMnemonic(e,t){return t||(t=_O),UO.#Dt(e.computeSeed(),e).derivePath(t)}static fromPhrase(e,t,r,n){null==t&&(t=""),null==r&&(r=_O),null==n&&(n=_x.wordlist());const i=Dx.fromPhrase(e,t,n);return UO.#Dt(i.computeSeed(),i).derivePath(r)}static fromSeed(e){return UO.#Dt(e,null)}}class jO extends $M{publicKey;fingerprint;parentFingerprint;chainCode;path;index;depth;constructor(e,t,r,n,i,s,o,a,c){super(t,c),UA(e,BO,"HDNodeVoidWallet"),TA(this,{publicKey:r});TA(this,{publicKey:r,fingerprint:JA(ZR(AC(r)),0,4),parentFingerprint:n,chainCode:i,path:s,index:o,depth:a})}connect(e){return new jO(BO,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,e)}get extendedKey(){return OA(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),DO($A(["0x0488B21E",OO(this.depth,1),this.parentFingerprint,OO(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return null!=this.path}deriveChild(e){const t=cS(e,"index");DA(t<=4294967295,"invalid index","index",t);let r=this.path;r&&(r+="/"+(2147483647&t),t&MO&&(r+="'"));const{IR:n,IL:i}=LO(t,this.chainCode,this.publicKey,null),s=FI.addPoints(i,this.publicKey,!0),o=IT(s);return new jO(BO,o,s,this.fingerprint,HA(n),r,t,this.depth+1,this.provider)}derivePath(e){return FO(this,e)}}function qO(e){try{if(JSON.parse(e).encseed)return!0}catch(e){}return!1}function zO(e,t){const r=JSON.parse(e),n=wO(t),i=GI(vO(r,"ethaddr:string!")),s=yO(vO(r,"encseed:string!"));DA(s&&s.length%16==0,"invalid encseed","json",e);const o=qA(tC(n,n,2e3,32,"sha256")).slice(0,16),a=s.slice(0,16),c=s.slice(16),u=function(e){if(e.length<16)throw new TypeError("PKCS#7 invalid length");const t=e[e.length-1];if(t>16)throw new TypeError("PKCS#7 padding byte out of range");const r=e.length-t;for(let n=0;n<t;n++)if(e[r+n]!==t)throw new TypeError("PKCS#7 invalid padding byte");return new Uint8Array(e.subarray(0,r))}(qA(new lO(o,a).decrypt(c)));let l="";for(let e=0;e<u.length;e++)l+=String.fromCharCode(u[e]);return{address:i,privateKey:mP(l)}}function KO(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}class GO extends Ax{constructor(e,t){"string"!=typeof e||e.startsWith("0x")||(e="0x"+e),super("string"==typeof e?new FI(e):e,t)}connect(e){return new GO(this.signingKey,e)}async encrypt(e,t){const r={address:this.address,privateKey:this.privateKey};return await TO(r,e,{progressCallback:t})}encryptSync(e){return PO({address:this.address,privateKey:this.privateKey},e)}static#Bt(e){if(DA(e,"invalid JSON wallet","json","[ REDACTED ]"),"mnemonic"in e&&e.mnemonic&&"en"===e.mnemonic.locale){const t=Dx.fromEntropy(e.mnemonic.entropy),r=UO.fromMnemonic(t,e.mnemonic.path);if(r.address===e.address&&r.privateKey===e.privateKey)return r;console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key")}const t=new GO(e.privateKey);return DA(t.address===e.address,"address/privateKey mismatch","json","[ REDACTED ]"),t}static async fromEncryptedJson(e,t,r){let n=null;return AO(e)?n=await async function(e,t,r){const n=JSON.parse(e),i=wO(t),s=kO(n);if("pbkdf2"===s.name){r&&(r(0),await RO(0));const{salt:e,count:t,dkLen:o,algorithm:a}=s,c=tC(i,e,t,o,a);return r&&(r(1),await RO(0)),SO(n,c)}OA("scrypt"===s.name,"cannot be reached","UNKNOWN_ERROR",{params:s});const{salt:o,N:a,r:c,p:u,dkLen:l}=s;return SO(n,await yC(i,o,a,c,u,l,r))}(e,t,r):qO(e)&&(r&&(r(0),await KO(0)),n=zO(e,t),r&&(r(1),await KO(0))),GO.#Bt(n)}static fromEncryptedJsonSync(e,t){let r=null;return AO(e)?r=function(e,t){const r=JSON.parse(e),n=wO(t),i=kO(r);if("pbkdf2"===i.name){const{salt:e,count:t,dkLen:s,algorithm:o}=i;return SO(r,tC(n,e,t,s,o))}OA("scrypt"===i.name,"cannot be reached","UNKNOWN_ERROR",{params:i});const{salt:s,N:o,r:a,p:c,dkLen:u}=i;return SO(r,bC(n,s,o,a,c,u))}(e,t):qO(e)?r=zO(e,t):DA(!1,"invalid JSON wallet","json","[ REDACTED ]"),GO.#Bt(r)}static createRandom(e){const t=UO.createRandom();return e?t.connect(e):t}static fromPhrase(e,t){const r=UO.fromPhrase(e);return t?r.connect(t):r}}const VO=new Bv("LoggingJsonRpcProvider");class HO extends ox{urlConfig;constructor(e,t,r){super(e,t,r),this.urlConfig=e}async send(e,t){const r=Wv(5),n=Date.now(),i={traceId:r,method:e,params:t,connection:{url:this.urlConfig.url,timeout:this.urlConfig.timeout}};let s;VO.debug("Send request",i);try{s=await super.send(e,t)}catch(e){throw VO.debug("Encountered error while requesting",{...i,err:e,elapsedTime:Date.now()-n}),e}return VO.debug("Received response",{...i,elapsedTime:Date.now()-n}),s}}var $O,WO,JO={},QO={};var ZO=(WO||(WO=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.config=void 0;const t=($O||($O=1,Object.defineProperty(QO,"__esModule",{value:!0}),QO.config=void 0,QO.config={dev0:{id:8995,name:"dev0",nativeCurrency:{symbol:"DEV",name:"Developer Ethereum",decimals:18},rpcEndpoints:[{url:"http://10.200.10.1:8545"},{url:"ws://10.200.10.1:8545"}],contracts:{AMB:"0xaFA0dc5Ad21796C9106a36D68f69aAD69994BB64",DATA:"0xbAA81A0179015bE47Ad439566374F2Bae098686F",DataUnionFactory:"0x90a0480c6fA6b2dC967d8F03660c81C8a5A7c465",DataUnionTemplate:"0x07a4CaF6064ACFe4c279e32e5ed2F376B36DcB3F",DefaultFeeOracle:"0x454E0fEcCf4611eA9E41C986E4A2949CFD4b53d4",ENS:"0x92E8435EB56fD01BF4C79B66d47AC1A94338BB03",FIFSRegistrar:"0x57B81a9442805f88c4617B506206531e72d96290",Marketplace:"0xF1371c0f40528406dc4f4cAf89924eA9Da49E866",MarketplaceV3:"0x56e57Bf7422eDe1ED75520D4387829feEe8a8319",MigrationManager:"0xc7aaf6c62e86a36395d8108fe95d5f758794c16c",PublicResolver:"0xBc0c81a318D57ae54dA28DE69184A9c3aE9a1e1c",TokenMediator:"0xedD2aa644a6843F2e5133Fe3d6BD3F4080d97D9F",TrackerRegistry:"0xBFCF120a8fD17670536f1B27D9737B775b2FD4CF",Uniswap2Router:"0xeE1bC9a7BFF1fFD913f4c97B6177D47E804E1920",UniswapAdapter:"0xE4eA76e830a659282368cA2e7E4d18C4AE52D8B3",Uniswap2AdapterForMarketplaceV3:"0xDbcdfB708A006A9AebC592C4520289cD87a95938",XDATA:"0x6d0F3bF9aD2455b4F62f22fFD21317e1E3eEFE5C","core-api":"0xFCAd0B19bB29D4674531d6f115237E16AfCE377c"}},dev1:{id:8997,name:"dev1",nativeCurrency:{symbol:"DEV",name:"Developer Ethereum",decimals:18},rpcEndpoints:[{url:"http://10.200.10.1:8546"},{url:"ws://10.200.10.1:8546"}],contracts:{AMB:"0xaFA0dc5Ad21796C9106a36D68f69aAD69994BB64",DATA:"0x73Be21733CC5D08e1a14Ea9a399fb27DB3BEf8fF",DataUnionFactory:"0x50aAa135AeBAC61E8394F80fF2Df091fcb66b072",DefaultFeeOracle:"0xd1FA6C06E1D838Bb989640A2C4b8a499FD0ab187",DataUnionTemplate:"0xC2F87E37019e227F2Be5030aabBCc7eAF136e05c",LINK:"0x3387F44140ea19100232873a5aAf9E46608c791E",Marketplace:"0xa072C42CB167d68D4c1cA15d0e4d0bd93E74A80f",MarketplaceV3:"0xA90CeCcA042312b8f2e8B924C04Ce62516CBF7b2",MarketplaceV4:"0xB9372284e0D61607aF3B7EF5f022e7D599Ed2a37",ProjectRegistryV1:"0x3C841B9Aa08166e9B864972930703e878d25804B",ProjectStakingV1:"0xBFCF120a8fD17670536f1B27D9737B775b2FD4CF",Mediator:"0xedD2aa644a6843F2e5133Fe3d6BD3F4080d97D9F",StorageNodeRegistry:"0x231b810D98702782963472e1D60a25496999E75D",StreamRegistry:"0x6cCdd5d866ea766f6DF5965aA98DeCCD629ff222",ENSCacheV2:"0x611900fD07BB133016Ed85553aF9586771da5ff9",StreamStorageRegistry:"0xd04af489677001444280366Dd0885B03dAaDe71D",Uniswap2Router:"0xdc5F6368cd31330adC259386e78604a5E29E9415",StreamrConfig:"0xa86863053cECFD9f6f861e0Fd39a042238411b75",SponsorshipFactory:"0x58C8e321d561123649bE41445cB0690Ec3d27Fe9",SponsorshipDefaultLeavePolicy:"0xa2338F8be0941B361baBebb01ab8da5725CF0a33",SponsorshipMaxOperatorsJoinPolicy:"0x2521E0480004056c35e199a1BBE2FdA9119032A0",SponsorshipOperatorContractOnlyJoinPolicy:"0xd8F0a63e5EB661695620c92af5d981D18d5a484E",SponsorshipStakeWeightedAllocationPolicy:"0xef927F18D2ac3862c6ABCAa953203A4DbF7f519e",SponsorshipVoteKickPolicy:"0x0617466e5bC15027c604A56E35b172E06d689E4f",OperatorFactory:"0xcb5bCb343218044C547AFdcBa2e50Ac728D0DcA3",OperatorDefaultDelegationPolicy:"0x03CF38C75BFb9F4466fBA0aEd95f2613B0D1bCA0",OperatorDefaultUndelegationPolicy:"0x67A0E9C9c21d11dB4eBAe420aBf705626a3a2561",OperatorDefaultExchangeRatePolicy:"0x252743660fACD52e7CEF851CEB1c133B58Fb526d"},theGraphUrl:"http://10.200.10.1:8000/subgraphs/name/streamr-dev/network-subgraphs"},dev2:{id:31337,name:"dev2",nativeCurrency:{symbol:"DEV",name:"Developer Ethereum",decimals:18},rpcEndpoints:[{url:"http://10.200.10.1:8547"}],adminPrivateKey:"0x5e98cce00cff5dea6b454889f359a4ec06b9fa6b88e9d69b86de8e1c81887da0",contracts:{DATA:"0xbAA81A0179015bE47Ad439566374F2Bae098686F",ENS:"0xEAA002f7Dc60178B6103f8617Be45a9D3df659B6",FIFSRegistrar:"0xF1371c0f40528406dc4f4cAf89924eA9Da49E866",PublicResolver:"0xdc5F6368cd31330adC259386e78604a5E29E9415",TrackerRegistry:"0xE4eA76e830a659282368cA2e7E4d18C4AE52D8B3",StorageNodeRegistry:"0x338090C5492C5c5E41a4458f5FC4b205cbc54A24",StreamRegistry:"0x18E0937099660B82464475Ea2B7e6Af4f2BFE5F0",ENSCacheV2:"0x7739b57beC285539A62434DF9808f66ebB405ba3",StreamStorageRegistry:"0xB73189CeBCc870bE6f9aa16764bbB3665e4B49B6",StreamrConfig:"0x00E680d549FE53a627a3db86a6F88fA2471CFfAa",SponsorshipOperatorContractOnlyJoinPolicy:"0xB9372284e0D61607aF3B7EF5f022e7D599Ed2a37",SponsorshipMaxOperatorsJoinPolicy:"0x36368Be8Cde49558Ab6ceEf2632984b282Db8775",SponsorshipStakeWeightedAllocationPolicy:"0xc24BA8c05E5206F1bE57bfA0aD14E9882126eD38",SponsorshipDefaultLeavePolicy:"0xBFCF120a8fD17670536f1B27D9737B775b2FD4CF",SponsorshipVoteKickPolicy:"0x92E8435EB56fD01BF4C79B66d47AC1A94338BB03",SponsorshipFactory:"0x699B4bE95614f017Bb622e427d3232837Cc814E6",OperatorDefaultDelegationPolicy:"0x5159FBF2e0Ff63e35b17293416fdf7a0909a0cDA",OperatorDefaultExchangeRatePolicy:"0xfC31c70FafCbFe399195C789602ae2455B247fD2",OperatorDefaultUndelegationPolicy:"0xBacF06448F4f14361AD80d425686021b041F3B2C",OperatorFactory:"0xD13D34d37e2c94cb35EA8D5DE7498Cb7830d26e0",ProjectRegistryV1:"0xA9166376706611110f814D1333b8E80FEc5d8f10",MarketplaceV4:"0xb8678223183d560280a7BEF68daAbB0E3daBd97D",ProjectStakingV1:"0x73a9310C43621B853C508902bb8c1DA8f1240EaE"},theGraphUrl:"http://10.200.10.1:8800/subgraphs/name/streamr-dev/network-subgraphs",entryPoints:[{nodeId:"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",websocket:{host:"10.200.10.1",port:40500,tls:!1}}]},alfajores:{id:44787,name:"Celo Alfajores",nativeCurrency:{symbol:"CELO",name:"Celo Alfajores",decimals:18},rpcEndpoints:[{url:"https://alfajores-forno.celo-testnet.org"}],contracts:{ProjectRegistryV1:"0x32A142A27A595DC75aD1443728fecCbD5650446A",MarketplaceV4:"0x14577e0D5BD77536E073712d98E471edDaFAE8b4",cUSD:"0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1"},blockExplorerUrl:"https://alfajores.celoscan.io"},optGoerli:{id:420,name:"Optimism Goerli Testnet",nativeCurrency:{symbol:"ETH",name:"Optimism Goerli Testnet Ethereum",decimals:18},rpcEndpoints:[{url:"https://goerli.optimism.io"}],contracts:{RemoteMarketplaceV1:"0xBef916b1EC6EAA3F522368f75094DAed5c228aF6",DAI:"0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1"},blockExplorerUrl:"https://goerli-optimism.etherscan.io"},ethereum:{id:1,name:"Ethereum",nativeCurrency:{symbol:"ETH",name:"Ethereum",decimals:18},rpcEndpoints:[],contracts:{AMB:"0x4C36d2919e407f0Cc2Ee3c993ccF8ac26d9CE64e",DATA:"0x8f693ca8D21b157107184d29D398A8D082b38b76",ENS:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",Marketplace:"0xdc8d23092b93f9bb7416f45dea36f55996f34867",MediatorDATA:"0x29e572d45cC33D5a68DCc8f92bfc7ded0017Bc59",MediatorXDATA:"0x2eeeDdeECe91c9F4c5bA4C8E1d784A0234C6d015",MigrationManager:"0xf32219E61c840300D1B35c939ed9E54a86163334",TrackerRegistry:"0xab9BEb0e8B106078c953CcAB4D6bF9142BeF854d",UniswapAdapter:"0xbe99db4ea1964ea9a9e80de41517901da6ef9307",XDATA:"0x0cf0ee63788a0849fe5297f3407f701e122cc023","core-api":"0xf3E5A65851C3779f468c9EcB32E6f25D9D68601a"},blockExplorerUrl:"https://etherscan.io"},gnosis:{id:100,name:"Gnosis Chain",nativeCurrency:{symbol:"xDAI",name:"xDai",decimals:18},rpcEndpoints:[{url:"https://rpc.gnosischain.com"},{url:"wss://rpc.gnosischain.com/wss"}],contracts:{AMB:"0x75Df5AF045d91108662D8080fD1FEFAd6aA0bb59",BinanceAdapterDATA:"0x193888692673b5dD46e6BC90bA8cBFeDa515c8C1",BinanceAdapterXDATA:"0x0c1aF6edA561fbDA48E9A7B1Dd46D216F31A97cC",DATA:"0x256eb8a51f382650B2A1e946b8811953640ee47D",DataUnionFactory:"0xe4515702878931b45Dfe4D89d3Fb3208910C913C",DataUnionTemplate:"0x1d425525c7A5df3736875fe76Bc3B9E776E89AcA",DataUnionFeeOracle:"0x86686266E7cA80b247151104f26d308079997637",Marketplace:"0x246dd6D96282c1ED9Ca69eF9f3e1f975fC1B8Bd5",MarketplaceV3:"0x2022E1F7749D355726Fb65285E29605A098bcb52",MediatorDATA:"0x53f3F44c434494da73EC44a6E8a8D091332bC2ce",MediatorXDATA:"0x7d55f9981d4E10A193314E001b96f72FCc901e40",MigrationManager:"0x29e572d45cC33D5a68DCc8f92bfc7ded0017Bc59",RemoteMarketplaceV1:"0x023eaE17d3dd65F1e7b4daa355e6478719Bd2BEf",StorageNodeRegistry:"0xC746847d7916623fb75849696f04827bbc34854f",UniswapAdapter:"0xc5Cd4900841a849d798725441b54fB0fec0d0f5b",Uniswap2AdapterForMarketplaceV3:"0xec92c5f94d45D1a4D917f2E07dD959b33e1AFe38",XDATA:"0xE4a2620edE1058D61BEe5F45F6414314fdf10548"},blockExplorerUrl:"https://gnosisscan.io"},binance:{id:56,name:"BNB Chain",nativeCurrency:{symbol:"BNB",name:"BNB",decimals:18},rpcEndpoints:[{url:"https://bsc-dataseed.binance.org"},{url:"wss://bsc-dataseed.binance.org"}],contracts:{DATA:"0x0864c156b3c5f69824564dec60c629ae6401bf2a",xdaiBridge:"0xa93ee7b4a7215f7e725437a6b6d7a4e7fe1dd8f0"},blockExplorerUrl:"https://bscscan.com"},polygon:{id:137,name:"Polygon",nativeCurrency:{symbol:"MATIC",name:"MATIC",decimals:18},rpcEndpoints:[{url:"https://polygon-rpc.com"},{url:"https://polygon.drpc.org"},{url:"https://rpc-mainnet.matic.quiknode.pro"},{url:"https://polygon-bor-rpc.publicnode.com"}],contracts:{ChainlinkOracle:"0x36BF71D0ba2e449fc14f9C4cF51468948E4ED27D",DATA:"0x3a9A81d576d83FF21f26f325066054540720fC34",DataUnionFactory:"0xd0B3a09A6bCee8446d10e6E7e12c78F8725C9B18",DataUnionTemplate:"0xaFe97F5a1cD3edE2c11d990e0EB0270054AA0589",DataUnionFeeOracle:"0x369Be397b3Cfe914728Bbd2329c0e5D1FE2E4202",GSNPayMaster:"0x43E69adABC664617EB9C5E19413a335e9cd4A243",GSNForwarder:"0xdA78a11FD57aF7be2eDD804840eA7f4c2A38801d",ENSCache:"0xEd9d3D29c25e197677DD84E3f7D81cCCD613B2bF",ENSCacheV2:"0xEd9d3D29c25e197677DD84E3f7D81cCCD613B2bF",Marketplace:"0x058FbB3Cf628EE51CE8864C9Ee8350f81E495A7D",MarketplaceV3:"0x1e9c22B4C92ce78Fe489C72f9D070C583D8359C3",MarketplaceV4:"0xdF8b74D735197dCD5C94bE933db080E69A958de6",ProjectRegistryV1:"0x496a6154da5aA6a021a3bd0DCd337DA80F48a6e1",ProjectStakingV1:"0xAA7a4BdBE91F143F3103206e48A8AfF21101B6DE",StorageNodeRegistry:"0x080F34fec2bc33928999Ea9e39ADc798bEF3E0d6",StreamRegistry:"0x0D483E10612F327FC11965Fc82E90dC19b141641",StreamStorageRegistry:"0xe8e2660CeDf2a59C917a5ED05B72df4146b58399",StreamrConfig:"0x869e88dB146ECAF20dDf199a12684cD80c263c8f",SponsorshipOperatorContractOnlyJoinPolicy:"0xa1F3c94A682Cb43d26AcC40dA1Dc31f49e4dA466",SponsorshipMaxOperatorsJoinPolicy:"0x27448061420bAccAE8c84DDC3E7e2e8B2aE4977E",SponsorshipStakeWeightedAllocationPolicy:"0x1Dd16E748308E9f259f3D6097d00e1793BfBdcDB",SponsorshipDefaultLeavePolicy:"0xa953D590098A3d56304a12A8e929D63748D90AAC",SponsorshipVoteKickPolicy:"0xeF3F567D7328849c1130CBCBF8Cd9feB42eA5dB5",SponsorshipFactory:"0x820b2f9a15ed45F9802c59d0CC77C22C81755e45",OperatorDefaultDelegationPolicy:"0x8e449F0B1AFAD807135B5Ea829F41851d5DE1426",OperatorDefaultExchangeRatePolicy:"0xE8F511bB4888D16D81acab7ab1c05A356E37237f",OperatorDefaultUndelegationPolicy:"0x5c81fA1e79318386Dd82Ef059bCB194DbA87De45",OperatorFactory:"0x935734e66729b69260543Cf6e5EfeB42AC962183",Uniswap2Router:"0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff",UniswapAdapter:"0xAd54A57383EcA2D4f0D22337A96A7c4f6Bd51A13",Uniswap2AdapterForMarketplaceV3:"0x83C42F77c6dD09A1A93A7834be65b3bB891106bE"},blockExplorerUrl:"https://polygonscan.com",theGraphUrl:"https://gateway-arbitrum.network.thegraph.com/api/a971cec07440a9ec63cd806c06ccc990/subgraphs/id/EGWFdhhiWypDuz22Uy7b3F69E9MEkyfU9iAQMttkH5Rj",entryPoints:[{nodeId:"e5f87a7ee99b3c91e7b795b70f87ef8ba5497596",websocket:{host:"polygon-entrypoint-3.streamr.network",port:443,tls:!0}},{nodeId:"6f5b53812fd9cc07f225a0b3a6aa5b96672e852e",websocket:{host:"polygon-entrypoint-4.streamr.network",port:443,tls:!0}}]},polygonAmoy:{id:80002,name:"Polygon Amoy testnet",nativeCurrency:{symbol:"MATIC",name:"Amoy MATIC",decimals:18},rpcEndpoints:[{url:"https://polygon-amoy-bor-rpc.publicnode.com"},{url:"https://rpc-amoy.polygon.technology"}],contracts:{DATA:"0xf5e28a2E7BbedbE97c3782b17b102410E10d90f1",StreamRegistry:"0xE9C98bdE63248e58E9137Db8270D9675B9E34b93",ENSCacheV2:"0x6a81414936868fdcF4f077e2a0B24879e2871016",StorageNodeRegistry:"0x02fdF917f4e6Ae8F7F1bBDd28179d819E2b76820",StreamStorageRegistry:"0x0f3671A9A92416E1aD32750faCf2AD4FA1b66f78",StreamrConfig:"0x835bC97D2a61bbF5d05932C5105Ca34e1b815F94",SponsorshipOperatorContractOnlyJoinPolicy:"0x930Dcc2ca313ACf7177185C0D68462fDc699C7e0",SponsorshipMaxOperatorsJoinPolicy:"0xd640C2C5102953d122759826daa6Aec25eC98ca5",SponsorshipStakeWeightedAllocationPolicy:"0xaC80c738FCF8d259F07C82eAD68B75aF4DF82223",SponsorshipDefaultLeavePolicy:"0x16Ba0F2793Da54b67717c6bAD471624C6628F2aa",SponsorshipVoteKickPolicy:"0xA73aDbEC14be2D3628CeAD022243f080CB162955",SponsorshipFactory:"0xb194a68b166f2e3074B551393fA61490D19c69f8",OperatorDefaultDelegationPolicy:"0x78f29fF290148e83795393f1858DC540D8cB046b",OperatorDefaultExchangeRatePolicy:"0x48d25dd5731AD644613b67E4281C505Ef392Dd70",OperatorDefaultUndelegationPolicy:"0x7962155D5ea2fF949FCF300F221964d5ef9d1bad",OperatorFactory:"0xE02E8E9fF5ea6a58F34D00C0e4B091e066B9fA81",ProjectRegistryV1:"0xc5e1434d35c0c7291c7032Fd9C4096b4876C6823",ProjectStakingV1:"0x3A27A16770477EbcFb4B81cE462F4f12591767A0",MarketplaceV4:"0x6C8eaA8e0bF605469c15b6F9106387B4cEC99976",DataUnionFactory:"0x62d48EBcf518AF1eb4c647721a19B046810623c4",DataUnionTemplate:"0xACe6B50B1d1Fb06b4650eF4Adb094747C65Ab674",DataUnionFeeOracle:"0x1A20217419156E09D36fd380d3F429d03AD2Dc97"},theGraphUrl:"https://gateway.thegraph.com/api/dd2dd773d33a3b2f5028ddaa8e1874c1/subgraphs/id/3nVH84bDz3wFJ82UZxMD2WfpGyU2KzDnZdEdDQFsHAqp",blockExplorerUrl:"https://amoy.polygonscan.com",entryPoints:[{nodeId:"d48787fc36eaed43770ec84947ef81557b19ec98",websocket:{host:"amoy-entrypoint-1.streamr.network",port:443,tls:!0}},{nodeId:"24395826687b099fd735a730219ba750169c4f40",websocket:{host:"amoy-entrypoint-2.streamr.network",port:443,tls:!0}}]},peaq:{id:3338,name:"Peaq EVM chain",nativeCurrency:{symbol:"PEAQ",name:"PEAQ",decimals:18},rpcEndpoints:[{url:"https://peaq.api.onfinality.io/public"}],contracts:{DATA:"0xdCB1EcdD509c61De5C3B672fDD2335AC750142c9",StreamRegistry:"0xD0C720e99Bd39311614f292d8B0B4e351Bde157c",ENSCacheV2:"0x4A71d0FA9e3326E830048B1423d7010fB9343071",StorageNodeRegistry:"0xaCF9e8134047eDc671162D9404BF63a587435bAa",StreamStorageRegistry:"0xB36CF8ee4219a3Ac9FBC3865C35E9a99353c26db",StreamrConfig:"0xc81Fa3Cc3E81dF24D21bfc608f8FB06262Da4F8c",SponsorshipOperatorContractOnlyJoinPolicy:"0xF655955dc561356851e95a6D0febeB0BAc955Ab5",SponsorshipMaxOperatorsJoinPolicy:"0xE41439BF434F9CfBF0153f5231C205d4ae0C22e3",SponsorshipStakeWeightedAllocationPolicy:"0xC8E8efAF4CE7bCcFc87878631BC64A1FAe63dc5D",SponsorshipDefaultLeavePolicy:"0xDa579a9a55158Bc57389f1b05F553DEf38a121c1",SponsorshipVoteKickPolicy:"0xdc8d23092b93F9BB7416F45dEa36f55996f34867",SponsorshipFactory:"0xdaF0905e19C45b9Fea7E60D232061edF78E9F570",OperatorDefaultDelegationPolicy:"0xD3329a2FC8194f0F96749275FF5162f7f2F031F7",OperatorDefaultExchangeRatePolicy:"0xA3D82B569ab0dEF86935fCf4e7714626a608CF81",OperatorDefaultUndelegationPolicy:"0x3EF89eF888721446Cf373C5070399B8225C9E936",OperatorFactory:"0x6d201374D7c28EF1c3cc1b6FA300f06110B597A3",ProjectRegistryV1:"0xB14205AE3D7672B937B972EBdf2b986fB0B8CfaA",ProjectStakingV1:"0xd1cBD6b1Be710C41c01A9613802209843407b8b9",MarketplaceV4:"0x959684926448296ea72BD4B05593426A3cD3F0dF"},blockExplorerUrl:"https://peaq.subscan.io",theGraphUrl:"https://gateway.thegraph.com/api/5bcf7b0d11045c944600d4007737d457/subgraphs/id/CV3grB3fYpUzET1s75kXG2BaNyREK5uRA8SkjLTyXXh7",entryPoints:[{nodeId:"e5f87a7ee99b3c91e7b795b70f87ef8ba5497596",websocket:{host:"polygon-entrypoint-3.streamr.network",port:443,tls:!0}},{nodeId:"6f5b53812fd9cc07f225a0b3a6aa5b96672e852e",websocket:{host:"polygon-entrypoint-4.streamr.network",port:443,tls:!0}}]},iotex:{id:4689,name:"IoTeX",nativeCurrency:{symbol:"IOTX",name:"IOTX",decimals:18},rpcEndpoints:[{url:"https://babel-api.mainnet.iotex.one"}],contracts:{DATA:"0xD94be6fd546d4cE502CB1E870A58330Cc8869e9B",StreamRegistry:"0x080F34fec2bc33928999Ea9e39ADc798bEF3E0d6",ENSCacheV2:"0xAB072849dd3Cd648cb85c73d525a70A36523337d",StorageNodeRegistry:"0xb9e70Bd9833dd091f06edc8073aa86a76EdeF46D",StreamStorageRegistry:"0xF79c40Fbc432f1f8B8B017441B644e0ac7bccea2",StreamrConfig:"0x176B108E72ee49A01Bea1eDb32f7f296d2bb3db8",SponsorshipOperatorContractOnlyJoinPolicy:"0xace5b2A71A44efD9259983b5671d8ba802703dF7",SponsorshipMaxOperatorsJoinPolicy:"0x6956abe11F99e3983282f8B4fFb30015cC45Ae1D",SponsorshipStakeWeightedAllocationPolicy:"0x0Eb81BF75e585B227c01BBd1Ba5Ee0Ab6b1b55d5",SponsorshipDefaultLeavePolicy:"0xb9fe5430aC3eE3B1D26734C513f41Bf96B10C830",SponsorshipVoteKickPolicy:"0xc4a1ba0655FC6C34F9283e33682e57031fC060af",SponsorshipFactory:"0x7ac03730374E995E366F2a466be6aCC14E1DB1C4",OperatorDefaultDelegationPolicy:"0x5E0F361EC38cBE990baCB0D3008B5582DA4eAa2a",OperatorDefaultExchangeRatePolicy:"0x75e26741538825263954AC2a1Ad9d6eAb695FD47",OperatorDefaultUndelegationPolicy:"0x6D48ee54898e9B1f5FBe468ab85eA542dd82Ae6c",OperatorFactory:"0xD1Bc2A37405F88d4904844B7BF1BEadA7c0851c1",ProjectRegistryV1:"0xbb2a2CF40Ca86378983cfcACB7Aac1568237a692",MarketplaceV4:"0xe3F6750a5f9a6315cB11adc5CE980F7356C927C4",ProjectStakingV1:"0x0F91Edc1760e64e434Fb9CaF93a76b262E7015b3"},blockExplorerUrl:"https://iotexscan.io",theGraphUrl:"https://gateway.thegraph.com/api/4bddc6e1e1fe65a49bf8091785478835/subgraphs/id/CvGQcfBwWH1SvyxJDGjRRMa4YXQpxmpt369orMirZ3RH",entryPoints:[{nodeId:"e5f87a7ee99b3c91e7b795b70f87ef8ba5497596",websocket:{host:"polygon-entrypoint-3.streamr.network",port:443,tls:!0}},{nodeId:"6f5b53812fd9cc07f225a0b3a6aa5b96672e852e",websocket:{host:"polygon-entrypoint-4.streamr.network",port:443,tls:!0}}]},iotexTestnet:{id:4690,name:"IoTeX Testnet",nativeCurrency:{symbol:"IOTEX",name:"IOTEX",decimals:18},rpcEndpoints:[{url:"https://babel-api.testnet.iotex.io"}],contracts:{DATA:"0x5ABD469031d2B5f939808565EAB8562d7Cbaa939",StreamRegistry:"0xDC695780959aa5aEe9B28dfED7332032e3045210",ENSCacheV2:"0xDDf8FB60f8c3ffb1C20375A30f6D8CFB0C48Bd38",StorageNodeRegistry:"0xc0F9666fbF16B2ac5726697237BcdF79096e3FA7",StreamStorageRegistry:"0xd0C3A69762Bd920C1cAfBE91612a4600429f02f1",StreamrConfig:"0x6d201374D7c28EF1c3cc1b6FA300f06110B597A3",SponsorshipOperatorContractOnlyJoinPolicy:"0xAd24077505d3584F1AC8d78719F9d31F7Da0E264",SponsorshipMaxOperatorsJoinPolicy:"0x78d13aaBA657F448933Bb469E4E549Dee88cB78B",SponsorshipStakeWeightedAllocationPolicy:"0xB14205AE3D7672B937B972EBdf2b986fB0B8CfaA",SponsorshipDefaultLeavePolicy:"0xfC9C1886EAd9a757039Edbee16Bea0183344D2BA",SponsorshipVoteKickPolicy:"0xd1cBD6b1Be710C41c01A9613802209843407b8b9",SponsorshipFactory:"0x84c8d8f9760639e159350e5d2Bfaada99b670114",OperatorDefaultDelegationPolicy:"0x67352e3F7dBA907aF877020aE7E9450C0029C70c",OperatorDefaultExchangeRatePolicy:"0xE41439BF434F9CfBF0153f5231C205d4ae0C22e3",OperatorDefaultUndelegationPolicy:"0xF655955dc561356851e95a6D0febeB0BAc955Ab5",OperatorFactory:"0xdaF0905e19C45b9Fea7E60D232061edF78E9F570"},blockExplorerUrl:"https://testnet.iotexscan.io",entryPoints:[]}}),QO);Object.defineProperty(e,"config",{enumerable:!0,get:function(){return t.config}}),t.config}(JO)),JO),YO=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},XO=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},eD=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};function tD(e){return e.contracts.ethereumNetwork.chainId===ZO.config.dev2.id}const rD=e=>({staticNetwork:!0,batchStallTime:tD(e)?0:void 0,cacheTimeout:tD(e)?-1:void 0});e.RpcProviderSource=class{config;provider;subProviders;constructor(e){this.config=e}getProvider(){if(void 0===this.provider){const e=this.getSubProviders();this.provider=new vx(e,this.config.contracts.ethereumNetwork.chainId,{quorum:Math.min(this.config.contracts.rpcQuorum,this.config.contracts.rpcs.length),cacheTimeout:rD(this.config).cacheTimeout})}return this.provider}getSubProviders(){return this.subProviders??=this.config.contracts.rpcs.map((e=>{const t=new OS(e.url);t.retryFunc=async()=>!1,t.timeout=this.config._timeouts.jsonRpcTimeout;const r=rD(this.config);return new HO(t,this.config.contracts.ethereumNetwork.chainId,r)})),this.subProviders}},e.RpcProviderSource=YO([q(d.ContainerScoped),eD(0,U(cA)),XO("design:paramtypes",[Object])],e.RpcProviderSource);const nD=async(e,t)=>{const r=t.contracts.ethereumNetwork,n=r.overrides??{};if(r.highGasPriceStrategy&&void 0===r.overrides?.gasPrice){const t=await e.getProvider().getFeeData(),r=e=>null===e.gasPrice?void 0:e.gasPrice*BigInt(130)/100n;return{...n,gasPrice:r(t)}}return n};var iD=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o};let sD=class extends sE{};sD=iD([q(d.ContainerScoped)],sD);var oD=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},aD=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},cD=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let uD=class{config;constructor(e){this.config=e}createLogger(e){return new Bv(e,{id:this.config.id},this.config.logLevel)}};var lD,hD,dD,fD;uD=oD([q(d.ContainerScoped),cD(0,U(cA)),aD("design:paramtypes",[Object])],uD);var pD=function(){if(fD)return dD;fD=1;const e=function(){if(hD)return lD;hD=1;class e{constructor(e){this.value=e,this.next=void 0}}class t{constructor(){this.clear()}enqueue(t){const r=new e(t);this._head?(this._tail.next=r,this._tail=r):(this._head=r,this._tail=r),this._size++}dequeue(){const e=this._head;if(e)return this._head=this._head.next,this._size--,e.value}clear(){this._head=void 0,this._tail=void 0,this._size=0}get size(){return this._size}*[Symbol.iterator](){let e=this._head;for(;e;)yield e.value,e=e.next}}return lD=t}();return dD=t=>{if(!Number.isInteger(t)&&t!==1/0||!(t>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");const r=new e;let n=0;const i=async(e,t,...i)=>{n++;const s=(async()=>e(...i))();t(s);try{await s}catch{}n--,r.size>0&&r.dequeue()()},s=(e,...s)=>new Promise((o=>{((e,s,...o)=>{r.enqueue(i.bind(null,e,s,...o)),(async()=>{await Promise.resolve(),n<t&&r.size>0&&r.dequeue()()})()})(e,o,...s)}));return Object.defineProperties(s,{activeCount:{get:()=>n},pendingCount:{get:()=>r.size},clearQueue:{value:()=>{r.clear()}}}),s}}(),gD=n(pD);async function mD(e){return(await e).wait()}const yD=async(e,t,r)=>{try{return await e()}catch(e){const n=ju(["reason","code"].map((t=>void 0!==e[t]?`${t}=${e[t]}`:void 0)),void 0),i=new Error(`Error while ${r} contract call "${t}"${n.length>0?", "+n.join(", "):""}`);throw i.reason=e,i}},bD=(e,t,r,n)=>{const i=new Sl,s=gD(n),o={eventEmitter:i,getAddress:()=>e.getAddress(),on:(t,r)=>{e.on(t,r)},off:(t,r)=>{e.off(t,r)}},a=e.interface.fragments.filter((e=>J_.isFunction(e))).map((e=>e.name));return a.forEach((r=>{o[r]=((e,t,r,n,i)=>{const s=e[r],o=`${t}.${r}`,a=async(...e)=>{const t=await yD((()=>i((()=>(n.emit("onMethodExecute",o),s(...e))))),o,"executing");if((e=>void 0!==e.wait&&"function"==typeof e.wait)(t)){n.emit("onTransactionSubmit",o,t);const e=t.wait.bind(t);t.wait=async(t,i)=>{const s=await yD((()=>e(t,i)),r,"waiting transaction for");return n.emit("onTransactionConfirm",o,s),s}}return t};return a.estimateGas=(...e)=>s.estimateGas(...e),a})(e,t,r,i,s)})),((e,t)=>{const r=t.createLogger("contract");e.on("onMethodExecute",(e=>{r.debug("Execute method",{methodName:e})})),e.on("onTransactionSubmit",((e,t)=>{r.debug("Submit transaction",{method:e,tx:t.hash,to:t.to,nonce:t.nonce,gasLimit:t.gasLimit,gasPrice:t.gasPrice})})),e.on("onTransactionConfirm",((e,t)=>{r.debug("Received transaction confirmation",{method:e,tx:t?.hash,block:t?.blockNumber,confirmations:t?.confirmations,gasUsed:t?.gasUsed,events:t?.logs??[]})}))})(i,r),o},wD=e=>{const t=e.loggerFactory.createLogger("contract");((e,t,r,n)=>{const i=n.getObserver(),s=t=>n.emit(e,t);let o;i.on("addEventListener",(r=>{r===e&&void 0===o&&(o=t(s))})),i.on("removeEventListener",(t=>{t===e&&void 0!==o&&0===n.getListenerCount(e)&&(r(o),o=void 0)})),n.getListenerCount(e)>0&&(o=t(s))})(e.targetName,(r=>{const n=(n,i)=>{let s;try{s=e.transformation(n,i)}catch(r){return void t.error("Skip emit event",{eventName:e.targetName,reason:r?.message})}r(s)};return e.sourceEmitter.on({onEvent:n,...e.sourceDefinition}),n}),(t=>{e.sourceEmitter.off({onEvent:t,...e.sourceDefinition})}),e.targetEmitter)};var vD=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},ED=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},AD=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let SD=class{config;eventEmitter;loggerFactory;constructor(e,t,r){this.config=e,this.eventEmitter=t,this.loggerFactory=r}createReadContract(e,t,r,n){return bD(new JN(e,t,r),n,this.loggerFactory,this.config.contracts.maxConcurrentCalls)}createWriteContract(e,t,r,n){const i=bD(new JN(e,t,r),n,this.loggerFactory,999999);return i.eventEmitter.on("onTransactionConfirm",((e,t)=>{this.eventEmitter.emit("contractTransactionConfirmed",{methodName:e,receipt:t})})),i}createEventContract(e,t,r){return new JN(e,t,r)}};SD=vD([q(d.ContainerScoped),AD(0,U(cA)),ED("design:paramtypes",[Object,sD,uD])],SD);var kD=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},RD=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},CD=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let ID=class{nodeRegistryContract;nodeRegistryContractReadonly;contractFactory;rpcProviderSource;config;identity;constructor(e,t,r,n){this.contractFactory=e,this.rpcProviderSource=t,this.config=r,this.identity=n,this.nodeRegistryContractReadonly=this.contractFactory.createReadContract(nb(this.config.contracts.storageNodeRegistryChainAddress),SA.NodeRegistryABI,t.getProvider(),"storageNodeRegistry")}async connectToContract(){if(void 0===this.nodeRegistryContract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.nodeRegistryContract=this.contractFactory.createWriteContract(nb(this.config.contracts.storageNodeRegistryChainAddress),SA.NodeRegistryABI,e,"storageNodeRegistry")}}async setStorageNodeMetadata(e){await this.connectToContract();const t=await nD(this.rpcProviderSource,this.config);void 0!==e?await mD(this.nodeRegistryContract.createOrUpdateNodeSelf(JSON.stringify(e),t)):await mD(this.nodeRegistryContract.removeNodeSelf(t))}async getStorageNodeMetadata(e){const[t,r]=await this.nodeRegistryContractReadonly.getNode(e);if("0x0000000000000000000000000000000000000000"!==t)return JSON.parse(r);throw new uA("Node not found, id: "+e,"NODE_NOT_FOUND")}};var PD,TD,_D,ND,MD,xD,OD,DD,BD,LD,FD,UD,jD,qD,zD,KD,GD,VD,HD,$D,WD,JD,QD,ZD,YD,XD,eB,tB,rB,nB,iB,sB,oB,aB,cB,uB,lB,hB,dB,fB,pB,gB,mB,yB,bB,wB,vB,EB,AB,SB,kB,RB,CB,IB,PB,TB,_B,NB,MB,xB,OB,DB,BB,LB,FB,UB,jB,qB,zB,KB;function GB(){if(ND)return _D;ND=1;var e=Vc(),t=(TD||(TD=1,PD=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}),PD),r=Zc();return _D=function(n,i,s,o,a,c){var u=1&s,l=n.length,h=i.length;if(l!=h&&!(u&&h>l))return!1;var d=c.get(n),f=c.get(i);if(d&&f)return d==i&&f==n;var p=-1,g=!0,m=2&s?new e:void 0;for(c.set(n,i),c.set(i,n);++p<l;){var y=n[p],b=i[p];if(o)var w=u?o(b,y,p,i,n,c):o(y,b,p,n,i,c);if(void 0!==w){if(w)continue;g=!1;break}if(m){if(!t(i,(function(e,t){if(!r(m,t)&&(y===e||a(y,e,s,o,c)))return m.push(t)}))){g=!1;break}}else if(y!==b&&!a(y,b,s,o,c)){g=!1;break}}return c.delete(n),c.delete(i),g},_D}function VB(){if(DD)return OD;return DD=1,OD=function(e){var t=-1,r=Array(e.size);return e.forEach((function(e){r[++t]=e})),r},OD}function HB(){if(LD)return BD;LD=1;var e=Oe(),t=Ch(),r=Uc(),n=GB(),i=(xD||(xD=1,MD=function(e){var t=-1,r=Array(e.size);return e.forEach((function(e,n){r[++t]=[n,e]})),r}),MD),s=VB(),o=e?e.prototype:void 0,a=o?o.valueOf:void 0;return BD=function(e,o,c,u,l,h,d){switch(c){case"[object DataView]":if(e.byteLength!=o.byteLength||e.byteOffset!=o.byteOffset)return!1;e=e.buffer,o=o.buffer;case"[object ArrayBuffer]":return!(e.byteLength!=o.byteLength||!h(new t(e),new t(o)));case"[object Boolean]":case"[object Date]":case"[object Number]":return r(+e,+o);case"[object Error]":return e.name==o.name&&e.message==o.message;case"[object RegExp]":case"[object String]":return e==o+"";case"[object Map]":var f=i;case"[object Set]":var p=1&u;if(f||(f=s),e.size!=o.size&&!p)return!1;var g=d.get(e);if(g)return g==o;u|=2,d.set(e,o);var m=n(f(e),f(o),u,l,h,d);return d.delete(e),m;case"[object Symbol]":if(a)return a.call(e)==a.call(o)}return!1},BD}function $B(){if(UD)return FD;return UD=1,FD=function(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e},FD}function WB(){if(qD)return jD;qD=1;var e=$B(),t=qu();return jD=function(r,n,i){var s=n(r);return t(r)?s:e(s,i(r))},jD}function JB(){if(VD)return GD;return VD=1,GD=function(){return[]}}function QB(){if($D)return HD;$D=1;var e=(KD||(KD=1,zD=function(e,t){for(var r=-1,n=null==e?0:e.length,i=0,s=[];++r<n;){var o=e[r];t(o,r,e)&&(s[i++]=o)}return s}),zD),t=JB(),r=Object.prototype.propertyIsEnumerable,n=Object.getOwnPropertySymbols,i=n?function(t){return null==t?[]:(t=Object(t),e(n(t),(function(e){return r.call(t,e)})))}:t;return HD=i}function ZB(){if(JD)return WD;JD=1;var e=WB(),t=QB(),r=rA();return WD=function(n){return e(n,r,t)},WD}function YB(){if(nB)return rB;nB=1;var e=Bc()(xe(),"Set");return rB=e}function XB(){if(aB)return oB;aB=1;var e=function(){if(XD)return YD;XD=1;var e=Bc()(xe(),"DataView");return YD=e}(),t=zc(),r=function(){if(tB)return eB;tB=1;var e=Bc()(xe(),"Promise");return eB=e}(),n=YB(),i=function(){if(sB)return iB;sB=1;var e=Bc()(xe(),"WeakMap");return iB=e}(),s=De(),o=Dc(),a="[object Map]",c="[object Promise]",u="[object Set]",l="[object WeakMap]",h="[object DataView]",d=o(e),f=o(t),p=o(r),g=o(n),m=o(i),y=s;return(e&&y(new e(new ArrayBuffer(1)))!=h||t&&y(new t)!=a||r&&y(r.resolve())!=c||n&&y(new n)!=u||i&&y(new i)!=l)&&(y=function(e){var t=s(e),r="[object Object]"==t?e.constructor:void 0,n=r?o(r):"";if(n)switch(n){case d:return h;case f:return a;case p:return c;case g:return u;case m:return l}return t}),oB=y}function eL(){if(uB)return cB;uB=1;var e=Yl(),t=GB(),r=HB(),n=function(){if(ZD)return QD;ZD=1;var e=ZB(),t=Object.prototype.hasOwnProperty;return QD=function(r,n,i,s,o,a){var c=1&i,u=e(r),l=u.length;if(l!=e(n).length&&!c)return!1;for(var h=l;h--;){var d=u[h];if(!(c?d in n:t.call(n,d)))return!1}var f=a.get(r),p=a.get(n);if(f&&p)return f==n&&p==r;var g=!0;a.set(r,n),a.set(n,r);for(var m=c;++h<l;){var y=r[d=u[h]],b=n[d];if(s)var w=c?s(b,y,d,n,r,a):s(y,b,d,r,n,a);if(!(void 0===w?y===b||o(y,b,i,s,a):w)){g=!1;break}m||(m="constructor"==d)}if(g&&!m){var v=r.constructor,E=n.constructor;v==E||!("constructor"in r)||!("constructor"in n)||"function"==typeof v&&v instanceof v&&"function"==typeof E&&E instanceof E||(g=!1)}return a.delete(r),a.delete(n),g},QD}(),i=XB(),s=qu(),o=Kh(),a=Ad(),c="[object Arguments]",u="[object Array]",l="[object Object]",h=Object.prototype.hasOwnProperty;return cB=function(d,f,p,g,m,y){var b=s(d),w=s(f),v=b?u:i(d),E=w?u:i(f),A=(v=v==c?l:v)==l,S=(E=E==c?l:E)==l,k=v==E;if(k&&o(d)){if(!o(f))return!1;b=!0,A=!1}if(k&&!A)return y||(y=new e),b||a(d)?t(d,f,p,g,m,y):r(d,f,v,p,g,m,y);if(!(1&p)){var R=A&&h.call(d,"__wrapped__"),C=S&&h.call(f,"__wrapped__");if(R||C){var I=R?d.value():d,P=C?f.value():f;return y||(y=new e),m(I,P,p,g,y)}}return!!k&&(y||(y=new e),n(d,f,p,g,m,y))},cB}function tL(){if(hB)return lB;hB=1;var e=eL(),t=Be();return lB=function r(n,i,s,o,a){return n===i||(null==n||null==i||!t(n)&&!t(i)?n!=n&&i!=i:e(n,i,s,o,r,a))},lB}function rL(){if(gB)return pB;gB=1;var e=Ne();return pB=function(t){return t==t&&!e(t)}}function nL(){if(wB)return bB;return wB=1,bB=function(e,t){return function(r){return null!=r&&(r[e]===t&&(void 0!==t||e in Object(r)))}},bB}function iL(){if(EB)return vB;EB=1;var e=function(){if(fB)return dB;fB=1;var e=Yl(),t=tL();return dB=function(r,n,i,s){var o=i.length,a=o,c=!s;if(null==r)return!a;for(r=Object(r);o--;){var u=i[o];if(c&&u[2]?u[1]!==r[u[0]]:!(u[0]in r))return!1}for(;++o<a;){var l=(u=i[o])[0],h=r[l],d=u[1];if(c&&u[2]){if(void 0===h&&!(l in r))return!1}else{var f=new e;if(s)var p=s(h,d,l,r,n,f);if(!(void 0===p?t(d,h,3,s,f):p))return!1}}return!0},dB}(),t=function(){if(yB)return mB;yB=1;var e=rL(),t=rA();return mB=function(r){for(var n=t(r),i=n.length;i--;){var s=n[i],o=r[s];n[i]=[s,o,e(o)]}return n},mB}(),r=nL();return vB=function(n){var i=t(n);return 1==i.length&&i[0][2]?r(i[0][0],i[0][1]):function(t){return t===n||e(t,n,i)}},vB}function sL(){if(SB)return AB;SB=1;var e=Pl(),t=_l();return AB=function(r,n){for(var i=0,s=(n=e(n,r)).length;null!=r&&i<s;)r=r[t(n[i++])];return i&&i==s?r:void 0},AB}function oL(){if(NB)return _B;NB=1;var e=(IB||(IB=1,CB=function(e,t){return null!=e&&t in Object(e)}),CB),t=function(){if(TB)return PB;TB=1;var e=Pl(),t=Oh(),r=qu(),n=Tl(),i=iu(),s=_l();return PB=function(o,a,c){for(var u=-1,l=(a=e(a,o)).length,h=!1;++u<l;){var d=s(a[u]);if(!(h=null!=o&&c(o,d)))break;o=o[d]}return h||++u!=l?h:!!(l=null==o?0:o.length)&&i(l)&&n(d,l)&&(r(o)||t(o))},PB}();return _B=function(r,n){return null!=r&&t(r,n,e)},_B}function aL(){if(xB)return MB;xB=1;var e=tL(),t=function(){if(RB)return kB;RB=1;var e=sL();return kB=function(t,r,n){var i=null==t?void 0:e(t,r);return void 0===i?n:i},kB}(),r=oL(),n=Cl(),i=rL(),s=nL(),o=_l();return MB=function(a,c){return n(a)&&i(c)?s(o(a),c):function(n){var i=t(n,a);return void 0===i&&i===c?r(n,a):e(c,i,3)}},MB}function cL(){if(LB)return BB;LB=1;var e=Vu(),t=function(){if(DB)return OB;DB=1;var e=sL();return OB=function(t){return function(r){return e(r,t)}},OB}(),r=Cl(),n=_l();return BB=function(i){return r(i)?e(n(i)):t(i)},BB}function uL(){if(UB)return FB;UB=1;var e=iL(),t=aL(),r=Yc(),n=qu(),i=cL();return FB=function(s){return"function"==typeof s?s:null==s?r:"object"==typeof s?n(s)?t(s[0],s[1]):e(s):i(s)}}ID=kD([q(d.ContainerScoped),CD(2,U(cA)),CD(3,U(kA)),RD("design:paramtypes",[SD,e.RpcProviderSource,Object,RA])],ID);var lL,hL,dL,fL=function(){if(KB)return zB;KB=1;var e=uL(),t=function(){if(qB)return jB;qB=1;var e=Le(),t=Math.floor,r=Math.min;return jB=function(n,i,s,o){var a=0,c=null==n?0:n.length;if(0===c)return 0;for(var u=(i=s(i))!=i,l=null===i,h=e(i),d=void 0===i;a<c;){var f=t((a+c)/2),p=s(n[f]),g=void 0!==p,m=null===p,y=p==p,b=e(p);if(u)var w=o||y;else w=d?y&&(o||g):l?y&&g&&(o||!m):h?y&&g&&!m&&(o||!b):!m&&!b&&(o?p<=i:p<i);w?a=f+1:c=f}return r(c,4294967294)},jB}();return zB=function(r,n,i){return t(r,n,e(i,2))},zB}(),pL=n(fL),gL={exports:{}};var mL=function(){if(dL)return hL;dL=1;const e=function(){if(lL)return gL.exports;lL=1;var e=65536,t=4294967295,n=We().Buffer,i=r.crypto||r.msCrypto;return i&&i.getRandomValues?gL.exports=function(r,s){if(r>t)throw new RangeError("requested too many random bytes");var o=n.allocUnsafe(r);if(r>0)if(r>e)for(var a=0;a<r;a+=e)i.getRandomValues(o.slice(a,a+e));else i.getRandomValues(o);return"function"==typeof s?process.nextTick((function(){s(null,o)})):o}:gL.exports=function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")},gL.exports}(),{EventEmitter:t}=pt();function n(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0,n=e.length;r<n;++r)if(e[r]!==t[r])return!1;return!0}function i(e,t){if(!(t instanceof Uint8Array))throw new TypeError(e+" is not a Uint8Array")}class s extends t{constructor(t={}){super(),this.localNodeId=t.localNodeId||e(20),this.numberOfNodesPerKBucket=t.numberOfNodesPerKBucket||20,this.numberOfNodesToPing=t.numberOfNodesToPing||3,this.distance=t.distance||s.distance,this.arbiter=t.arbiter||s.arbiter,this.metadata=Object.assign({},t.metadata),i("option.localNodeId as parameter 1",this.localNodeId),this.root={contacts:[],dontSplit:!1,left:null,right:null}}static arbiter(e,t){return e.vectorClock>t.vectorClock?e:t}static distance(e,t){let r=0,n=0;const i=Math.min(e.length,t.length),s=Math.max(e.length,t.length);for(;n<i;++n)r=256*r+(e[n]^t[n]);for(;n<s;++n)r=256*r+255;return r}add(e){i("contact.id",(e||{}).id);let t=0,r=this.root;for(;null===r.contacts;)r=this._determineNode(r,e.id,t++);const n=this._indexOf(r,e.id);return n>=0?(this._update(r,n,e),this):r.contacts.length<this.numberOfNodesPerKBucket?(r.contacts.push(e),this.emit("added",e),this):r.dontSplit?(this.emit("ping",r.contacts.slice(0,this.numberOfNodesToPing),e),this):(this._split(r,t),this.add(e))}closest(e,t=1/0){if(i("id",e),!Number.isInteger(t)&&t!==1/0||t<=0)throw new TypeError("n is not positive number");let r=[];for(let n=[this.root],i=0;n.length>0&&r.length<t;){const t=n.pop();if(null===t.contacts){const r=this._determineNode(t,e,i++);n.push(t.left===r?t.right:t.left),n.push(r)}else r=r.concat(t.contacts)}return r.map((t=>[this.distance(t.id,e),t])).sort(((e,t)=>e[0]-t[0])).slice(0,t).map((e=>e[1]))}count(){let e=0;for(const t=[this.root];t.length>0;){const r=t.pop();null===r.contacts?t.push(r.right,r.left):e+=r.contacts.length}return e}_determineNode(e,t,r){const n=r>>3,i=r%8;if(t.length<=n&&0!==i)return e.left;return t[n]&1<<7-i?e.right:e.left}get(e){i("id",e);let t=0,r=this.root;for(;null===r.contacts;)r=this._determineNode(r,e,t++);const n=this._indexOf(r,e);return n>=0?r.contacts[n]:null}_indexOf(e,t){for(let r=0;r<e.contacts.length;++r)if(n(e.contacts[r].id,t))return r;return-1}remove(e){i("the id as parameter 1",e);let t=0,r=this.root;for(;null===r.contacts;)r=this._determineNode(r,e,t++);const n=this._indexOf(r,e);if(n>=0){const e=r.contacts.splice(n,1)[0];this.emit("removed",e)}return this}_split(e,t){e.left={contacts:[],dontSplit:!1,left:null,right:null},e.right={contacts:[],dontSplit:!1,left:null,right:null};for(const r of e.contacts)this._determineNode(e,r.id,t).contacts.push(r);e.contacts=null;const r=this._determineNode(e,this.localNodeId,t);(e.left===r?e.right:e.left).dontSplit=!0}toArray(){let e=[];for(const t=[this.root];t.length>0;){const r=t.pop();null===r.contacts?t.push(r.right,r.left):e=e.concat(r.contacts)}return e}*toIterable(){for(const e=[this.root];e.length>0;){const t=e.pop();null===t.contacts?e.push(t.right,t.left):yield*t.contacts}}_update(e,t,r){if(!n(e.contacts[t].id,r.id))throw new Error("wrong index for _update");const i=e.contacts[t],s=this.arbiter(i,r);s===i&&i!==r||(e.contacts.splice(t,1),e.contacts.push(s),this.emit("updated",i,s))}}return hL=s}(),yL=n(mL);function bL(e){let t=typeof e;if("object"==t){if(Array.isArray(e))return"array";if(null===e)return"null"}return t}function wL(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let vL="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),EL=[];for(let e=0;e<vL.length;e++)EL[vL[e].charCodeAt(0)]=e;var AL,SL;function kL(e,t){return Object.assign(Object.assign({},e),t)}function RL(){let e=0,t=0;for(let r=0;r<28;r+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<r,!(128&n))return this.assertBounds(),[e,t]}let r=this.buf[this.pos++];if(e|=(15&r)<<28,t=(112&r)>>4,!(128&r))return this.assertBounds(),[e,t];for(let r=3;r<=31;r+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<r,!(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function CL(e,t,r){for(let n=0;n<28;n+=7){const i=e>>>n,s=!(i>>>7==0&&0==t),o=255&(s?128|i:i);if(r.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,i=!!(t>>3);if(r.push(255&(i?128|n:n)),i){for(let e=3;e<31;e+=7){const n=t>>>e,i=!(n>>>7==0),s=255&(i?128|n:n);if(r.push(s),!i)return}r.push(t>>>31&1)}}EL["-".charCodeAt(0)]=vL.indexOf("+"),EL["_".charCodeAt(0)]=vL.indexOf("/"),function(e){e.symbol=Symbol.for("protobuf-ts/unknown"),e.onRead=(r,n,i,s,o)=>{(t(n)?n[e.symbol]:n[e.symbol]=[]).push({no:i,wireType:s,data:o})},e.onWrite=(t,r,n)=>{for(let{no:t,wireType:i,data:s}of e.list(r))n.tag(t,i).raw(s)},e.list=(r,n)=>{if(t(r)){let t=r[e.symbol];return n?t.filter((e=>e.no==n)):t}return[]},e.last=(t,r)=>e.list(t,r).slice(-1)[0];const t=t=>t&&Array.isArray(t[e.symbol])}(AL||(AL={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(SL||(SL={}));const IL=4294967296;function PL(e){let t="-"==e[0];t&&(e=e.slice(1));const r=1e6;let n=0,i=0;function s(t,s){const o=Number(e.slice(t,s));i*=r,n=n*r+o,n>=IL&&(i+=n/IL|0,n%=IL)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[t,n,i]}function TL(e,t){if(t>>>0<=2097151)return""+(IL*t+(e>>>0));let r=(e>>>24|t<<8)>>>0&16777215,n=t>>16&65535,i=(16777215&e)+6777216*r+6710656*n,s=r+8147497*n,o=2*n,a=1e7;function c(e,t){let r=e?String(e):"";return t?"0000000".slice(r.length)+r:r}return i>=a&&(s+=Math.floor(i/a),i%=a),s>=a&&(o+=Math.floor(s/a),s%=a),c(o,0)+c(s,o)+c(i,1)}function _L(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let r=0;r<9;r++)t.push(127&e|128),e>>=7;t.push(1)}}function NL(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let ML;function xL(e){if(!e)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}!function(){const e=new DataView(new ArrayBuffer(8)),t=void 0!==globalThis.BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64;ML=t?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:e}:void 0}();const OL=/^-?[0-9]+$/,DL=4294967296,BL=2147483648;class LL{constructor(e,t){this.lo=0|e,this.hi=0|t}isZero(){return 0==this.lo&&0==this.hi}toNumber(){let e=this.hi*DL+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class FL extends LL{static from(e){if(ML)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=ML.C(e);case"number":if(0===e)return this.ZERO;e=ML.C(e);case"bigint":if(!e)return this.ZERO;if(e<ML.UMIN)throw new Error("signed value for ulong");if(e>ML.UMAX)throw new Error("ulong too large");return ML.V.setBigUint64(0,e,!0),new FL(ML.V.getInt32(0,!0),ML.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!OL.test(e))throw new Error("string is no integer");let[t,r,n]=PL(e);if(t)throw new Error("signed value for ulong");return new FL(r,n);case"number":if(0==e)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new FL(e,e/DL)}throw new Error("unknown value "+typeof e)}toString(){return ML?this.toBigInt().toString():TL(this.lo,this.hi)}toBigInt(){return xL(ML),ML.V.setInt32(0,this.lo,!0),ML.V.setInt32(4,this.hi,!0),ML.V.getBigUint64(0,!0)}}FL.ZERO=new FL(0,0);class UL extends LL{static from(e){if(ML)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=ML.C(e);case"number":if(0===e)return this.ZERO;e=ML.C(e);case"bigint":if(!e)return this.ZERO;if(e<ML.MIN)throw new Error("signed long too small");if(e>ML.MAX)throw new Error("signed long too large");return ML.V.setBigInt64(0,e,!0),new UL(ML.V.getInt32(0,!0),ML.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!OL.test(e))throw new Error("string is no integer");let[t,r,n]=PL(e);if(t){if(n>BL||n==BL&&0!=r)throw new Error("signed long too small")}else if(n>=BL)throw new Error("signed long too large");let i=new UL(r,n);return t?i.negate():i;case"number":if(0==e)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new UL(e,e/DL):new UL(-e,-e/DL).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return!!(this.hi&BL)}negate(){let e=~this.hi,t=this.lo;return t?t=1+~t:e+=1,new UL(t,e)}toString(){if(ML)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+TL(e.lo,e.hi)}return TL(this.lo,this.hi)}toBigInt(){return xL(ML),ML.V.setInt32(0,this.lo,!0),ML.V.setInt32(4,this.hi,!0),ML.V.getBigInt64(0,!0)}}UL.ZERO=new UL(0,0);const jL={readUnknownField:!0,readerFactory:e=>new qL(e)};class qL{constructor(e,t){this.varint64=RL,this.uint32=NL,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),t=e>>>3,r=7&e;if(t<=0||r<0||r>5)throw new Error("illegal tag: field no "+t+" wire type "+r);return[t,r]}skip(e){let t=this.pos;switch(e){case SL.Varint:for(;128&this.buf[this.pos++];);break;case SL.Bit64:this.pos+=4;case SL.Bit32:this.pos+=4;break;case SL.LengthDelimited:let t=this.uint32();this.pos+=t;break;case SL.StartGroup:let r;for(;(r=this.tag()[1])!==SL.EndGroup;)this.skip(r);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return new UL(...this.varint64())}uint64(){return new FL(...this.varint64())}sint64(){let[e,t]=this.varint64(),r=-(1&e);return e=(e>>>1|(1&t)<<31)^r,t=t>>>1^r,new UL(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new FL(this.sfixed32(),this.sfixed32())}sfixed64(){return new UL(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function zL(e,t){if(!e)throw new Error(t)}function KL(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function GL(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function VL(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const HL={writeUnknownFields:!0,writerFactory:()=>new $L};class $L{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),r=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],r),r+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(GL(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return KL(e),_L(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){VL(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){GL(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){KL(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return KL(e),_L(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=UL.from(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=FL.from(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=UL.from(e);return CL(t.lo,t.hi,this.buf),this}sint64(e){let t=UL.from(e),r=t.hi>>31;return CL(t.lo<<1^r,(t.hi<<1|t.lo>>>31)^r,this.buf),this}uint64(e){let t=FL.from(e);return CL(t.lo,t.hi,this.buf),this}}const WL={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},JL={ignoreUnknownFields:!1};function QL(e){return e?Object.assign(Object.assign({},WL),e):WL}function ZL(e,t){var r,n;let i=Object.assign(Object.assign({},e),t);return i.typeRegistry=[...null!==(r=null==e?void 0:e.typeRegistry)&&void 0!==r?r:[],...null!==(n=null==t?void 0:t.typeRegistry)&&void 0!==n?n:[]],i}const YL=Symbol.for("protobuf-ts/message-type");function XL(e){let t=!1;const r=[];for(let n=0;n<e.length;n++){let i=e.charAt(n);"_"==i?t=!0:/\d/.test(i)?(r.push(i),t=!0):t?(r.push(i.toUpperCase()),t=!1):0==n?r.push(i.toLowerCase()):r.push(i)}return r.join("")}var eF,tF,rF;function nF(e){var t,r,n,i;return e.localName=null!==(t=e.localName)&&void 0!==t?t:XL(e.name),e.jsonName=null!==(r=e.jsonName)&&void 0!==r?r:XL(e.name),e.repeat=null!==(n=e.repeat)&&void 0!==n?n:rF.NO,e.opt=null!==(i=e.opt)&&void 0!==i?i:!e.repeat&&(!e.oneof&&"message"==e.kind),e}function iF(e){if("object"!=typeof e||null===e||!e.hasOwnProperty("oneofKind"))return!1;switch(typeof e.oneofKind){case"string":return void 0!==e[e.oneofKind]&&2==Object.keys(e).length;case"undefined":return 1==Object.keys(e).length;default:return!1}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(eF||(eF={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING",e[e.NUMBER=2]="NUMBER"}(tF||(tF={})),function(e){e[e.NO=0]="NO",e[e.PACKED=1]="PACKED",e[e.UNPACKED=2]="UNPACKED"}(rF||(rF={}));class sF{constructor(e){var t;this.fields=null!==(t=e.fields)&&void 0!==t?t:[]}prepare(){if(this.data)return;const e=[],t=[],r=[];for(let n of this.fields)if(n.oneof)r.includes(n.oneof)||(r.push(n.oneof),e.push(n.oneof),t.push(n.oneof));else switch(t.push(n.localName),n.kind){case"scalar":case"enum":n.opt&&!n.repeat||e.push(n.localName);break;case"message":n.repeat&&e.push(n.localName);break;case"map":e.push(n.localName)}this.data={req:e,known:t,oneofs:Object.values(r)}}is(e,t,r=!1){if(t<0)return!0;if(null==e||"object"!=typeof e)return!1;this.prepare();let n=Object.keys(e),i=this.data;if(n.length<i.req.length||i.req.some((e=>!n.includes(e))))return!1;if(!r&&n.some((e=>!i.known.includes(e))))return!1;if(t<1)return!0;for(const n of i.oneofs){const i=e[n];if(!iF(i))return!1;if(void 0===i.oneofKind)continue;const s=this.fields.find((e=>e.localName===i.oneofKind));if(!s)return!1;if(!this.field(i[i.oneofKind],s,r,t))return!1}for(const n of this.fields)if(void 0===n.oneof&&!this.field(e[n.localName],n,r,t))return!1;return!0}field(e,t,r,n){let i=t.repeat;switch(t.kind){case"scalar":return void 0===e?t.opt:i?this.scalars(e,t.T,n,t.L):this.scalar(e,t.T,t.L);case"enum":return void 0===e?t.opt:i?this.scalars(e,eF.INT32,n):this.scalar(e,eF.INT32);case"message":return void 0===e||(i?this.messages(e,t.T(),r,n):this.message(e,t.T(),r,n));case"map":if("object"!=typeof e||null===e)return!1;if(n<2)return!0;if(!this.mapKeys(e,t.K,n))return!1;switch(t.V.kind){case"scalar":return this.scalars(Object.values(e),t.V.T,n,t.V.L);case"enum":return this.scalars(Object.values(e),eF.INT32,n);case"message":return this.messages(Object.values(e),t.V.T(),r,n)}}return!0}message(e,t,r,n){return r?t.isAssignable(e,n):t.is(e,n)}messages(e,t,r,n){if(!Array.isArray(e))return!1;if(n<2)return!0;if(r){for(let r=0;r<e.length&&r<n;r++)if(!t.isAssignable(e[r],n-1))return!1}else for(let r=0;r<e.length&&r<n;r++)if(!t.is(e[r],n-1))return!1;return!0}scalar(e,t,r){let n=typeof e;switch(t){case eF.UINT64:case eF.FIXED64:case eF.INT64:case eF.SFIXED64:case eF.SINT64:switch(r){case tF.BIGINT:return"bigint"==n;case tF.NUMBER:return"number"==n&&!isNaN(e);default:return"string"==n}case eF.BOOL:return"boolean"==n;case eF.STRING:return"string"==n;case eF.BYTES:return e instanceof Uint8Array;case eF.DOUBLE:case eF.FLOAT:return"number"==n&&!isNaN(e);default:return"number"==n&&Number.isInteger(e)}}scalars(e,t,r,n){if(!Array.isArray(e))return!1;if(r<2)return!0;if(Array.isArray(e))for(let i=0;i<e.length&&i<r;i++)if(!this.scalar(e[i],t,n))return!1;return!0}mapKeys(e,t,r){let n=Object.keys(e);switch(t){case eF.INT32:case eF.FIXED32:case eF.SFIXED32:case eF.SINT32:case eF.UINT32:return this.scalars(n.slice(0,r).map((e=>parseInt(e))),t,r);case eF.BOOL:return this.scalars(n.slice(0,r).map((e=>"true"==e||"false"!=e&&e)),t,r);default:return this.scalars(n,t,r,tF.STRING)}}}function oF(e,t){switch(t){case tF.BIGINT:return e.toBigInt();case tF.NUMBER:return e.toNumber();default:return e.toString()}}class aF{constructor(e){this.info=e}prepare(){var e;if(void 0===this.fMap){this.fMap={};const t=null!==(e=this.info.fields)&&void 0!==e?e:[];for(const e of t)this.fMap[e.name]=e,this.fMap[e.jsonName]=e,this.fMap[e.localName]=e}}assert(e,t,r){if(!e){let e=bL(r);throw"number"!=e&&"boolean"!=e||(e=r.toString()),new Error(`Cannot parse JSON ${e} for ${this.info.typeName}#${t}`)}}read(e,t,r){this.prepare();const n=[];for(const[i,s]of Object.entries(e)){const e=this.fMap[i];if(!e){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${i}`);continue}const o=e.localName;let a;if(e.oneof){if(null===s&&("enum"!==e.kind||"google.protobuf.NullValue"!==e.T()[0]))continue;if(n.includes(e.oneof))throw new Error(`Multiple members of the oneof group "${e.oneof}" of ${this.info.typeName} are present in JSON.`);n.push(e.oneof),a=t[e.oneof]={oneofKind:o}}else a=t;if("map"==e.kind){if(null===s)continue;this.assert(wL(s),e.name,s);const t=a[o];for(const[n,i]of Object.entries(s)){let s;switch(this.assert(null!==i,e.name+" map value",null),e.V.kind){case"message":s=e.V.T().internalJsonRead(i,r);break;case"enum":if(s=this.enum(e.V.T(),i,e.name,r.ignoreUnknownFields),!1===s)continue;break;case"scalar":s=this.scalar(i,e.V.T,e.V.L,e.name)}this.assert(void 0!==s,e.name+" map value",i);let o=n;e.K==eF.BOOL&&(o="true"==o||"false"!=o&&o),o=this.scalar(o,e.K,tF.STRING,e.name).toString(),t[o]=s}}else if(e.repeat){if(null===s)continue;this.assert(Array.isArray(s),e.name,s);const t=a[o];for(const n of s){let i;switch(this.assert(null!==n,e.name,null),e.kind){case"message":i=e.T().internalJsonRead(n,r);break;case"enum":if(i=this.enum(e.T(),n,e.name,r.ignoreUnknownFields),!1===i)continue;break;case"scalar":i=this.scalar(n,e.T,e.L,e.name)}this.assert(void 0!==i,e.name,s),t.push(i)}}else switch(e.kind){case"message":if(null===s&&"google.protobuf.Value"!=e.T().typeName){this.assert(void 0===e.oneof,e.name+" (oneof member)",null);continue}a[o]=e.T().internalJsonRead(s,r,a[o]);break;case"enum":if(null===s)continue;let t=this.enum(e.T(),s,e.name,r.ignoreUnknownFields);if(!1===t)continue;a[o]=t;break;case"scalar":if(null===s)continue;a[o]=this.scalar(s,e.T,e.L,e.name)}}}enum(e,t,r,n){if("google.protobuf.NullValue"==e[0]&&zL(null===t||"NULL_VALUE"===t,`Unable to parse field ${this.info.typeName}#${r}, enum ${e[0]} only accepts null.`),null===t)return 0;switch(typeof t){case"number":return zL(Number.isInteger(t),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${t}.`),t;case"string":let i=t;e[2]&&t.substring(0,e[2].length)===e[2]&&(i=t.substring(e[2].length));let s=e[1][i];return(void 0!==s||!n)&&(zL("number"==typeof s,`Unable to parse field ${this.info.typeName}#${r}, enum ${e[0]} has no value for "${t}".`),s)}zL(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof t}".`)}scalar(e,t,r,n){let i;try{switch(t){case eF.DOUBLE:case eF.FLOAT:if(null===e)return 0;if("NaN"===e)return Number.NaN;if("Infinity"===e)return Number.POSITIVE_INFINITY;if("-Infinity"===e)return Number.NEGATIVE_INFINITY;if(""===e){i="empty string";break}if("string"==typeof e&&e.trim().length!==e.length){i="extra whitespace";break}if("string"!=typeof e&&"number"!=typeof e)break;let n=Number(e);if(Number.isNaN(n)){i="not a number";break}if(!Number.isFinite(n)){i="too large or small";break}return t==eF.FLOAT&&VL(n),n;case eF.INT32:case eF.FIXED32:case eF.SFIXED32:case eF.SINT32:case eF.UINT32:if(null===e)return 0;let s;if("number"==typeof e?s=e:""===e?i="empty string":"string"==typeof e&&(e.trim().length!==e.length?i="extra whitespace":s=Number(e)),void 0===s)break;return t==eF.UINT32?GL(s):KL(s),s;case eF.INT64:case eF.SFIXED64:case eF.SINT64:if(null===e)return oF(UL.ZERO,r);if("number"!=typeof e&&"string"!=typeof e)break;return oF(UL.from(e),r);case eF.FIXED64:case eF.UINT64:if(null===e)return oF(FL.ZERO,r);if("number"!=typeof e&&"string"!=typeof e)break;return oF(FL.from(e),r);case eF.BOOL:if(null===e)return!1;if("boolean"!=typeof e)break;return e;case eF.STRING:if(null===e)return"";if("string"!=typeof e){i="extra whitespace";break}try{encodeURIComponent(e)}catch(i){i="invalid UTF8";break}return e;case eF.BYTES:if(null===e||""===e)return new Uint8Array(0);if("string"!=typeof e)break;return function(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let r,n=new Uint8Array(t),i=0,s=0,o=0;for(let t=0;t<e.length;t++){if(r=EL[e.charCodeAt(t)],void 0===r)switch(e[t]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:n[i++]=o<<2|(48&r)>>4,o=r,s=2;break;case 2:n[i++]=(15&o)<<4|(60&r)>>2,o=r,s=3;break;case 3:n[i++]=(3&o)<<6|r,s=0}}if(1==s)throw Error("invalid base64 string.");return n.subarray(0,i)}(e)}}catch(e){i=e.message}this.assert(!1,n+(i?" - "+i:""),e)}}class cF{constructor(e){var t;this.fields=null!==(t=e.fields)&&void 0!==t?t:[]}write(e,t){const r={},n=e;for(const e of this.fields){if(!e.oneof){let i=this.field(e,n[e.localName],t);void 0!==i&&(r[t.useProtoFieldName?e.name:e.jsonName]=i);continue}const i=n[e.oneof];if(i.oneofKind!==e.localName)continue;const s="scalar"==e.kind||"enum"==e.kind?Object.assign(Object.assign({},t),{emitDefaultValues:!0}):t;let o=this.field(e,i[e.localName],s);zL(void 0!==o),r[t.useProtoFieldName?e.name:e.jsonName]=o}return r}field(e,t,r){let n;if("map"==e.kind){zL("object"==typeof t&&null!==t);const i={};switch(e.V.kind){case"scalar":for(const[r,n]of Object.entries(t)){const t=this.scalar(e.V.T,n,e.name,!1,!0);zL(void 0!==t),i[r.toString()]=t}break;case"message":const n=e.V.T();for(const[s,o]of Object.entries(t)){const t=this.message(n,o,e.name,r);zL(void 0!==t),i[s.toString()]=t}break;case"enum":const s=e.V.T();for(const[n,o]of Object.entries(t)){zL(void 0===o||"number"==typeof o);const t=this.enum(s,o,e.name,!1,!0,r.enumAsInteger);zL(void 0!==t),i[n.toString()]=t}}(r.emitDefaultValues||Object.keys(i).length>0)&&(n=i)}else if(e.repeat){zL(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let r=0;r<t.length;r++){const n=this.scalar(e.T,t[r],e.name,e.opt,!0);zL(void 0!==n),i.push(n)}break;case"enum":const n=e.T();for(let s=0;s<t.length;s++){zL(void 0===t[s]||"number"==typeof t[s]);const o=this.enum(n,t[s],e.name,e.opt,!0,r.enumAsInteger);zL(void 0!==o),i.push(o)}break;case"message":const s=e.T();for(let n=0;n<t.length;n++){const o=this.message(s,t[n],e.name,r);zL(void 0!==o),i.push(o)}}(r.emitDefaultValues||i.length>0||r.emitDefaultValues)&&(n=i)}else switch(e.kind){case"scalar":n=this.scalar(e.T,t,e.name,e.opt,r.emitDefaultValues);break;case"enum":n=this.enum(e.T(),t,e.name,e.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":n=this.message(e.T(),t,e.name,r)}return n}enum(e,t,r,n,i,s){if("google.protobuf.NullValue"==e[0])return i||n?null:void 0;if(void 0!==t){if(0!==t||i||n)return zL("number"==typeof t),zL(Number.isInteger(t)),s||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}else zL(n)}message(e,t,r,n){return void 0===t?n.emitDefaultValues?null:void 0:e.internalJsonWrite(t,n)}scalar(e,t,r,n,i){if(void 0===t)return void zL(n);const s=i||n;switch(e){case eF.INT32:case eF.SFIXED32:case eF.SINT32:return 0===t?s?0:void 0:(KL(t),t);case eF.FIXED32:case eF.UINT32:return 0===t?s?0:void 0:(GL(t),t);case eF.FLOAT:VL(t);case eF.DOUBLE:return 0===t?s?0:void 0:(zL("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case eF.STRING:return""===t?s?"":void 0:(zL("string"==typeof t),t);case eF.BOOL:return!1===t?!s&&void 0:(zL("boolean"==typeof t),t);case eF.UINT64:case eF.FIXED64:zL("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let e=FL.from(t);if(e.isZero()&&!s)return;return e.toString();case eF.INT64:case eF.SFIXED64:case eF.SINT64:zL("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let r=UL.from(t);if(r.isZero()&&!s)return;return r.toString();case eF.BYTES:return zL(t instanceof Uint8Array),t.byteLength?function(e){let t,r="",n=0,i=0;for(let s=0;s<e.length;s++)switch(t=e[s],n){case 0:r+=vL[t>>2],i=(3&t)<<4,n=1;break;case 1:r+=vL[i|t>>4],i=(15&t)<<2,n=2;break;case 2:r+=vL[i|t>>6],r+=vL[63&t],n=0}return n&&(r+=vL[i],r+="=",1==n&&(r+="=")),r}(t):s?"":void 0}}}function uF(e,t=tF.STRING){switch(e){case eF.BOOL:return!1;case eF.UINT64:case eF.FIXED64:return oF(FL.ZERO,t);case eF.INT64:case eF.SFIXED64:case eF.SINT64:return oF(UL.ZERO,t);case eF.DOUBLE:case eF.FLOAT:return 0;case eF.BYTES:return new Uint8Array(0);case eF.STRING:return"";default:return 0}}class lF{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const t=null!==(e=this.info.fields)&&void 0!==e?e:[];this.fieldNoToField=new Map(t.map((e=>[e.no,e])))}}read(e,t,r,n){this.prepare();const i=void 0===n?e.len:e.pos+n;for(;e.pos<i;){const[n,i]=e.tag(),s=this.fieldNoToField.get(n);if(!s){let s=r.readUnknownField;if("throw"==s)throw new Error(`Unknown field ${n} (wire type ${i}) for ${this.info.typeName}`);let o=e.skip(i);!1!==s&&(!0===s?AL.onRead:s)(this.info.typeName,t,n,i,o);continue}let o=t,a=s.repeat,c=s.localName;switch(s.oneof&&(o=o[s.oneof],o.oneofKind!==c&&(o=t[s.oneof]={oneofKind:c})),s.kind){case"scalar":case"enum":let t="enum"==s.kind?eF.INT32:s.T,n="scalar"==s.kind?s.L:void 0;if(a){let r=o[c];if(i==SL.LengthDelimited&&t!=eF.STRING&&t!=eF.BYTES){let i=e.uint32()+e.pos;for(;e.pos<i;)r.push(this.scalar(e,t,n))}else r.push(this.scalar(e,t,n))}else o[c]=this.scalar(e,t,n);break;case"message":if(a){let t=o[c],n=s.T().internalBinaryRead(e,e.uint32(),r);t.push(n)}else o[c]=s.T().internalBinaryRead(e,e.uint32(),r,o[c]);break;case"map":let[u,l]=this.mapEntry(s,e,r);o[c][u]=l}}}mapEntry(e,t,r){let n,i,s=t.uint32(),o=t.pos+s;for(;t.pos<o;){let[s,o]=t.tag();switch(s){case 1:n=e.K==eF.BOOL?t.bool().toString():this.scalar(t,e.K,tF.STRING);break;case 2:switch(e.V.kind){case"scalar":i=this.scalar(t,e.V.T,e.V.L);break;case"enum":i=t.int32();break;case"message":i=e.V.T().internalBinaryRead(t,t.uint32(),r)}break;default:throw new Error(`Unknown field ${s} (wire type ${o}) in map entry for ${this.info.typeName}#${e.name}`)}}if(void 0===n){let t=uF(e.K);n=e.K==eF.BOOL?t.toString():t}if(void 0===i)switch(e.V.kind){case"scalar":i=uF(e.V.T,e.V.L);break;case"enum":i=0;break;case"message":i=e.V.T().create()}return[n,i]}scalar(e,t,r){switch(t){case eF.INT32:return e.int32();case eF.STRING:return e.string();case eF.BOOL:return e.bool();case eF.DOUBLE:return e.double();case eF.FLOAT:return e.float();case eF.INT64:return oF(e.int64(),r);case eF.UINT64:return oF(e.uint64(),r);case eF.FIXED64:return oF(e.fixed64(),r);case eF.FIXED32:return e.fixed32();case eF.BYTES:return e.bytes();case eF.UINT32:return e.uint32();case eF.SFIXED32:return e.sfixed32();case eF.SFIXED64:return oF(e.sfixed64(),r);case eF.SINT32:return e.sint32();case eF.SINT64:return oF(e.sint64(),r)}}}class hF{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort(((e,t)=>e.no-t.no))}}write(e,t,r){this.prepare();for(const n of this.fields){let i,s,o=n.repeat,a=n.localName;if(n.oneof){const t=e[n.oneof];if(t.oneofKind!==a)continue;i=t[a],s=!0}else i=e[a],s=!1;switch(n.kind){case"scalar":case"enum":let e="enum"==n.kind?eF.INT32:n.T;if(o)if(zL(Array.isArray(i)),o==rF.PACKED)this.packed(t,e,n.no,i);else for(const r of i)this.scalar(t,e,n.no,r,!0);else void 0===i?zL(n.opt):this.scalar(t,e,n.no,i,s||n.opt);break;case"message":if(o){zL(Array.isArray(i));for(const e of i)this.message(t,r,n.T(),n.no,e)}else this.message(t,r,n.T(),n.no,i);break;case"map":zL("object"==typeof i&&null!==i);for(const[e,s]of Object.entries(i))this.mapEntry(t,r,n,e,s)}}let n=r.writeUnknownFields;!1!==n&&(!0===n?AL.onWrite:n)(this.info.typeName,e,t)}mapEntry(e,t,r,n,i){e.tag(r.no,SL.LengthDelimited),e.fork();let s=n;switch(r.K){case eF.INT32:case eF.FIXED32:case eF.UINT32:case eF.SFIXED32:case eF.SINT32:s=Number.parseInt(n);break;case eF.BOOL:zL("true"==n||"false"==n),s="true"==n}switch(this.scalar(e,r.K,1,s,!0),r.V.kind){case"scalar":this.scalar(e,r.V.T,2,i,!0);break;case"enum":this.scalar(e,eF.INT32,2,i,!0);break;case"message":this.message(e,t,r.V.T(),2,i)}e.join()}message(e,t,r,n,i){void 0!==i&&(r.internalBinaryWrite(i,e.tag(n,SL.LengthDelimited).fork(),t),e.join())}scalar(e,t,r,n,i){let[s,o,a]=this.scalarInfo(t,n);a&&!i||(e.tag(r,s),e[o](n))}packed(e,t,r,n){if(!n.length)return;zL(t!==eF.BYTES&&t!==eF.STRING),e.tag(r,SL.LengthDelimited),e.fork();let[,i]=this.scalarInfo(t);for(let t=0;t<n.length;t++)e[i](n[t]);e.join()}scalarInfo(e,t){let r,n=SL.Varint,i=void 0===t,s=0===t;switch(e){case eF.INT32:r="int32";break;case eF.STRING:s=i||!t.length,n=SL.LengthDelimited,r="string";break;case eF.BOOL:s=!1===t,r="bool";break;case eF.UINT32:r="uint32";break;case eF.DOUBLE:n=SL.Bit64,r="double";break;case eF.FLOAT:n=SL.Bit32,r="float";break;case eF.INT64:s=i||UL.from(t).isZero(),r="int64";break;case eF.UINT64:s=i||FL.from(t).isZero(),r="uint64";break;case eF.FIXED64:s=i||FL.from(t).isZero(),n=SL.Bit64,r="fixed64";break;case eF.BYTES:s=i||!t.byteLength,n=SL.LengthDelimited,r="bytes";break;case eF.FIXED32:n=SL.Bit32,r="fixed32";break;case eF.SFIXED32:n=SL.Bit32,r="sfixed32";break;case eF.SFIXED64:s=i||UL.from(t).isZero(),n=SL.Bit64,r="sfixed64";break;case eF.SINT32:r="sint32";break;case eF.SINT64:s=i||UL.from(t).isZero(),r="sint64"}return[n,r,i||s]}}function dF(e,t,r){let n,i,s=r;for(let r of e.fields){let e=r.localName;if(r.oneof){const o=s[r.oneof];if(null==(null==o?void 0:o.oneofKind))continue;if(n=o[e],i=t[r.oneof],i.oneofKind=o.oneofKind,null==n){delete i[e];continue}}else if(n=s[e],i=t,null==n)continue;switch(r.repeat&&(i[e].length=n.length),r.kind){case"scalar":case"enum":if(r.repeat)for(let t=0;t<n.length;t++)i[e][t]=n[t];else i[e]=n;break;case"message":let t=r.T();if(r.repeat)for(let r=0;r<n.length;r++)i[e][r]=t.create(n[r]);else void 0===i[e]?i[e]=t.create(n):t.mergePartial(i[e],n);break;case"map":switch(r.V.kind){case"scalar":case"enum":Object.assign(i[e],n);break;case"message":let t=r.V.T();for(let r of Object.keys(n))i[e][r]=t.create(n[r])}}}}const fF=Object.values;function pF(e,t,r){if(t===r)return!0;if(e!==eF.BYTES)return!1;let n=t,i=r;if(n.length!==i.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!=i[e])return!1;return!0}function gF(e,t,r){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!pF(e,t[n],r[n]))return!1;return!0}function mF(e,t,r){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!e.equals(t[n],r[n]))return!1;return!0}const yF=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),bF=yF[YL]={};class wF{constructor(e,t,r){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(nF),this.options=null!=r?r:{},bF.value=this,this.messagePrototype=Object.create(null,yF),this.refTypeCheck=new sF(this),this.refJsonReader=new aF(this),this.refJsonWriter=new cF(this),this.refBinReader=new lF(this),this.refBinWriter=new hF(this)}create(e){let t=function(e){const t=e.messagePrototype?Object.create(e.messagePrototype):Object.defineProperty({},YL,{value:e});for(let r of e.fields){let e=r.localName;if(!r.opt)if(r.oneof)t[r.oneof]={oneofKind:void 0};else if(r.repeat)t[e]=[];else switch(r.kind){case"scalar":t[e]=uF(r.T,r.L);break;case"enum":t[e]=0;break;case"map":t[e]={}}}return t}(this);return void 0!==e&&dF(this,t,e),t}clone(e){let t=this.create();return dF(this,t,e),t}equals(e,t){return function(e,t,r){if(t===r)return!0;if(!t||!r)return!1;for(let n of e.fields){let e=n.localName,i=n.oneof?t[n.oneof][e]:t[e],s=n.oneof?r[n.oneof][e]:r[e];switch(n.kind){case"enum":case"scalar":let e="enum"==n.kind?eF.INT32:n.T;if(!(n.repeat?gF(e,i,s):pF(e,i,s)))return!1;break;case"map":if(!("message"==n.V.kind?mF(n.V.T(),fF(i),fF(s)):gF("enum"==n.V.kind?eF.INT32:n.V.T,fF(i),fF(s))))return!1;break;case"message":let t=n.T();if(!(n.repeat?mF(t,i,s):t.equals(i,s)))return!1}}return!0}(this,e,t)}is(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!1)}isAssignable(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!0)}mergePartial(e,t){dF(this,e,t)}fromBinary(e,t){let r=function(e){return e?Object.assign(Object.assign({},jL),e):jL}(t);return this.internalBinaryRead(r.readerFactory(e),e.byteLength,r)}fromJson(e,t){return this.internalJsonRead(e,function(e){return e?Object.assign(Object.assign({},JL),e):JL}(t))}fromJsonString(e,t){let r=JSON.parse(e);return this.fromJson(r,t)}toJson(e,t){return this.internalJsonWrite(e,QL(t))}toJsonString(e,t){var r;let n=this.toJson(e,t);return JSON.stringify(n,null,null!==(r=null==t?void 0:t.prettySpaces)&&void 0!==r?r:0)}toBinary(e,t){let r=function(e){return e?Object.assign(Object.assign({},HL),e):HL}(t);return this.internalBinaryWrite(e,r.writerFactory(),r).finish()}internalJsonRead(e,t,r){if(null!==e&&"object"==typeof e&&!Array.isArray(e)){let n=null!=r?r:this.create();return this.refJsonReader.read(e,n,t),n}throw new Error(`Unable to parse message ${this.typeName} from JSON ${bL(e)}.`)}internalJsonWrite(e,t){return this.refJsonWriter.write(e,t)}internalBinaryWrite(e,t,r){return this.refBinWriter.write(e,t,r),t}internalBinaryRead(e,t,r,n){let i=null!=n?n:this.create();return this.refBinReader.read(e,i,r,t),i}}class vF{constructor(e,t,r){this.typeName=e,this.methods=t.map((e=>function(e,t){var r,n,i;let s=e;return s.service=t,s.localName=null!==(r=s.localName)&&void 0!==r?r:XL(s.name),s.serverStreaming=!!s.serverStreaming,s.clientStreaming=!!s.clientStreaming,s.options=null!==(n=s.options)&&void 0!==n?n:{},s.idempotency=null!==(i=s.idempotency)&&void 0!==i?i:void 0,s}(e,this))),this.options=null!=r?r:{}}}class EF extends Error{constructor(e,t="UNKNOWN",r){super(e),this.name="RpcError",Object.setPrototypeOf(this,new.target.prototype),this.code=t,this.meta=null!=r?r:{}}toString(){const e=[this.name+": "+this.message];this.code&&(e.push(""),e.push("Code: "+this.code)),this.serviceName&&this.methodName&&e.push("Method: "+this.serviceName+"/"+this.methodName);let t=Object.entries(this.meta);if(t.length){e.push(""),e.push("Meta:");for(let[r,n]of t)e.push(` ${r}: ${n}`)}return e.join("\n")}}function AF(e,t){if(!e)return;let r=t;for(let[t,n]of Object.entries(e))n instanceof Date?r[t]=new Date(n.getTime()):Array.isArray(n)?r[t]=n.concat():r[t]=n}var SF;!function(e){e[e.PENDING=0]="PENDING",e[e.REJECTED=1]="REJECTED",e[e.RESOLVED=2]="RESOLVED"}(SF||(SF={}));class kF{constructor(e=!0){this._state=SF.PENDING,this._promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t})),e&&this._promise.catch((e=>{}))}get state(){return this._state}get promise(){return this._promise}resolve(e){if(this.state!==SF.PENDING)throw new Error(`cannot resolve ${SF[this.state].toLowerCase()}`);this._resolve(e),this._state=SF.RESOLVED}reject(e){if(this.state!==SF.PENDING)throw new Error(`cannot reject ${SF[this.state].toLowerCase()}`);this._reject(e),this._state=SF.REJECTED}resolvePending(e){this._state===SF.PENDING&&this.resolve(e)}rejectPending(e){this._state===SF.PENDING&&this.reject(e)}}var RF=window&&window.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class CF{constructor(e,t,r,n,i,s,o){this.method=e,this.requestHeaders=t,this.request=r,this.headers=n,this.response=i,this.status=s,this.trailers=o}then(e,t){return this.promiseFinished().then((t=>e?Promise.resolve(e(t)):t),(e=>t?Promise.resolve(t(e)):Promise.reject(e)))}promiseFinished(){return RF(this,void 0,void 0,(function*(){let[e,t,r,n]=yield Promise.all([this.headers,this.response,this.status,this.trailers]);return{method:this.method,requestHeaders:this.requestHeaders,request:this.request,headers:e,response:t,status:r,trailers:n}}))}}function IF(e,t,r,n,i){var s;{let e=(e,r,n)=>t.unary(e,r,n);for(const t of(null!==(s=n.interceptors)&&void 0!==s?s:[]).filter((e=>e.interceptUnary)).reverse()){const r=e;e=(e,n,i)=>t.interceptUnary(r,e,n,i)}return e(r,i,n)}}const PF=[];for(let e=0;e<256;++e)PF.push((e+256).toString(16).slice(1));let TF;const _F=new Uint8Array(16);var NF,MF={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function xF(e,t,r){if(MF.randomUUID&&!e)return MF.randomUUID();const n=(e=e||{}).random??e.rng?.()??function(){if(!TF){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");TF=crypto.getRandomValues.bind(crypto)}return TF(_F)}();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=15&n[6]|64,n[8]=63&n[8]|128,function(e,t=0){return(PF[e[t+0]]+PF[e[t+1]]+PF[e[t+2]]+PF[e[t+3]]+"-"+PF[e[t+4]]+PF[e[t+5]]+"-"+PF[e[t+6]]+PF[e[t+7]]+"-"+PF[e[t+8]]+PF[e[t+9]]+"-"+PF[e[t+10]]+PF[e[t+11]]+PF[e[t+12]]+PF[e[t+13]]+PF[e[t+14]]+PF[e[t+15]]).toLowerCase()}(n)}!function(e){e.RPC_TIMEOUT="RPC_TIMEOUT",e.RPC_REQUEST="RPC_REQUEST",e.RPC_SERVER_ERROR="RPC_SERVER_ERROR",e.RPC_CLIENT_ERROR="RPC_CLIENT_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNKNOWN_RPC_METHOD="UNKNOWN_RPC_METHOD",e.FAILED_TO_PARSE="FAILED_TO_PARSE",e.FAILED_TO_SERIALIZE="FAILED_TO_SERIALIZE",e.DISCONNECTED="DISCONNECTED"}(NF||(NF={}));let OF=class extends Error{code;originalError;constructor(e,t,r){super(t),this.code=e,this.originalError=r}};class DF extends OF{constructor(e,t){super(NF.RPC_TIMEOUT,e,t)}}class BF extends OF{constructor(e,t){super(NF.RPC_REQUEST,e,t)}}class LF extends OF{errorClassName;errorCode;constructor(e,t,r){super(NF.RPC_SERVER_ERROR,e),this.errorClassName=t,this.errorCode=r}}class FF extends OF{constructor(e,t){super(NF.NOT_IMPLEMENTED,e,t)}}let UF=class extends OF{constructor(e,t){super(NF.UNKNOWN_RPC_METHOD,e,t)}};class jF extends OF{constructor(e,t){super(NF.FAILED_TO_PARSE,e,t)}}var qF=Object.freeze({__proto__:null,Disconnected:class extends OF{constructor(e,t){super(NF.DISCONNECTED,e,t)}},get ErrorCode(){return NF},FailedToParse:jF,FailedToSerialize:class extends OF{constructor(e,t){super(NF.FAILED_TO_SERIALIZE,e,t)}},NotImplemented:FF,RpcClientError:class extends OF{constructor(e,t){super(NF.RPC_CLIENT_ERROR,e,t)}},RpcRequest:BF,RpcServerError:LF,RpcTimeout:DF,UnknownRpcMethod:UF});const zF=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}},KF=new Bv("ClientTransport");class GF extends Sl{static objectCount=0;objectId;defaultOptions;constructor(e=5e3){super(),this.objectId=GF.objectCount++,this.defaultOptions={timeout:e,clientId:this.objectId}}mergeOptions(e){return function(e,t){if(!t)return e;let r={};AF(e,r),AF(t,r);for(let n of Object.keys(t)){let i=t[n];switch(n){case"jsonOptions":r.jsonOptions=ZL(e.jsonOptions,r.jsonOptions);break;case"binaryOptions":r.binaryOptions=kL(e.binaryOptions,r.binaryOptions);break;case"meta":r.meta={},AF(e.meta,r.meta),AF(t.meta,r.meta);break;case"interceptors":r.interceptors=e.interceptors?e.interceptors.concat(i):i.concat()}}return r}(this.defaultOptions,e)}static createRequestHeaders(e,t){return{method:e.localName,request:"request",notification:t?"notification":void 0}}unary(e,t,r){if(!r?.isProtoRpc)throw new Error("ProtoRpc ClientTransport can only be used with ProtoRpcClients. Please convert your protobuf-ts generated client to a ProtoRpcClient by calling toProtoRpcclient(yourClient).");const n=zF.pack(t,e.I),i={header:GF.createRequestHeaders(e,r.notification),body:n,requestId:xF()},s=new kF,o=new kF,a=new kF,c=new kF,u=new CF(e,{},t,s.promise,o.promise,a.promise,c.promise),l={message:o,header:s,trailer:c,status:a,messageParser:t=>e.O.fromBinary(t)};return KF.trace(`New rpc ${r.notification?"notification":"request"}, ${i.requestId}`),this.emit("rpcRequest",i,r,l),u}clientStreaming(e){const t=new EF("Client streaming is not supported by DhtTransport");throw t.methodName=e.name,t.serviceName=e.service.typeName,t}duplex(e){const t=new EF("Duplex streaming is not supported by DhtTransport");throw t.methodName=e.name,t.serviceName=e.service.typeName,t}serverStreaming(e){const t=new EF("Server streaming is not supported by DhtTransport");throw t.methodName=e.name,t.serviceName=e.service.typeName,t}stop(){this.removeAllListeners()}}const VF=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var HF;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(HF||(HF={}));new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>zF},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",HF]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};function $F(e,t){const r=new Promise(((r,n)=>{const i=setTimeout((()=>{n(new DF("Timed out in "+e+"ms."))}),e);t.finally((()=>clearTimeout(i))).catch((()=>null))}));return Promise.race([t,r])}new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>VF}])}};class WF{method=void 0;headers=void 0;deadline=void 0;trailers=void 0;status=void 0;sendResponseHeaders(e){throw new FF("Method not implemented.")}cancelled=void 0;onCancel(e){throw new FF("Method not implemented.")}notification}var JF=UF;const QF=e=>({timeout:e.timeout??1e3}),ZF=new Bv("ServerRegistry");function YF(e){try{return e()}catch(e){throw new jF("Could not parse binary to JSON-object",e)}}class XF{methods=new Map;notifications=new Map;getImplementation(e,t){if(!e?.header?.method)throw new JF('Header "method" missing from RPC message');if(!t.has(e.header.method))throw new JF(`RPC Method ${e.header.method} is not provided`);return t.get(e.header.method)}async handleRequest(e,t){ZF.trace(`Server processing RPC call ${e.requestId}`);const r=this.getImplementation(e,this.methods),n=r.options.timeout;return await $F(n,r.fn(e.body,t??new WF))}async handleNotification(e,t){ZF.trace(`Server processing RPC notification ${e.requestId}`);const r=this.getImplementation(e,this.notifications),n=r.options.timeout;await $F(n,r.fn(e.body,t??new WF))}registerRpcMethod(e,t,r,n,i={}){const s={fn:async(r,i)=>{const s=YF((()=>zF.unpack(r,e))),o=await n(s,i);return zF.pack(o,t)},options:QF(i)};this.methods.set(r,s)}registerRpcNotification(e,t,r,n={}){const i={fn:async(t,n)=>{const i=YF((()=>zF.unpack(t,e)));await r(i,n)},options:QF(n)};this.notifications.set(t,i)}}var eU;!function(e){e.OK="OK",e.STOPPED="STOPPED",e.DEADLINE_EXCEEDED="DEADLINE_EXCEEDED",e.SERVER_ERROR="SERVER_ERROR"}(eU||(eU={}));class tU{deferredPromises;callContext;timeoutRef;constructor(e,t,r){this.deferredPromises=e,this.callContext=t,r&&(this.timeoutRef=setTimeout((()=>{const e=new DF("Rpc request timed out",new Error);this.rejectDeferredPromises(e,eU.DEADLINE_EXCEEDED),r.onTimeout()}),r.timeout))}resolveRequest(e){this.timeoutRef&&clearTimeout(this.timeoutRef),this.resolveDeferredPromises(e)}resolveNotification(){this.timeoutRef&&clearTimeout(this.timeoutRef),this.deferredPromises.message.state===SF.PENDING&&(this.deferredPromises.message.resolve({}),this.deferredPromises.header.resolve({}),this.deferredPromises.status.resolve({code:eU.OK,detail:""}),this.deferredPromises.trailer.resolve({}))}rejectRequest(e,t){this.timeoutRef&&clearTimeout(this.timeoutRef),this.rejectDeferredPromises(e,t)}resolveDeferredPromises(e){if(this.deferredPromises.message.state===SF.PENDING)try{const t=this.deferredPromises.messageParser(e.body.value);this.deferredPromises.message.resolve(t),this.deferredPromises.header.resolve({}),this.deferredPromises.status.resolve({code:eU.OK,detail:""}),this.deferredPromises.trailer.resolve({})}catch(e){rU.debug("Could not parse response, received message is likely ");const t=new jF("Failed to parse received response, network protocol version likely is likely incompatible",e);this.rejectDeferredPromises(t,eU.SERVER_ERROR)}}rejectDeferredPromises(e,t){this.deferredPromises.message.state===SF.PENDING&&(this.deferredPromises.message.reject(e),this.deferredPromises.header.reject(e),this.deferredPromises.status.reject({code:t,detail:e.message}),this.deferredPromises.trailer.reject(e))}fulfillsPredicate(e){return e(this)}getCallContext(){return this.callContext}}const rU=new Bv("RpcCommunicator");class nU{stopped=!1;rpcClientTransport;rpcServerRegistry;ongoingRequests;rpcRequestTimeout;outgoingMessageListener;constructor(e){this.rpcRequestTimeout=e?.rpcRequestTimeout??5e3,this.rpcClientTransport=new GF(this.rpcRequestTimeout),this.rpcServerRegistry=new XF,this.ongoingRequests=new Map,this.rpcClientTransport.on("rpcRequest",((e,t,r)=>{this.onOutgoingMessage(e,t,r)}))}async handleIncomingMessage(e,t){if(!this.stopped)return this.onIncomingMessage(e,t)}registerRpcMethod(e,t,r,n,i={}){this.rpcServerRegistry.registerRpcMethod(e,t,r,n,i)}registerRpcNotification(e,t,r,n={}){this.rpcServerRegistry.registerRpcNotification(e,t,r,n)}getRpcClientTransport(){return this.rpcClientTransport}stop(){this.stopped=!0,this.ongoingRequests.forEach((e=>{e.rejectRequest(new Error("stopped"),eU.STOPPED)})),this.ongoingRequests.clear(),this.rpcClientTransport.stop()}onOutgoingMessage(e,t,r){if(this.stopped){if(r){new tU(r,t).rejectRequest(new Error("stopped"),eU.STOPPED)}return}const n=this.rpcClientTransport.mergeOptions(t);if(!r||t&&t.notification||this.registerRequest(e.requestId,r,t,n.timeout),rU.trace(`onOutGoingMessage, messageId: ${e.requestId}`),this.outgoingMessageListener)this.outgoingMessageListener(e,e.requestId,t).catch((n=>{if(r)if(this.ongoingRequests.has(e.requestId))this.handleClientError(e.requestId,n);else{new tU(r,t).rejectRequest(n,eU.SERVER_ERROR)}})).then((()=>{if(r&&!this.ongoingRequests.has(e.requestId)){new tU(r,t).resolveNotification()}}));else if(r&&!this.ongoingRequests.has(e.requestId)){new tU(r,t).resolveNotification()}}async onIncomingMessage(e,t){rU.trace(`onIncomingMessage, requestId: ${e.requestId}`),e.header.response&&this.ongoingRequests.has(e.requestId)?void 0!==e.errorType?this.rejectOngoingRequest(e):this.resolveOngoingRequest(e):e.header.request&&e.header.method&&(e.header.notification?await this.handleNotification(e,t):await this.handleRequest(e,t))}async handleRequest(e,t){if(this.stopped)return;let r;try{const n=await this.rpcServerRegistry.handleRequest(e,t);r=this.createResponseRpcMessage({request:e,body:n})}catch(t){const n={request:e};t.code===NF.UNKNOWN_RPC_METHOD?n.errorType=HF.UNKNOWN_RPC_METHOD:t.code===NF.RPC_TIMEOUT?n.errorType=HF.SERVER_TIMEOUT:(n.errorType=HF.SERVER_ERROR,t.className&&(n.errorClassName=t.className),t.code&&(n.errorCode=t.code),t.message&&(n.errorMessage=t.message)),r=this.createResponseRpcMessage(n)}this.onOutgoingMessage(r,t,void 0)}async handleNotification(e,t){if(!this.stopped)try{await this.rpcServerRegistry.handleNotification(e,t)}catch(e){rU.debug("error",{err:e})}}registerRequest(e,t,r,n=this.rpcRequestTimeout){if(this.stopped)return;const i=new tU(t,r,{timeout:n,onTimeout:()=>this.ongoingRequests.delete(e)});this.ongoingRequests.set(e,i)}resolveOngoingRequest(e){if(this.stopped)return;this.ongoingRequests.get(e.requestId).resolveRequest(e),this.ongoingRequests.delete(e.requestId)}rejectOngoingRequest(e){if(this.stopped)return;const t=this.ongoingRequests.get(e.requestId);let r;r=e.errorType===HF.SERVER_TIMEOUT?new DF("Server timed out on request"):e.errorType===HF.UNKNOWN_RPC_METHOD?new UF(`Server does not implement method ${e.header.method}`):e.errorType===HF.SERVER_ERROR?new LF(e.errorMessage,e.errorClassName,e.errorCode):new BF("Unknown RPC Error"),t.rejectRequest(r,eU.SERVER_ERROR),this.ongoingRequests.delete(e.requestId)}handleClientError(e,t){if(this.stopped)return;const r=this.ongoingRequests.get(e);r&&(r.rejectRequest(t,eU.SERVER_ERROR),this.ongoingRequests.delete(e))}setOutgoingMessageListener(e){this.outgoingMessageListener=e}getRequestIds(e){return Array.from(this.ongoingRequests.entries()).filter((([t,r])=>r.fulfillsPredicate(e))).map((([e])=>e))}createResponseRpcMessage({request:e,body:t,errorType:r,errorClassName:n,errorCode:i,errorMessage:s}){return{body:t,header:{response:"response",method:e.header.method},requestId:e.requestId,errorType:r,errorClassName:n,errorCode:i,errorMessage:s}}}function iU(e){const t={};Object.assign(t,e);return e.methods.forEach((r=>{r.O.typeName===VF.typeName?t[r.name]=(...t)=>(async(e,t,r)=>{r.length<2?r.push({}):r[1]??={},r[1].isProtoRpc=!0,r[1].notification=!0,await t[e].apply(t,r)})(r.name,e,t):t[r.name]=(...t)=>((e,t,r)=>(r.length<2?r.push({}):r[1]??={},r[1].isProtoRpc=!0,t[e].apply(t,r)))(r.name,e,t).response})),t}var sU,oU={exports:{}},aU=oU.exports;var cU,uU,lU=(sU||(sU=1,function(e){!function(t){const r="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp(`^${r}\\.${r}\\.${r}\\.${r}$`,"i"),threeOctet:new RegExp(`^${r}\\.${r}\\.${r}$`,"i"),twoOctet:new RegExp(`^${r}\\.${r}$`,"i"),longValue:new RegExp(`^${r}$`,"i")},i=new RegExp("^0[0-7]+$","i"),s=new RegExp("^0x[a-f0-9]+$","i"),o="%[0-9a-z]{1,}",a="(?:[0-9a-f]+::?)+",c={zoneIndex:new RegExp(o,"i"),native:new RegExp(`^(::)?(${a})?([0-9a-f]+)?(::)?(${o})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${r}\\.${r}\\.${r}\\.${r}(${o})?)$`,"i"),transitional:new RegExp(`^((?:${a})|(?:::)(?:${a})?)${r}\\.${r}\\.${r}\\.${r}(${o})?$`,"i")};function u(e,t){if(e.indexOf("::")!==e.lastIndexOf("::"))return null;let r,n,i=0,s=-1,o=(e.match(c.zoneIndex)||[])[0];for(o&&(o=o.substring(1),e=e.replace(/%.+$/,""));(s=e.indexOf(":",s+1))>=0;)i++;if("::"===e.substr(0,2)&&i--,"::"===e.substr(-2,2)&&i--,i>t)return null;for(n=t-i,r=":";n--;)r+="0:";return":"===(e=e.replace("::",r))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){const t=e.split(":"),r=[];for(let e=0;e<t.length;e++)r.push(parseInt(t[e],16));return r}(),zoneId:o}}function l(e,t,r,n){if(e.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let i,s=0;for(;n>0;){if(i=r-n,i<0&&(i=0),e[s]>>i!=t[s]>>i)return!1;n-=r,s+=1}return!0}function h(e){if(s.test(e))return parseInt(e,16);if("0"===e[0]&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw new Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function d(e,t){for(;e.length<t;)e=`0${e}`;return e}const f={};f.IPv4=function(){function e(e){if(4!==e.length)throw new Error("ipaddr: ipv4 octet count should be 4");let t,r;for(t=0;t<e.length;t++)if(r=e[t],!(0<=r&&r<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=e}return e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,18,0,0]),15],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]],as112:[[new e([192,175,48,0]),24],[new e([192,31,196,0]),24]],amt:[[new e([192,52,193,0]),24]]},e.prototype.kind=function(){return"ipv4"},e.prototype.match=function(e,t){let r;if(void 0===t&&(r=e,e=r[0],t=r[1]),"ipv4"!==e.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return l(this.octets,e.octets,8,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1;const r={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0};let n,i,s;for(n=3;n>=0;n-=1){if(i=this.octets[n],!(i in r))return null;if(s=r[i],t&&0!==s)return null;8!==s&&(t=!0),e+=s}return 32-e},e.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return f.IPv6.parse(`::ffff:${this.toString()}`)},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(".")},e}(),f.IPv4.broadcastAddressFromCIDR=function(e){try{const t=this.parseCIDR(e),r=t[0].toByteArray(),n=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[];let s=0;for(;s<4;)i.push(parseInt(r[s],10)|255^parseInt(n[s],10)),s++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.isIPv4=function(e){return null!==this.parser(e)},f.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(e){return!1}},f.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch(e){return!1}},f.IPv4.isValidFourPartDecimal=function(e){return!(!f.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},f.IPv4.networkAddressFromCIDR=function(e){let t,r,n,i,s;try{for(t=this.parseCIDR(e),n=t[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.parse=function(e){const t=this.parser(e);if(null===t)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(t)},f.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){const e=parseInt(t[2]);if(e>=0&&e<=32){const r=[this.parse(t[1]),e];return Object.defineProperty(r,"toString",{value:function(){return this.join("/")}}),r}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},f.IPv4.parser=function(e){let t,r,i;if(t=e.match(n.fourOctet))return function(){const e=t.slice(1,6),n=[];for(let t=0;t<e.length;t++)r=e[t],n.push(h(r));return n}();if(t=e.match(n.longValue)){if(i=h(t[1]),i>4294967295||i<0)throw new Error("ipaddr: address outside defined range");return function(){const e=[];let t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e}().reverse()}return(t=e.match(n.twoOctet))?function(){const e=t.slice(1,4),r=[];if(i=h(e[1]),i>16777215||i<0)throw new Error("ipaddr: address outside defined range");return r.push(h(e[0])),r.push(i>>16&255),r.push(i>>8&255),r.push(255&i),r}():(t=e.match(n.threeOctet))?function(){const e=t.slice(1,5),r=[];if(i=h(e[2]),i>65535||i<0)throw new Error("ipaddr: address outside defined range");return r.push(h(e[0])),r.push(h(e[1])),r.push(i>>8&255),r.push(255&i),r}():null},f.IPv4.subnetMaskFromPrefixLength=function(e){if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");const t=[0,0,0,0];let r=0;const n=Math.floor(e/8);for(;r<n;)t[r]=255,r++;return n<4&&(t[n]=Math.pow(2,e%8)-1<<8-e%8),new this(t)},f.IPv6=function(){function e(e,t){let r,n;if(16===e.length)for(this.parts=[],r=0;r<=14;r+=2)this.parts.push(e[r]<<8|e[r+1]);else{if(8!==e.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=e}for(r=0;r<this.parts.length;r++)if(n=this.parts[r],!(0<=n&&n<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],discard:[new e([256,0,0,0,0,0,0,0]),64],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],benchmarking:[new e([8193,2,0,0,0,0,0,0]),48],amt:[new e([8193,3,0,0,0,0,0,0]),32],as112v6:[[new e([8193,4,274,0,0,0,0,0]),48],[new e([9760,79,32768,0,0,0,0,0]),48]],deprecated:[new e([8193,16,0,0,0,0,0,0]),28],orchid2:[new e([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new e([8193,48,0,0,0,0,0,0]),28],reserved:[[new e([8193,0,0,0,0,0,0,0]),23],[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},e.prototype.kind=function(){return"ipv6"},e.prototype.match=function(e,t){let r;if(void 0===t&&(r=e,e=r[0],t=r[1]),"ipv6"!==e.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return l(this.parts,e.parts,16,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1;const r={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0};let n,i;for(let s=7;s>=0;s-=1){if(n=this.parts[s],!(n in r))return null;if(i=r[n],t&&0!==i)return null;16!==i&&(t=!0),e+=i}return 128-e},e.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e;const t=[],r=this.parts;for(let n=0;n<r.length;n++)e=r[n],t.push(e>>8),t.push(255&e);return t},e.prototype.toFixedLengthString=function(){const e=function(){const e=[];for(let t=0;t<this.parts.length;t++)e.push(d(this.parts[t].toString(16),4));return e}.call(this).join(":");let t="";return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");const e=this.parts.slice(-2),t=e[0],r=e[1];return new f.IPv4([t>>8,255&t,r>>8,255&r])},e.prototype.toNormalizedString=function(){const e=function(){const e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}.call(this).join(":");let t="";return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toRFC5952String=function(){const e=/((^|:)(0(:|$)){2,})/g,t=this.toNormalizedString();let r,n=0,i=-1;for(;r=e.exec(t);)r[0].length>i&&(n=r.index,i=r[0].length);return i<0?t:`${t.substring(0,n)}::${t.substring(n+i)}`},e.prototype.toString=function(){return this.toRFC5952String()},e}(),f.IPv6.broadcastAddressFromCIDR=function(e){try{const t=this.parseCIDR(e),r=t[0].toByteArray(),n=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[];let s=0;for(;s<16;)i.push(parseInt(r[s],10)|255^parseInt(n[s],10)),s++;return new this(i)}catch(e){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},f.IPv6.isIPv6=function(e){return null!==this.parser(e)},f.IPv6.isValid=function(e){if("string"==typeof e&&-1===e.indexOf(":"))return!1;try{const t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch(e){return!1}},f.IPv6.isValidCIDR=function(e){if("string"==typeof e&&-1===e.indexOf(":"))return!1;try{return this.parseCIDR(e),!0}catch(e){return!1}},f.IPv6.networkAddressFromCIDR=function(e){let t,r,n,i,s;try{for(t=this.parseCIDR(e),n=t[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<16;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},f.IPv6.parse=function(e){const t=this.parser(e);if(null===t.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(t.parts,t.zoneId)},f.IPv6.parseCIDR=function(e){let t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]),t>=0&&t<=128))return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},f.IPv6.parser=function(e){let t,r,n,i,s,o;if(n=e.match(c.deprecatedTransitional))return this.parser(`::ffff:${n[1]}`);if(c.native.test(e))return u(e,8);if((n=e.match(c.transitional))&&(o=n[6]||"",t=n[1],n[1].endsWith("::")||(t=t.slice(0,-1)),t=u(t+o,6),t.parts)){for(s=[parseInt(n[2]),parseInt(n[3]),parseInt(n[4]),parseInt(n[5])],r=0;r<s.length;r++)if(i=s[r],!(0<=i&&i<=255))return null;return t.parts.push(s[0]<<8|s[1]),t.parts.push(s[2]<<8|s[3]),{parts:t.parts,zoneId:t.zoneId}}return null},f.IPv6.subnetMaskFromPrefixLength=function(e){if((e=parseInt(e))<0||e>128)throw new Error("ipaddr: invalid IPv6 prefix length");const t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let r=0;const n=Math.floor(e/8);for(;r<n;)t[r]=255,r++;return n<16&&(t[n]=Math.pow(2,e%8)-1<<8-e%8),new this(t)},f.fromByteArray=function(e){const t=e.length;if(4===t)return new f.IPv4(e);if(16===t)return new f.IPv6(e);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},f.isValid=function(e){return f.IPv6.isValid(e)||f.IPv4.isValid(e)},f.isValidCIDR=function(e){return f.IPv6.isValidCIDR(e)||f.IPv4.isValidCIDR(e)},f.parse=function(e){if(f.IPv6.isValid(e))return f.IPv6.parse(e);if(f.IPv4.isValid(e))return f.IPv4.parse(e);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},f.parseCIDR=function(e){try{return f.IPv6.parseCIDR(e)}catch(t){try{return f.IPv4.parseCIDR(e)}catch(e){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},f.process=function(e){const t=this.parse(e);return"ipv6"===t.kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t},f.subnetMatch=function(e,t,r){let n,i,s,o;for(i in null==r&&(r="unicast"),t)if(Object.prototype.hasOwnProperty.call(t,i))for(s=t[i],!s[0]||s[0]instanceof Array||(s=[s]),n=0;n<s.length;n++)if(o=s[n],e.kind()===o[0].kind()&&e.match.apply(e,o))return i;return r},e.exports?e.exports=f:t.ipaddr=f}(aU)}(oU)),oU.exports),hU=n(lU);var dU,fU,pU,gU,mU="1.0.35";var yU=function(){if(gU)return pU;var e;if(gU=1,"object"==typeof globalThis)e=globalThis;else try{e=function(){if(uU)return cU;uU=1;var e=function(){if("object"==typeof self&&self)return self;if("object"==typeof window&&window)return window;throw new Error("Unable to resolve global `this`")};return cU=function(){if(this)return this;if("object"==typeof globalThis&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch(t){return e()}try{return __global__||e()}finally{delete Object.prototype.__global__}}()}()}catch(e){}finally{if(e||"undefined"==typeof window||(e=window),!e)throw new Error("Could not determine global this")}var t=e.WebSocket||e.MozWebSocket,r=fU?dU:(fU=1,dU=mU);function n(e,r){return r?new t(e,r):new t(e)}return t&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(n,e,{get:function(){return t[e]}})})),pU={w3cwebsocket:t?n:null,version:r}}();var bU,wU,vU,EU,AU,SU,kU,RU;function CU(){if(wU)return bU;wU=1;var e=BE();return bU=function(t,r){var n=-1,i=t.length,s=i-1;for(r=void 0===r?i:r;++n<r;){var o=e(n,s),a=t[o];t[o]=t[n],t[n]=a}return t.length=r,t},bU}var IU=function(){if(RU)return kU;RU=1;var e=function(){if(EU)return vU;EU=1;var e=Th(),t=CU();return vU=function(r){return t(e(r))},vU}(),t=function(){if(SU)return AU;SU=1;var e=CU(),t=nA();return AU=function(r){return e(t(r))}}(),r=qu();return kU=function(n){return(r(n)?e:t)(n)}}(),PU=n(IU),TU=function(e,t){return TU=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},TU(e,t)};function _U(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}TU(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}"function"==typeof SuppressedError&&SuppressedError;var NU=function(){function e(e,t,r){void 0===r&&(r=1),this.t=void 0,this.i=void 0,this.h=void 0,this.u=e,this.o=t,this.l=r}return e.prototype.v=function(){var e=this,t=e.h.h===e;if(t&&1===e.l)e=e.i;else if(e.t)for(e=e.t;e.i;)e=e.i;else{if(t)return e.h;for(var r=e.h;r.t===e;)r=(e=r).h;e=r}return e},e.prototype.p=function(){var e=this;if(e.i){for(e=e.i;e.t;)e=e.t;return e}for(var t=e.h;t.i===e;)t=(e=t).h;return e.i!==t?t:e},e.prototype.T=function(){var e=this.h,t=this.i,r=t.t;return e.h===this?e.h=t:e.t===this?e.t=t:e.i=t,t.h=e,t.t=this,this.h=t,this.i=r,r&&(r.h=this),t},e.prototype.I=function(){var e=this.h,t=this.t,r=t.i;return e.h===this?e.h=t:e.t===this?e.t=t:e.i=t,t.h=e,t.i=this,this.h=t,this.t=r,r&&(r.h=this),t},e}(),MU=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.O=1,t}return _U(t,e),t.prototype.T=function(){var t=e.prototype.T.call(this);return this.M(),t.M(),t},t.prototype.I=function(){var t=e.prototype.I.call(this);return this.M(),t.M(),t},t.prototype.M=function(){this.O=1,this.t&&(this.O+=this.t.O),this.i&&(this.O+=this.i.O)},t}(NU),xU=function(){function e(e){void 0===e&&(e=0),this.iteratorType=e}return e.prototype.equals=function(e){return this.C===e.C},e}(),OU=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return _U(t,e),t}(function(){function e(){this._=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._},enumerable:!1,configurable:!0}),e.prototype.size=function(){return this._},e.prototype.empty=function(){return 0===this._},e}());function DU(){throw new RangeError("Iterator access denied!")}var BU,LU,FU=function(e){function t(t,r){void 0===t&&(t=function(e,t){return e<t?-1:e>t?1:0}),void 0===r&&(r=!1);var n=e.call(this)||this;return n.N=void 0,n.g=t,n.enableIndex=r,n.S=r?MU:NU,n.A=new n.S,n}return _U(t,e),t.prototype.m=function(e,t){for(var r=this.A;e;){var n=this.g(e.u,t);if(n<0)e=e.i;else{if(!(n>0))return e;r=e,e=e.t}}return r},t.prototype.B=function(e,t){for(var r=this.A;e;){this.g(e.u,t)<=0?e=e.i:(r=e,e=e.t)}return r},t.prototype.j=function(e,t){for(var r=this.A;e;){var n=this.g(e.u,t);if(n<0)r=e,e=e.i;else{if(!(n>0))return e;e=e.t}}return r},t.prototype.k=function(e,t){for(var r=this.A;e;){this.g(e.u,t)<0?(r=e,e=e.i):e=e.t}return r},t.prototype.R=function(e){for(;;){var t,r=e.h;if(r===this.A)return;if(1===e.l)return void(e.l=0);if(e===r.t)if(1===(t=r.i).l)t.l=0,r.l=1,r===this.N?this.N=r.T():r.T();else{if(t.i&&1===t.i.l)return t.l=r.l,r.l=0,t.i.l=0,void(r===this.N?this.N=r.T():r.T());t.t&&1===t.t.l?(t.l=1,t.t.l=0,t.I()):(t.l=1,e=r)}else if(1===(t=r.t).l)t.l=0,r.l=1,r===this.N?this.N=r.I():r.I();else{if(t.t&&1===t.t.l)return t.l=r.l,r.l=0,t.t.l=0,void(r===this.N?this.N=r.I():r.I());t.i&&1===t.i.l?(t.l=1,t.i.l=0,t.T()):(t.l=1,e=r)}}},t.prototype.G=function(e){if(1!==this._){for(var t=e;t.t||t.i;){if(t.i)for(t=t.i;t.t;)t=t.t;else t=t.t;var r=e.u;e.u=t.u,t.u=r;var n=e.o;e.o=t.o,t.o=n,e=t}this.A.t===t?this.A.t=t.h:this.A.i===t&&(this.A.i=t.h),this.R(t);var i=t.h;if(t===i.t?i.t=void 0:i.i=void 0,this._-=1,this.N.l=0,this.enableIndex)for(;i!==this.A;)i.O-=1,i=i.h}else this.clear()},t.prototype.P=function(e){for(var t="number"==typeof e?e:void 0,r="function"==typeof e?e:void 0,n=void 0===e?[]:void 0,i=0,s=this.N,o=[];o.length||s;)if(s)o.push(s),s=s.t;else{if(s=o.pop(),i===t)return s;n&&n.push(s),r&&r(s,i,this),i+=1,s=s.i}return n},t.prototype.q=function(e){for(;;){var t=e.h;if(0===t.l)return;var r=t.h;if(t===r.t){if((n=r.i)&&1===n.l){if(n.l=t.l=0,r===this.N)return;r.l=1,e=r;continue}if(e!==t.i)return t.l=0,r===this.N?this.N=r.I():r.I(),void(r.l=1);e.l=0,e.t&&(e.t.h=t),e.i&&(e.i.h=r),t.i=e.t,r.t=e.i,e.t=t,e.i=r,r===this.N?(this.N=e,this.A.h=e):(i=r.h).t===r?i.t=e:i.i=e,e.h=r.h,t.h=e,r.h=e,r.l=1}else{var n,i;if((n=r.t)&&1===n.l){if(n.l=t.l=0,r===this.N)return;r.l=1,e=r;continue}if(e!==t.t)return t.l=0,r===this.N?this.N=r.T():r.T(),void(r.l=1);e.l=0,e.t&&(e.t.h=r),e.i&&(e.i.h=t),r.i=e.t,t.t=e.i,e.t=r,e.i=t,r===this.N?(this.N=e,this.A.h=e):(i=r.h).t===r?i.t=e:i.i=e,e.h=r.h,t.h=e,r.h=e,r.l=1}return void(this.enableIndex&&(t.M(),r.M(),e.M()))}},t.prototype.D=function(e,t,r){if(void 0===this.N)return this._+=1,this.N=new this.S(e,t,0),this.N.h=this.A,this.A.h=this.A.t=this.A.i=this.N,this._;var n,i=this.A.t,s=this.g(i.u,e);if(0===s)return i.o=t,this._;if(s>0)i.t=new this.S(e,t),i.t.h=i,n=i.t,this.A.t=n;else{var o=this.A.i,a=this.g(o.u,e);if(0===a)return o.o=t,this._;if(a<0)o.i=new this.S(e,t),o.i.h=o,n=o.i,this.A.i=n;else{if(void 0!==r){var c=r.C;if(c!==this.A){var u=this.g(c.u,e);if(0===u)return c.o=t,this._;if(u>0){var l=c.v(),h=this.g(l.u,e);if(0===h)return l.o=t,this._;h<0&&(n=new this.S(e,t),void 0===l.i?(l.i=n,n.h=l):(c.t=n,n.h=c))}}}if(void 0===n)for(n=this.N;;){var d=this.g(n.u,e);if(d>0){if(void 0===n.t){n.t=new this.S(e,t),n.t.h=n,n=n.t;break}n=n.t}else{if(!(d<0))return n.o=t,this._;if(void 0===n.i){n.i=new this.S(e,t),n.i.h=n,n=n.i;break}n=n.i}}}}if(this.enableIndex)for(var f=n.h;f!==this.A;)f.O+=1,f=f.h;return this.q(n),this._+=1,this._},t.prototype.F=function(e,t){for(;e;){var r=this.g(e.u,t);if(r<0)e=e.i;else{if(!(r>0))return e;e=e.t}}return e||this.A},t.prototype.clear=function(){this._=0,this.N=void 0,this.A.h=void 0,this.A.t=this.A.i=void 0},t.prototype.updateKeyByIterator=function(e,t){var r=e.C;if(r===this.A&&DU(),1===this._)return r.u=t,!0;var n=r.p().u;if(r===this.A.t)return this.g(n,t)>0&&(r.u=t,!0);var i=r.v().u;return r===this.A.i?this.g(i,t)<0&&(r.u=t,!0):!(this.g(i,t)>=0||this.g(n,t)<=0)&&(r.u=t,!0)},t.prototype.eraseElementByPos=function(e){if(e<0||e>this._-1)throw new RangeError;var t=this.P(e);return this.G(t),this._},t.prototype.eraseElementByKey=function(e){if(0===this._)return!1;var t=this.F(this.N,e);return t!==this.A&&(this.G(t),!0)},t.prototype.eraseElementByIterator=function(e){var t=e.C;t===this.A&&DU();var r=void 0===t.i;return 0===e.iteratorType?r&&e.next():r&&void 0!==t.t||e.next(),this.G(t),e},t.prototype.getHeight=function(){if(0===this._)return 0;return function e(t){return t?Math.max(e(t.t),e(t.i))+1:0}(this.N)},t}(OU),UU=function(e){function t(t,r,n){var i=e.call(this,n)||this;return i.C=t,i.A=r,0===i.iteratorType?(i.pre=function(){return this.C===this.A.t&&DU(),this.C=this.C.v(),this},i.next=function(){return this.C===this.A&&DU(),this.C=this.C.p(),this}):(i.pre=function(){return this.C===this.A.i&&DU(),this.C=this.C.p(),this},i.next=function(){return this.C===this.A&&DU(),this.C=this.C.v(),this}),i}return _U(t,e),Object.defineProperty(t.prototype,"index",{get:function(){var e=this.C,t=this.A.h;if(e===this.A)return t?t.O-1:0;var r=0;for(e.t&&(r+=e.t.O);e!==t;){var n=e.h;e===n.i&&(r+=1,n.t&&(r+=n.t.O)),e=n}return r},enumerable:!1,configurable:!0}),t.prototype.isAccessible=function(){return this.C!==this.A},t}(xU),jU=function(e){function t(t,r,n,i){var s=e.call(this,t,r,i)||this;return s.container=n,s}return _U(t,e),Object.defineProperty(t.prototype,"pointer",{get:function(){this.C===this.A&&DU();var e=this;return new Proxy([],{get:function(t,r){return"0"===r?e.C.u:"1"===r?e.C.o:(t[0]=e.C.u,t[1]=e.C.o,t[r])},set:function(t,r,n){if("1"!==r)throw new TypeError("prop must be 1");return e.C.o=n,!0}})},enumerable:!1,configurable:!0}),t.prototype.copy=function(){return new t(this.C,this.A,this.container,this.iteratorType)},t}(UU),qU=function(e){function t(t,r,n){void 0===t&&(t=[]);var i=e.call(this,r,n)||this,s=i;return t.forEach((function(e){s.setElement(e[0],e[1])})),i}return _U(t,e),t.prototype.begin=function(){return new jU(this.A.t||this.A,this.A,this)},t.prototype.end=function(){return new jU(this.A,this.A,this)},t.prototype.rBegin=function(){return new jU(this.A.i||this.A,this.A,this,1)},t.prototype.rEnd=function(){return new jU(this.A,this.A,this,1)},t.prototype.front=function(){if(0!==this._){var e=this.A.t;return[e.u,e.o]}},t.prototype.back=function(){if(0!==this._){var e=this.A.i;return[e.u,e.o]}},t.prototype.lowerBound=function(e){var t=this.m(this.N,e);return new jU(t,this.A,this)},t.prototype.upperBound=function(e){var t=this.B(this.N,e);return new jU(t,this.A,this)},t.prototype.reverseLowerBound=function(e){var t=this.j(this.N,e);return new jU(t,this.A,this)},t.prototype.reverseUpperBound=function(e){var t=this.k(this.N,e);return new jU(t,this.A,this)},t.prototype.forEach=function(e){this.P((function(t,r,n){e([t.u,t.o],r,n)}))},t.prototype.setElement=function(e,t,r){return this.D(e,t,r)},t.prototype.getElementByPos=function(e){if(e<0||e>this._-1)throw new RangeError;var t=this.P(e);return[t.u,t.o]},t.prototype.find=function(e){var t=this.F(this.N,e);return new jU(t,this.A,this)},t.prototype.getElementByKey=function(e){return this.F(this.N,e).o},t.prototype.union=function(e){var t=this;return e.forEach((function(e){t.setElement(e[0],e[1])})),this._},t.prototype[Symbol.iterator]=function(){var e,t,r,n;return function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}}(this,(function(i){switch(i.label){case 0:e=this._,t=this.P(),r=0,i.label=1;case 1:return r<e?[4,[(n=t[r]).u,n.o]]:[3,4];case 2:i.sent(),i.label=3;case 3:return++r,[3,1];case 4:return[2]}}))},t}(FU);function zU(){if(LU)return BU;return LU=1,BU=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0},BU}var KU,GU,VU,HU,$U,WU,JU,QU,ZU=n(zU());function YU(){if(HU)return VU;HU=1;var e=Jc(),t=Hc(),r=(GU||(GU=1,KU=function(e,t,r,n){for(var i=r-1,s=e.length;++i<s;)if(n(e[i],t))return i;return-1}),KU),n=Qc(),i=Th(),s=Array.prototype.splice;return VU=function(o,a,c,u){var l=u?r:t,h=-1,d=a.length,f=o;for(o===a&&(a=i(a)),c&&(f=e(o,n(c)));++h<d;)for(var p=0,g=a[h],m=c?c(g):g;(p=l(f,m,p,u))>-1;)f!==o&&s.call(f,p,1),s.call(o,p,1);return o},VU}var XU=function(){if(QU)return JU;QU=1;var e=nu(),t=function(){if(WU)return $U;WU=1;var e=YU();return $U=function(t,r){return t&&t.length&&r&&r.length?e(t,r):t},$U}(),r=e(t);return JU=r}(),ej=n(XU);const tj="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,rj=new Set,nj="object"==typeof process&&process?process:{},ij=(e,t,r,n)=>{"function"==typeof nj.emitWarning?nj.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)};let sj=globalThis.AbortController,oj=globalThis.AbortSignal;if(void 0===sj){oj=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},sj=class{constructor(){t()}signal=new oj;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==nj.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,ij("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}const aj=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),cj=e=>aj(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?uj:null:null;class uj extends Array{constructor(e){super(e),this.fill(0)}}class lj{heap;length;static#Lt=!1;static create(e){const t=cj(e);if(!t)return[];lj.#Lt=!0;const r=new lj(e,t);return lj.#Lt=!1,r}constructor(e,t){if(!lj.#Lt)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class hj{#Ft;#Ut;#jt;#qt;#zt;#Kt;#Gt;#Vt;get perf(){return this.#Vt}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#Ht;#$t;#Wt;#Jt;#Qt;#Zt;#Yt;#Xt;#er;#tr;#rr;#nr;#ir;#sr;#or;#ar;#cr;#ur;static unsafeExposeInternals(e){return{starts:e.#ir,ttls:e.#sr,sizes:e.#nr,keyMap:e.#Wt,keyList:e.#Jt,valList:e.#Qt,next:e.#Zt,prev:e.#Yt,get head(){return e.#Xt},get tail(){return e.#er},free:e.#tr,isBackgroundFetch:t=>e.#lr(t),backgroundFetch:(t,r,n,i)=>e.#hr(t,r,n,i),moveToTail:t=>e.#dr(t),indexes:t=>e.#fr(t),rindexes:t=>e.#pr(t),isStale:t=>e.#gr(t)}}get max(){return this.#Ft}get maxSize(){return this.#Ut}get calculatedSize(){return this.#$t}get size(){return this.#Ht}get fetchMethod(){return this.#Kt}get memoMethod(){return this.#Gt}get dispose(){return this.#jt}get onInsert(){return this.#qt}get disposeAfter(){return this.#zt}constructor(e){const{max:t=0,ttl:r,ttlResolution:n=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:o,allowStale:a,dispose:c,onInsert:u,disposeAfter:l,noDisposeOnSet:h,noUpdateTTL:d,maxSize:f=0,maxEntrySize:p=0,sizeCalculation:g,fetchMethod:m,memoMethod:y,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:E,ignoreFetchAbort:A,perf:S}=e;if(void 0!==S&&"function"!=typeof S?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#Vt=S??tj,0!==t&&!aj(t))throw new TypeError("max option must be a nonnegative integer");const k=t?cj(t):Array;if(!k)throw new Error("invalid max value: "+t);if(this.#Ft=t,this.#Ut=f,this.maxEntrySize=p||this.#Ut,this.sizeCalculation=g,this.sizeCalculation){if(!this.#Ut&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==y&&"function"!=typeof y)throw new TypeError("memoMethod must be a function if defined");if(this.#Gt=y,void 0!==m&&"function"!=typeof m)throw new TypeError("fetchMethod must be a function if specified");if(this.#Kt=m,this.#ar=!!m,this.#Wt=new Map,this.#Jt=new Array(t).fill(void 0),this.#Qt=new Array(t).fill(void 0),this.#Zt=new k(t),this.#Yt=new k(t),this.#Xt=0,this.#er=0,this.#tr=lj.create(t),this.#Ht=0,this.#$t=0,"function"==typeof c&&(this.#jt=c),"function"==typeof u&&(this.#qt=u),"function"==typeof l?(this.#zt=l,this.#rr=[]):(this.#zt=void 0,this.#rr=void 0),this.#or=!!this.#jt,this.#ur=!!this.#qt,this.#cr=!!this.#zt,this.noDisposeOnSet=!!h,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!v,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!A,0!==this.maxEntrySize){if(0!==this.#Ut&&!aj(this.#Ut))throw new TypeError("maxSize must be a positive integer if specified");if(!aj(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#mr()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!o,this.ttlResolution=aj(n)||0===n?n:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!aj(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#yr()}if(0===this.#Ft&&0===this.ttl&&0===this.#Ut)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Ft&&!this.#Ut){const e="LRU_CACHE_UNBOUNDED";if((e=>!rj.has(e))(e)){rj.add(e);ij("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,hj)}}}getRemainingTTL(e){return this.#Wt.has(e)?1/0:0}#yr(){const e=new uj(this.#Ft),t=new uj(this.#Ft);this.#sr=e,this.#ir=t,this.#br=(r,n,i=this.#Vt.now())=>{if(t[r]=0!==n?i:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout((()=>{this.#gr(r)&&this.#wr(this.#Jt[r],"expire")}),n+1);e.unref&&e.unref()}},this.#vr=r=>{t[r]=0!==e[r]?this.#Vt.now():0},this.#Er=(i,s)=>{if(e[s]){const o=e[s],a=t[s];if(!o||!a)return;i.ttl=o,i.start=a,i.now=r||n();const c=i.now-a;i.remainingTTL=o-c}};let r=0;const n=()=>{const e=this.#Vt.now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>r=0),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{const s=this.#Wt.get(i);if(void 0===s)return 0;const o=e[s],a=t[s];if(!o||!a)return 1/0;return o-((r||n())-a)},this.#gr=i=>{const s=t[i],o=e[i];return!!o&&!!s&&(r||n())-s>o}}#vr=()=>{};#Er=()=>{};#br=()=>{};#gr=()=>!1;#mr(){const e=new uj(this.#Ft);this.#$t=0,this.#nr=e,this.#Ar=t=>{this.#$t-=e[t],e[t]=0},this.#Sr=(e,t,r,n)=>{if(this.#lr(t))return 0;if(!aj(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!aj(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r},this.#kr=(t,r,n)=>{if(e[t]=r,this.#Ut){const r=this.#Ut-e[t];for(;this.#$t>r;)this.#Rr(!0)}this.#$t+=e[t],n&&(n.entrySize=r,n.totalCalculatedSize=this.#$t)}}#Ar=e=>{};#kr=(e,t,r)=>{};#Sr=(e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#fr({allowStale:e=this.allowStale}={}){if(this.#Ht)for(let t=this.#er;this.#Cr(t)&&(!e&&this.#gr(t)||(yield t),t!==this.#Xt);)t=this.#Yt[t]}*#pr({allowStale:e=this.allowStale}={}){if(this.#Ht)for(let t=this.#Xt;this.#Cr(t)&&(!e&&this.#gr(t)||(yield t),t!==this.#er);)t=this.#Zt[t]}#Cr(e){return void 0!==e&&this.#Wt.get(this.#Jt[e])===e}*entries(){for(const e of this.#fr())void 0===this.#Qt[e]||void 0===this.#Jt[e]||this.#lr(this.#Qt[e])||(yield[this.#Jt[e],this.#Qt[e]])}*rentries(){for(const e of this.#pr())void 0===this.#Qt[e]||void 0===this.#Jt[e]||this.#lr(this.#Qt[e])||(yield[this.#Jt[e],this.#Qt[e]])}*keys(){for(const e of this.#fr()){const t=this.#Jt[e];void 0===t||this.#lr(this.#Qt[e])||(yield t)}}*rkeys(){for(const e of this.#pr()){const t=this.#Jt[e];void 0===t||this.#lr(this.#Qt[e])||(yield t)}}*values(){for(const e of this.#fr()){void 0===this.#Qt[e]||this.#lr(this.#Qt[e])||(yield this.#Qt[e])}}*rvalues(){for(const e of this.#pr()){void 0===this.#Qt[e]||this.#lr(this.#Qt[e])||(yield this.#Qt[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const r of this.#fr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;if(void 0!==i&&e(i,this.#Jt[r],this))return this.get(this.#Jt[r],t)}}forEach(e,t=this){for(const r of this.#fr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#Jt[r],this)}}rforEach(e,t=this){for(const r of this.#pr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#Jt[r],this)}}purgeStale(){let e=!1;for(const t of this.#pr({allowStale:!0}))this.#gr(t)&&(this.#wr(this.#Jt[t],"expire"),e=!0);return e}info(e){const t=this.#Wt.get(e);if(void 0===t)return;const r=this.#Qt[t],n=this.#lr(r)?r.__staleWhileFetching:r;if(void 0===n)return;const i={value:n};if(this.#sr&&this.#ir){const e=this.#sr[t],r=this.#ir[t];if(e&&r){const t=e-(this.#Vt.now()-r);i.ttl=t,i.start=Date.now()}}return this.#nr&&(i.size=this.#nr[t]),i}dump(){const e=[];for(const t of this.#fr({allowStale:!0})){const r=this.#Jt[t],n=this.#Qt[t],i=this.#lr(n)?n.__staleWhileFetching:n;if(void 0===i||void 0===r)continue;const s={value:i};if(this.#sr&&this.#ir){s.ttl=this.#sr[t];const e=this.#Vt.now()-this.#ir[t];s.start=Math.floor(Date.now()-e)}this.#nr&&(s.size=this.#nr[t]),e.unshift([r,s])}return e}load(e){this.clear();for(const[t,r]of e){if(r.start){const e=Date.now()-r.start;r.start=this.#Vt.now()-e}this.set(t,r.value,r)}}set(e,t,r={}){if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:a}=r;let{noUpdateTTL:c=this.noUpdateTTL}=r;const u=this.#Sr(e,t,r.size||0,o);if(this.maxEntrySize&&u>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#wr(e,"set"),this;let l=0===this.#Ht?void 0:this.#Wt.get(e);if(void 0===l)l=0===this.#Ht?this.#er:0!==this.#tr.length?this.#tr.pop():this.#Ht===this.#Ft?this.#Rr(!1):this.#Ht,this.#Jt[l]=e,this.#Qt[l]=t,this.#Wt.set(e,l),this.#Zt[this.#er]=l,this.#Yt[l]=this.#er,this.#er=l,this.#Ht++,this.#kr(l,u,a),a&&(a.set="add"),c=!1,this.#ur&&this.#qt?.(t,e,"add");else{this.#dr(l);const r=this.#Qt[l];if(t!==r){if(this.#ar&&this.#lr(r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||s||(this.#or&&this.#jt?.(t,e,"set"),this.#cr&&this.#rr?.push([t,e,"set"]))}else s||(this.#or&&this.#jt?.(r,e,"set"),this.#cr&&this.#rr?.push([r,e,"set"]));if(this.#Ar(l),this.#kr(l,u,a),this.#Qt[l]=t,a){a.set="replace";const e=r&&this.#lr(r)?r.__staleWhileFetching:r;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update");this.#ur&&this.onInsert?.(t,e,t===r?"update":"replace")}if(0===n||this.#sr||this.#yr(),this.#sr&&(c||this.#br(l,n,i),a&&this.#Er(a,l)),!s&&this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}return this}pop(){try{for(;this.#Ht;){const e=this.#Qt[this.#Xt];if(this.#Rr(!0),this.#lr(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}}}#Rr(e){const t=this.#Xt,r=this.#Jt[t],n=this.#Qt[t];return this.#ar&&this.#lr(n)?n.__abortController.abort(new Error("evicted")):(this.#or||this.#cr)&&(this.#or&&this.#jt?.(n,r,"evict"),this.#cr&&this.#rr?.push([n,r,"evict"])),this.#Ar(t),e&&(this.#Jt[t]=void 0,this.#Qt[t]=void 0,this.#tr.push(t)),1===this.#Ht?(this.#Xt=this.#er=0,this.#tr.length=0):this.#Xt=this.#Zt[t],this.#Wt.delete(r),this.#Ht--,t}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,i=this.#Wt.get(e);if(void 0!==i){const e=this.#Qt[i];if(this.#lr(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#gr(i))return r&&this.#vr(i),n&&(n.has="hit",this.#Er(n,i)),!0;n&&(n.has="stale",this.#Er(n,i))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=this.#Wt.get(e);if(void 0===n||!r&&this.#gr(n))return;const i=this.#Qt[n];return this.#lr(i)?i.__staleWhileFetching:i}#hr(e,t,r,n){const i=void 0===t?void 0:this.#Qt[t];if(this.#lr(i))return i;const s=new sj,{signal:o}=r;o?.addEventListener("abort",(()=>s.abort(o.reason)),{signal:s.signal});const a={signal:s.signal,options:r,context:n},c=(n,i=!1)=>{const{aborted:o}=s.signal,c=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(o&&!i?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,c&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),o&&!c&&!i)return u(s.signal.reason);const h=l,d=this.#Qt[t];return(d===l||c&&i&&void 0===d)&&(void 0===n?void 0!==h.__staleWhileFetching?this.#Qt[t]=h.__staleWhileFetching:this.#wr(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,a.options))),n},u=n=>{const{aborted:i}=s.signal,o=i&&r.allowStaleOnFetchAbort,a=o||r.allowStaleOnFetchRejection,c=a||r.noDeleteOnFetchRejection,u=l;if(this.#Qt[t]===l){!c||void 0===u.__staleWhileFetching?this.#wr(e,"fetch"):o||(this.#Qt[t]=u.__staleWhileFetching)}if(a)return r.status&&void 0!==u.__staleWhileFetching&&(r.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw n};r.status&&(r.status.fetchDispatched=!0);const l=new Promise(((t,n)=>{const o=this.#Kt?.(e,i,a);o&&o instanceof Promise&&o.then((e=>t(void 0===e?void 0:e)),n),s.signal.addEventListener("abort",(()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))}))})).then(c,(e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e)))),h=Object.assign(l,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,h,{...a.options,status:void 0}),t=this.#Wt.get(e)):this.#Qt[t]=h,h}#lr(e){if(!this.#ar)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof sj}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:p,forceRefresh:g=!1,status:m,signal:y}=t;if(!this.#ar)return m&&(m.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,status:m});const b={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:o,size:a,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:f,ignoreFetchAbort:d,status:m,signal:y};let w=this.#Wt.get(e);if(void 0===w){m&&(m.fetch="miss");const t=this.#hr(e,w,b,p);return t.__returned=t}{const t=this.#Qt[w];if(this.#lr(t)){const e=r&&void 0!==t.__staleWhileFetching;return m&&(m.fetch="inflight",e&&(m.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const i=this.#gr(w);if(!g&&!i)return m&&(m.fetch="hit"),this.#dr(w),n&&this.#vr(w),m&&this.#Er(m,w),t;const s=this.#hr(e,w,b,p),o=void 0!==s.__staleWhileFetching&&r;return m&&(m.fetch=i?"stale":"refresh",o&&i&&(m.returnedStale=!0)),o?s.__staleWhileFetching:s.__returned=s}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=this.#Gt;if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:i,...s}=t,o=this.get(e,s);if(!i&&void 0!==o)return o;const a=r(e,o,{options:s,context:n});return this.set(e,a,s),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,o=this.#Wt.get(e);if(void 0!==o){const t=this.#Qt[o],a=this.#lr(t);return s&&this.#Er(s,o),this.#gr(o)?(s&&(s.get="stale"),a?(s&&r&&void 0!==t.__staleWhileFetching&&(s.returnedStale=!0),r?t.__staleWhileFetching:void 0):(i||this.#wr(e,"expire"),s&&r&&(s.returnedStale=!0),r?t:void 0)):(s&&(s.get="hit"),a?t.__staleWhileFetching:(this.#dr(o),n&&this.#vr(o),t))}s&&(s.get="miss")}#Et(e,t){this.#Yt[t]=e,this.#Zt[e]=t}#dr(e){e!==this.#er&&(e===this.#Xt?this.#Xt=this.#Zt[e]:this.#Et(this.#Yt[e],this.#Zt[e]),this.#Et(this.#er,e),this.#er=e)}delete(e){return this.#wr(e,"delete")}#wr(e,t){let r=!1;if(0!==this.#Ht){const n=this.#Wt.get(e);if(void 0!==n)if(r=!0,1===this.#Ht)this.#Ir(t);else{this.#Ar(n);const r=this.#Qt[n];if(this.#lr(r)?r.__abortController.abort(new Error("deleted")):(this.#or||this.#cr)&&(this.#or&&this.#jt?.(r,e,t),this.#cr&&this.#rr?.push([r,e,t])),this.#Wt.delete(e),this.#Jt[n]=void 0,this.#Qt[n]=void 0,n===this.#er)this.#er=this.#Yt[n];else if(n===this.#Xt)this.#Xt=this.#Zt[n];else{const e=this.#Yt[n];this.#Zt[e]=this.#Zt[n];const t=this.#Zt[n];this.#Yt[t]=this.#Yt[n]}this.#Ht--,this.#tr.push(n)}}if(this.#cr&&this.#rr?.length){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}return r}clear(){return this.#Ir("delete")}#Ir(e){for(const t of this.#pr({allowStale:!0})){const r=this.#Qt[t];if(this.#lr(r))r.__abortController.abort(new Error("deleted"));else{const n=this.#Jt[t];this.#or&&this.#jt?.(r,n,e),this.#cr&&this.#rr?.push([r,n,e])}}if(this.#Wt.clear(),this.#Qt.fill(void 0),this.#Jt.fill(void 0),this.#sr&&this.#ir&&(this.#sr.fill(0),this.#ir.fill(0)),this.#nr&&this.#nr.fill(0),this.#Xt=0,this.#er=0,this.#tr.length=0,this.#$t=0,this.#Ht=0,this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}}}var dj,fj={exports:{}};var pj=(dj||(dj=1,function(e){var t,r,n,i=(t={km:6371,mile:3960,meter:6371e3,nmi:3440},r=function(e){return e*Math.PI/180},n=function(e,t){switch(e){case"[lat,lon]":return{latitude:t[0],longitude:t[1]};case"[lon,lat]":return{latitude:t[1],longitude:t[0]};case"{lon,lat}":return{latitude:t.lat,longitude:t.lon};case"{lat,lng}":return{latitude:t.lat,longitude:t.lng};case"geojson":return{latitude:t.geometry.coordinates[1],longitude:t.geometry.coordinates[0]};default:return t}},function(e,i,s){var o=(s=s||{}).unit in t?t[s.unit]:t.km,a=n(s.format,e),c=n(s.format,i),u=r(c.latitude-a.latitude),l=r(c.longitude-a.longitude),h=r(a.latitude),d=r(c.latitude),f=Math.sin(u/2)*Math.sin(u/2)+Math.sin(l/2)*Math.sin(l/2)*Math.cos(h)*Math.cos(d),p=2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f));return s.threshold?s.threshold>o*p:o*p});e.exports&&(e.exports=i)}(fj)),fj.exports),gj=n(pj);const mj={JFK:[100,40.639447,-73.779317],LGA:[200,40.777199,-73.872597],EWR:[300,40.692501,-74.168701],BUF:[400,42.94049835,-78.73220062],BFI:[500,47.529999,-122.302002],SEA:[600,47.449162,-122.311134],PDX:[700,45.58869934,-122.5979996],HIO:[800,45.540401,-122.949997],SMF:[900,38.69540023803711,-121.59100341796875],SFO:[1e3,37.61899948120117,-122.375],PAO:[1100,37.461101532,-122.114997864],SJC:[1200,37.362452,-121.929188],WVI:[1300,36.9356994629,-121.790000916],BUR:[1400,34.197703,-118.356378],LAX:[1500,33.942501,-118.407997],SAN:[1600,32.7336006165,-117.190002441],LAS:[1700,36.083361,-115.151817],PHX:[1800,33.435302,-112.005905],ABQ:[1900,35.040199,-106.609001],DEN:[2e3,39.861698150635,-104.672996521],SLC:[2100,40.785749,-111.979746],STP:[2200,44.93479,-93.060036],MSP:[2300,44.882,-93.221802],FSD:[2400,43.585463,-96.741152],OMA:[2500,41.3032,-95.894096],MCI:[2600,39.2976,-94.713898],OKC:[2700,35.393101,-97.6007],ADS:[2800,32.9686012268,-96.8364028931],DFW:[2900,32.896801,-97.038002],IAH:[3e3,29.984399795532227,-95.34140014648438],AUS:[3100,30.197535,-97.662015],SAT:[3200,29.533701,-98.469803],MFE:[3300,26.176141,-98.237965],HNL:[3400,21.32062,-157.924228],ANC:[3500,61.1744,-149.996002],BOS:[3600,42.3643,-71.005203],BGR:[3700,44.8074,-68.828102],YTO:[3800,43.6772,-79.6306],YYZ:[3900,43.6772,-79.6306],YOW:[4e3,45.322498,-75.669197],YUL:[4100,45.4706,-73.740799],YHZ:[4200,44.8807983398,-63.5085983276],YVR:[4300,49.193901062,-123.183998108],YYC:[4400,51.113899231,-114.019996643],YXE:[4500,52.170799255371094,-106.69999694824219],YWG:[4600,49.909999847399995,-97.2398986816],KEF:[4700,63.985001,-22.6056],DUB:[4800,53.428713,-6.262121],ORK:[4900,51.841301,-8.49111],MAN:[5e3,53.349375,-2.279521],LHR:[5100,51.4706,-.461941],LON:[5200,51.4706,-.461941],LCY:[5300,51.505299,.055278],EDI:[5400,55.950145,-3.372288],BRU:[5500,50.901402,4.48444],AMS:[5600,52.308601,4.76389],DUS:[5700,51.289501,6.76678],FRA:[5800,50.036521,8.561268],WIE:[5900,50.049800872802734,8.325400352478027],STR:[6e3,48.689899,9.22196],MUC:[6100,48.353802,11.7861],TXL:[6200,52.362247,13.500672],HAM:[6300,53.630402,9.98823],LUX:[6400,49.6233333,6.2044444],DLP:[6500,49.012798,2.55],CDG:[6600,49.012798,2.55],PAR:[6700,49.012798,2.55],BOD:[6800,44.8283,-.715556],MRS:[6900,43.438088,5.2125],LYS:[7e3,45.725556,5.081111],GVA:[7100,46.238098,6.10895],ZRH:[7200,47.458056,8.548056],MXP:[7300,45.6306,8.72811],LIN:[7400,45.445099,9.27674],FCO:[7500,41.804532,12.251998],PMO:[7600,38.175999,13.091],PRG:[7700,50.103514,14.256992],CPH:[7800,55.617900848389,12.656000137329],OSL:[7900,60.193901,11.1004],ARN:[8e3,59.651901245117,17.918600082397],BMA:[8100,59.354400634765625,17.941699981689453],GOT:[8200,57.662799835205,12.279800415039],RIX:[8300,56.923599,23.9711],TLL:[8400,59.41329956049999,24.832799911499997],HEL:[8500,60.3172,24.963301],LED:[8600,59.80030059814453,30.262500762939453],KLD:[8700,56.82469940185547,35.7577018737793],DME:[8800,55.40879821777344,37.90629959106445],SVX:[8900,56.743099212646,60.802700042725],KJA:[9e3,56.173077,92.492437],KHV:[9100,48.528338,135.188588],MSQ:[9200,53.888071,28.039964],VNO:[9300,54.634102,25.285801],WAW:[9400,52.1656990051,20.967100143399996],KBP:[9500,50.345001,30.894699],KIV:[9600,46.9277,28.931],OTP:[9700,44.572127,26.103396],IST:[9800,41.261297,28.741951],ADB:[9900,38.2924,27.157],ATH:[1e4,37.936401,23.9445],SKG:[10100,40.51928,22.970009],SOF:[10200,42.696357,23.417671],TIA:[10300,41.4147,19.7206],BEG:[10400,44.818401,20.309099],BUD:[10500,47.43018,19.262393],BTS:[10600,48.1702,17.2127],VIE:[10700,48.110298,16.5697],ZAG:[10800,45.742901,16.0688],TUN:[10900,36.851002,10.2272],AAE:[11e3,36.826781,7.81334],ALG:[11100,36.693886,3.214531],ORN:[11200,35.623901,-.621183],MAD:[11300,40.471926,-3.56264],BCN:[11400,41.2971,2.07846],LIS:[11500,38.7813,-9.13592],CMN:[11600,33.3675,-7.58997],DKR:[11700,14.7397,-17.4902],OUA:[11800,12.3532,-1.51242],ACC:[11900,5.605189800262451,-.16678600013256073],LOS:[12e3,6.5773701667785645,3.321160078048706],FIH:[12100,-4.38575,15.4446],LAD:[12200,-8.85837,13.2312],CPT:[12300,-33.9648017883,18.6016998291],DUR:[12400,-29.6144444444,31.1197222222],JNB:[12500,-26.1392,28.246],MPM:[12600,-25.920799,32.572601],GBE:[12700,-24.555201,25.9182],HRE:[12800,-17.931801,31.0928],TNR:[12900,-18.7969,47.478802],RUN:[13e3,-20.890087,55.518894],MRU:[13100,-20.430201,57.683601],DAR:[13200,-6.87811,39.202599],MBA:[13300,-4.03483,39.5942],NBO:[13400,-1.31923997402,36.9277992249],KGL:[13500,-1.96863,30.1395],JIB:[13600,11.5473,43.1595],CAI:[13700,30.111534,31.396694],TLV:[13800,32.011398,34.8867],HFA:[13900,32.80939865112305,35.04309844970703],ZDM:[14e3,31.91123,35.20756],AMM:[14100,31.7226009369,35.9931983948],BEY:[14200,33.820899963378906,35.488399505615234],LCA:[14300,34.875099,33.624901],EVN:[14400,40.1473007202,44.3959007263],TBS:[14500,41.669201,44.9547],GYD:[14600,40.467498779296875,50.04669952392578],LLK:[14700,38.757919,48.807042],EBL:[14800,36.23759841918945,43.963199615478516],ISU:[14900,35.5617485046,45.316738128699996],BGW:[15e3,33.262501,44.2346],NJF:[15100,31.989853,44.404317],XNH:[15200,30.935801,46.090099],BSR:[15300,30.549101,47.662102],KWI:[15400,29.226601,47.968899],RUH:[15500,24.9576,46.698799],DMM:[15600,26.471200942993164,49.79790115356445],JED:[15700,21.6796,39.156502],BAH:[15800,26.267295,50.63764],DOH:[15900,25.273056,51.608056],DXB:[16e3,25.2527999878,55.3643989563],FJR:[16100,25.1122,56.324001],MCT:[16200,23.593299865722656,58.284400939941406],MLE:[16300,4.191830158233643,73.52909851074219],CMB:[16400,7.180759906768799,79.88410186767578],MAA:[16500,12.990005,80.169296],BLR:[16600,13.1979,77.706299],HYD:[16700,17.231318,78.429855],NAG:[16800,21.092199,79.047203],BBI:[16900,20.244400024399997,85.8178024292],CCU:[17e3,22.654699325561523,88.44670104980469],AMD:[17100,23.0772,72.634697],BOM:[17200,19.0886993408,72.8678970337],PNQ:[17300,18.5821,73.919701],CNN:[17400,11.918614,75.547211],COK:[17500,10.152,76.401901],PAT:[17600,25.591299,85.087997],KNU:[17700,26.404301,80.410103],DEL:[17800,28.55563,77.09519],IXC:[17900,30.6735,76.788498],JSR:[18e3,23.1838,89.160797],CGP:[18100,22.249599,91.813301],DAC:[18200,23.843347,90.397783],PBH:[18300,27.4032,89.424599],KTM:[18400,27.6966,85.3591],LHE:[18500,31.521601,74.403603],ISB:[18600,33.549,72.82566],KHI:[18700,24.9065,67.160797],TAS:[18800,41.257900238,69.2811965942],ALA:[18900,43.354267,77.042828],ULN:[19e3,47.843102,106.766998],ICN:[19100,37.46910095214844,126.45099639892578],TYO:[19200,35.764702,140.386002],NRT:[19300,35.764702,140.386002],HND:[19400,35.552299,139.779999],ITM:[19500,34.785499572753906,135.43800354003906],KIX:[19600,34.427299,135.244003],FUK:[19700,33.585899353027344,130.4510040283203],OKA:[19800,26.195801,127.646004],GUM:[19900,13.4834,144.796005],CGY:[2e4,8.612203,124.456496],CEB:[20100,10.309261,123.97974],MNL:[20200,14.5086,121.019997],BWN:[20300,4.9442,114.928001],SGN:[20400,10.8188,106.652],HAN:[20500,21.221201,105.806999],PNH:[20600,11.5466,104.844002],VTE:[20700,17.988300323500003,102.56300354],MFM:[20800,22.149599,113.592003],HKG:[20900,22.308901,113.915001],KHH:[21e3,22.577101,120.349998],TPE:[21100,25.0777,121.233002],FOC:[21200,25.934669,119.66318],HYN:[21300,28.562201,121.429001],HGH:[21400,30.23609,120.428865],SHA:[21500,31.198104,121.33426],CZX:[21600,31.919701,119.778999],WHU:[21700,31.3906,118.408997],KHN:[21800,28.864815,115.90271],CGD:[21900,28.9189,111.639999],KWE:[22e3,26.541466,106.803331],KMG:[22100,25.110313,102.936743],LHW:[22200,36.515202,103.620003],ZHY:[22300,37.573125,105.154454],SJW:[22400,38.280701,114.696999],PKX:[22500,39.509945,116.41092],BJS:[22600,40.080101013183594,116.58499908447266],TSN:[22700,39.124401092499994,117.346000671],TNA:[22800,36.857201,117.216003],TAO:[22900,36.361953,120.088171],HAK:[23e3,19.9349,110.459],FUO:[23100,23.0833,113.07],ZGN:[23200,23.392401,113.299004],CAN:[23300,23.392401,113.299004],SZX:[23400,22.639299,113.810997],MDL:[23500,21.702199935913086,95.97789764404297],RGN:[23600,16.907300949099998,96.1332015991],CNX:[23700,18.766799926799997,98.962600708],BKK:[23800,13.681099891662598,100.74700164794922],URT:[23900,9.13259983063,99.135597229],KUL:[24e3,2.74558,101.709999],JHB:[24100,1.64131,103.669998],QPG:[24200,1.36042,103.910004],SIN:[24300,1.35019,103.994003],CGK:[24400,-6.1255698204,106.65599823],JOG:[24500,-7.78818,110.431999],DPS:[24600,-8.74817,115.167],DEX:[24700,-4.8557,139.482006],PER:[24800,-31.94029998779297,115.96700286865234],ADL:[24900,-34.947512,138.533393],MEL:[25e3,-37.673302,144.843002],HBA:[25100,-42.836101532,147.509994507],CBR:[25200,-35.3069,149.195007],SYD:[25300,-33.94609832763672,151.177001953125],BNE:[25400,-27.384199142456055,153.11700439453125],CHC:[25500,-43.48939895629883,172.53199768066406],WLG:[25600,-41.3272018433,174.804992676],AKL:[25700,-37.01199,174.786331],NOU:[25800,-22.014601,166.212997],SUV:[25900,-18.04330062866211,178.5590057373047],PPT:[26e3,-17.553699,-149.606995],GDL:[26100,20.52504,-103.301557],QRO:[26200,20.6173,-100.185997],MEX:[26300,19.435433,-99.082432],GUA:[26400,14.5833,-90.527496],TGU:[26500,14.0609,-87.217201],SJO:[26600,9.99386,-84.208801],PTY:[26700,9.0713596344,-79.3834991455],MDE:[26800,6.16454,-75.4231],BOG:[26900,4.70159,-74.1469],UIO:[27e3,-.125399,-78.354306],GYE:[27100,-2.15742,-79.883598],LIM:[27200,-12.0219,-77.114305],ARI:[27300,-18.348499,-70.338699],SCL:[27400,-33.393001556396484,-70.78579711914062],COR:[27500,-31.323601,-64.208],NQN:[27600,-38.949001,-68.155701],EZE:[27700,-34.8222,-58.5358],ASU:[27800,-25.240156,-57.519227],CGB:[27900,-15.6529,-56.116699],GYN:[28e3,-16.632,-49.220699],BSB:[28100,-15.869167,-47.920834],UDI:[28200,-18.883579,-48.225936],SJP:[28300,-20.817113,-49.406963],RAO:[28400,-21.134314,-47.774053],VCP:[28500,-23.007404,-47.134502],SOD:[28600,-23.478001,-47.490002],GRU:[28700,-23.431944,-46.467778],QWJ:[28800,-23.431944,-46.467778],SJK:[28900,-23.2292,-45.8615],GIG:[29e3,-22.809999,-43.250557],CNF:[29100,-19.63571,-43.966928],CAW:[29200,-21.698299,-41.301701],VIX:[29300,-20.258,-40.285],SSA:[29400,-12.908611,-38.322498],REC:[29500,-8.125984,-34.923316],JDO:[29600,-7.21932,-39.269096],FOR:[29700,-3.775833,-38.532222],BEL:[29800,-1.379279,-48.476207],MAO:[29900,-3.03861,-60.049702],POA:[3e4,-29.994712,-51.166592],FLN:[30100,-27.670279,-48.552502],ITJ:[30200,-26.879431,-48.650979],NVT:[30300,-26.879431,-48.650979],BNU:[30400,-26.831661,-49.093569],JOI:[30500,-26.224501,-48.797401],CWB:[30600,-25.5285,-49.1758],CFC:[30700,-26.787423,-50.939942],XAP:[30800,-27.134199,-52.656601],PBM:[30900,5.45283,-55.187801],GEO:[31e3,6.49855,-58.254101],BGI:[31100,13.0746,-59.4925],GND:[31200,12.0042,-61.786201],CUR:[31300,12.1889,-68.959801],SDQ:[31400,18.42970085144,-69.668899536133],STI:[31500,19.406099319458008,-70.60469818115234],KIN:[31600,17.935699462890625,-76.7874984741211],MIA:[31700,25.79319953918457,-80.29060363769531],TPA:[31800,27.975500106811523,-82.533203125],GNV:[31900,29.6900997162,-82.2717971802],JAX:[32e3,30.49410057067871,-81.68789672851562],TLH:[32100,30.3965,-84.350304],MGM:[32200,32.300598,-86.393997],ATL:[32300,33.6367,-84.428101],PDK:[32400,33.8755989075,-84.3020019531],BNA:[32500,36.1245002746582,-86.6781997680664],MEM:[32600,35.04240036010742,-89.97669982910156],STL:[32700,38.748697,-90.370003],IND:[32800,39.7173,-86.294403],CHI:[32900,41.9786,-87.9048],ORD:[33e3,41.9786,-87.9048],DTW:[33100,42.212398529052734,-83.35340118408203],CLE:[33200,41.411701,-81.8498],PIT:[33300,40.49150085,-80.23290253],CMH:[33400,39.998001,-82.891899],LCK:[33500,39.813801,-82.927803],CLT:[33600,35.2140007019043,-80.94309997558594],RDU:[33700,35.877602,-78.787498],ORF:[33800,36.8946,-76.201202],RIC:[33900,37.50519943237305,-77.3197021484375],IAD:[34e3,38.9445,-77.455803],DCA:[34100,38.8521,-77.037697],PHL:[34200,39.87189865112305,-75.24109649658203],NYC:[34300,40.639447,-73.779317]},yj=new Bv("fetchAirportCodeFromCdn"),bj=async(e,t,r)=>(await Xv(fetch(e,{method:"HEAD"}),r)).headers.get(t),wj=async()=>{const e=2e3;try{return await(async(e,t)=>{const r=await bj(e,"X-Amz-Cf-Pop",t);if(!r||r.length<3)throw new Error("Could not get airport code from Amazon");return r.substring(0,3)})("https://d47ahk2wrqweh.cloudfront.net/cdn-location",e)}catch(e){yj.warn(e)}try{return await(async e=>{const t=await bj("https://www.fastly.com","X-Served-By",e);if(!t||t.length<3)throw new Error("Could not get airport code from Fastly");return t.substring(t.length-3)})(e)}catch(e){yj.warn(e)}try{return await(async e=>{const t=await bj("https://www.cloudflare.com","CF-RAY",e);if(!t||t.length<3)throw new Error("Could not get airport code from Cloudflare");return t.substring(t.length-3)})(e)}catch(e){yj.warn(e)}throw new Error("Could not get airport code from any CDN")},vj=new Bv("getLocalRegion");let Ej,Aj;const Sj=async()=>{let e;return e=await(async()=>{let e;try{e=await wj()}catch{return}return e})(),void 0!==e&&mj[e]?mj[e][0]:(()=>{const e=Object.keys(mj),t=e[Math.floor(Math.random()*e.length)],r=mj[t][0]+99;return vj.warn(`Could not get airport code, using random region: ${r}`),r})()};var kj,Rj,Cj={exports:{}},Ij=Cj.exports;function Pj(){return kj||(kj=1,function(e){(function(){var t,r,n,i,s,o,a,c,u,l,h,d,f,p,g;n=Math.floor,l=Math.min,r=function(e,t){return e<t?-1:e>t?1:0},u=function(e,t,i,s,o){var a;if(null==i&&(i=0),null==o&&(o=r),i<0)throw new Error("lo must be non-negative");for(null==s&&(s=e.length);i<s;)o(t,e[a=n((i+s)/2)])<0?s=a:i=a+1;return[].splice.apply(e,[i,i-i].concat(t)),t},o=function(e,t,n){return null==n&&(n=r),e.push(t),p(e,0,e.length-1,n)},s=function(e,t){var n,i;return null==t&&(t=r),n=e.pop(),e.length?(i=e[0],e[0]=n,g(e,0,t)):i=n,i},c=function(e,t,n){var i;return null==n&&(n=r),i=e[0],e[0]=t,g(e,0,n),i},a=function(e,t,n){var i;return null==n&&(n=r),e.length&&n(e[0],t)<0&&(t=(i=[e[0],t])[0],e[0]=i[1],g(e,0,n)),t},i=function(e,t){var i,s,o,a,c,u;for(null==t&&(t=r),c=[],s=0,o=(a=function(){u=[];for(var t=0,r=n(e.length/2);0<=r?t<r:t>r;0<=r?t++:t--)u.push(t);return u}.apply(this).reverse()).length;s<o;s++)i=a[s],c.push(g(e,i,t));return c},f=function(e,t,n){var i;if(null==n&&(n=r),-1!==(i=e.indexOf(t)))return p(e,0,i,n),g(e,i,n)},h=function(e,t,n){var s,o,c,u,l;if(null==n&&(n=r),!(o=e.slice(0,t)).length)return o;for(i(o,n),c=0,u=(l=e.slice(t)).length;c<u;c++)s=l[c],a(o,s,n);return o.sort(n).reverse()},d=function(e,t,n){var o,a,c,h,d,f,p,g,m;if(null==n&&(n=r),10*t<=e.length){if(!(c=e.slice(0,t).sort(n)).length)return c;for(a=c[c.length-1],h=0,f=(p=e.slice(t)).length;h<f;h++)n(o=p[h],a)<0&&(u(c,o,0,null,n),c.pop(),a=c[c.length-1]);return c}for(i(e,n),m=[],d=0,g=l(t,e.length);0<=g?d<g:d>g;0<=g?++d:--d)m.push(s(e,n));return m},p=function(e,t,n,i){var s,o,a;for(null==i&&(i=r),s=e[n];n>t&&i(s,o=e[a=n-1>>1])<0;)e[n]=o,n=a;return e[n]=s},g=function(e,t,n){var i,s,o,a,c;for(null==n&&(n=r),s=e.length,c=t,o=e[t],i=2*t+1;i<s;)(a=i+1)<s&&!(n(e[i],e[a])<0)&&(i=a),e[t]=e[i],i=2*(t=i)+1;return e[t]=o,p(e,c,t,n)},t=function(){function e(e){this.cmp=null!=e?e:r,this.nodes=[]}return e.push=o,e.pop=s,e.replace=c,e.pushpop=a,e.heapify=i,e.updateItem=f,e.nlargest=h,e.nsmallest=d,e.prototype.push=function(e){return o(this.nodes,e,this.cmp)},e.prototype.pop=function(){return s(this.nodes,this.cmp)},e.prototype.peek=function(){return this.nodes[0]},e.prototype.contains=function(e){return-1!==this.nodes.indexOf(e)},e.prototype.replace=function(e){return c(this.nodes,e,this.cmp)},e.prototype.pushpop=function(e){return a(this.nodes,e,this.cmp)},e.prototype.heapify=function(){return i(this.nodes,this.cmp)},e.prototype.updateItem=function(e){return f(this.nodes,e,this.cmp)},e.prototype.clear=function(){return this.nodes=[]},e.prototype.empty=function(){return 0===this.nodes.length},e.prototype.size=function(){return this.nodes.length},e.prototype.clone=function(){var t;return(t=new e).nodes=this.nodes.slice(0),t},e.prototype.toArray=function(){return this.nodes.slice(0)},e.prototype.insert=e.prototype.push,e.prototype.top=e.prototype.peek,e.prototype.front=e.prototype.peek,e.prototype.has=e.prototype.contains,e.prototype.copy=e.prototype.clone,e}(),e.exports=t}).call(Ij)}(Cj)),Cj.exports}Rj||(Rj=1,Pj());const Tj=(e,t)=>yL.distance(e,t),_j=e=>gw(e),Nj=e=>mw(e),Mj=e=>_j(e.nodeId),xj=(e,t)=>yw(e.nodeId,t.nodeId),Oj=()=>_j(so(20));class Dj extends Sl{options;contactsById=new Map;contactIds=[];constructor(e){super(),this.options=e,this.compareIds=this.compareIds.bind(this)}getClosestContactId(){return this.contactIds[0]}getContactIds(){return this.contactIds}addContact(e){const t=e.getNodeId();if(!this.options.excludedNodeIds?.has(t)&&!(!this.options.allowToContainReferenceId&&this.options.referenceId===t||void 0!==this.options.nodeIdDistanceLimit&&this.compareIds(this.options.nodeIdDistanceLimit,t)<0||this.contactsById.has(t)))if(void 0===this.options.maxSize||this.contactIds.length<this.options.maxSize){this.contactsById.set(t,e);const r=pL(this.contactIds,t,(e=>this.distanceToReferenceId(e)));this.contactIds.splice(r,0,t),this.hasEventListeners()&&this.emit("contactAdded",e)}else if(this.compareIds(this.contactIds[this.options.maxSize-1],t)>0){const r=this.contactIds.pop(),n=this.contactsById.get(r);this.contactsById.delete(r),this.contactsById.set(t,e);const i=pL(this.contactIds,t,(e=>this.distanceToReferenceId(e)));this.contactIds.splice(i,0,t),this.hasEventListeners()&&(this.emit("contactRemoved",n),this.emit("contactAdded",e))}}addContacts(e){e.forEach((e=>this.addContact(e)))}getContact(e){return this.contactsById.get(e)}has(e){return this.contactsById.has(e)}getClosestContacts(e){return(void 0===e?this.contactIds:this.contactIds.slice(0,Math.max(e,0))).map((e=>this.contactsById.get(e)))}getFurthestContacts(e){const t=[...this.getClosestContacts()].reverse();return void 0===e?t:t.slice(0,Math.max(e,0))}compareIds(e,t){return this.distanceToReferenceId(e)-this.distanceToReferenceId(t)}distanceToReferenceId(e){return Tj(Nj(this.options.referenceId),Nj(e))}removeContact(e){if(this.contactsById.has(e)){const t=this.contactsById.get(e),r=this.contactIds.findIndex((t=>t===e));return this.contactIds.splice(r,1),this.contactsById.delete(e),this.hasEventListeners()&&this.emit("contactRemoved",t),!0}return!1}getAllContactsInUndefinedOrder(){return this.contactsById.values()}getSize(e){let t=0;if(void 0!==e)for(const r of e)this.has(r)&&t++;return this.contactIds.length-t}clear(){this.contactsById.clear(),this.contactIds=[]}stop(){this.removeAllListeners(),this.clear()}hasEventListeners(){return this.eventNames().length>0}}class Bj{values=new Set;queue=[];maxItemCount;constructor(e){this.maxItemCount=e}add(e){if(this.values.add(e),this.queue.push(e),this.queue.length>this.maxItemCount){const e=this.queue.shift();this.values.delete(e)}}isMostLikelyDuplicate(e){return this.values.has(e)}size(){return this.values.size}clear(){this.values.clear(),this.queue=[]}}var Lj;!function(e){e.CONNECTION_FAILED="CONNECTION_FAILED",e.COULD_NOT_ROUTE="COULD_NOT_ROUTE",e.STARTING_WEBSOCKET_SERVER_FAILED="STARTING_WEBSOCKET_SERVER_FAILED",e.WEBSOCKET_CONNECTION_REQUEST_REJECTED="WEBSOCKET_CONNECTION_REQUEST_REJECTED",e.COULD_NOT_START="COULD_NOT_START",e.COULD_NOT_STOP="COULD_NOT_STOP",e.CANNOT_CONNECT_TO_SELF="CANNOT_CONNECT_TO_SELF",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.ILLEGAL_RTC_PEER_CONNECTION_STATE="ILLEGAL_RTC_PEER_CONNECTION_STATE",e.ILLEGAL_ARGUMENTS="ILLEGAL_ARGUMENTS",e.CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT="CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT",e.CONNECTION_LOCKER="CONNECTION_LOCKER",e.DHT_JOIN_TIMEOUT="DHT_JOIN_TIMEOUT",e.SEND_FAILED="SEND_FAILED",e.GETTING_DATA_FAILED="GETTING_DATA_FAILED",e.CONNECTION_NOT_OPEN="CONNECTION_NOT_OPEN"}(Lj||(Lj={}));class Fj extends Error{code;originalError;constructor(e,t,r){super(t),this.code=e,this.originalError=r}}class Uj extends Fj{constructor(e,t){super(Lj.CONNECTION_FAILED,e,t)}}class jj extends Fj{constructor(e,t){super(Lj.STARTING_WEBSOCKET_SERVER_FAILED,e,t)}}class qj extends Fj{constructor(e,t){super(Lj.COULD_NOT_START,e,t)}}class zj extends Fj{constructor(e,t){super(Lj.CANNOT_CONNECT_TO_SELF,e,t)}}class Kj extends Fj{constructor(e,t){super(Lj.CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT,e,t)}}class Gj extends Fj{constructor(e,t){super(Lj.SEND_FAILED,e,t)}}const Vj=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};const Hj=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var $j;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}($j||($j={}));const Wj=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>Hj},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",$j]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>Vj}])}};const Jj=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var Qj,Zj,Yj,Xj,eq,tq;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(Qj||(Qj={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(Zj||(Zj={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}(Yj||(Yj={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(Xj||(Xj={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(eq||(eq={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(tq||(tq={}));const rq=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>Hj},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>Jj},{no:5,name:"ttl",kind:"scalar",T:13}])}};const nq=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const iq=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>Hj}])}};const sq=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>yq}])}};const oq=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>aq}])}};const aq=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>Hj},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>Jj},{no:5,name:"storedAt",kind:"message",T:()=>Jj},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const cq=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const uq=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>yq},{no:2,name:"requestId",kind:"scalar",T:9}])}};const lq=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const hq=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>yq},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>yq},{no:3,name:"requestId",kind:"scalar",T:9}])}};const dq=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",Qj]}])}};const fq=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>yq},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>aq},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>yq}])}};const pq=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const gq=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const mq=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const yq=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",Zj]},{no:3,name:"udp",kind:"message",T:()=>bq},{no:4,name:"tcp",kind:"message",T:()=>bq},{no:5,name:"websocket",kind:"message",T:()=>bq},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const bq=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const wq=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>yq},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>Rq},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>yq},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>yq},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const vq=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",Xj]}])}};const Eq=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const Aq=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>bq},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const Sq=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>yq},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>yq},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const kq=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>yq},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",eq]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const Rq=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>yq},{no:3,name:"targetDescriptor",kind:"message",T:()=>yq},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>Wj},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>Eq},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>Aq},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>Sq},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>kq},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>dq}])}};const Cq=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const Iq=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const Pq=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const Tq=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const _q=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const Nq=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const Mq=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const xq=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const Oq=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",tq]}])}};const Dq=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const Bq=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const Lq=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>aq}])}};const Fq=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const Uq=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>yq}])}},jq=new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:cq,O:uq},{name:"getClosestRingPeers",options:{},I:lq,O:hq},{name:"ping",options:{},I:pq,O:gq},{name:"leaveNotice",options:{},I:mq,O:Vj}]),qq=new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:wq,O:vq},{name:"forwardMessage",options:{},I:wq,O:vq}]),zq=new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:wq,O:vq}]),Kq=new vF("dht.StoreRpc",[{name:"storeData",options:{},I:rq,O:nq},{name:"replicateData",options:{},I:oq,O:Vj}]),Gq=new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:fq,O:Vj}]),Vq=new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:Cq,O:Vj}]),Hq=new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:Iq,O:Vj},{name:"rtcOffer",options:{},I:Pq,O:Vj},{name:"rtcAnswer",options:{},I:Tq,O:Vj},{name:"iceCandidate",options:{},I:_q,O:Vj}]),$q=new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:Nq,O:xq},{name:"unlockRequest",options:{},I:Mq,O:Vj},{name:"gracefulDisconnect",options:{},I:Oq,O:Vj},{name:"setPrivate",options:{},I:Dq,O:Vj}]),Wq=new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:Bq,O:Lq},{name:"externalStoreData",options:{},I:iq,O:sq},{name:"externalFindClosestNodes",options:{},I:Fq,O:Uq}]);class Jq{_transport;typeName=jq.typeName;methods=jq.methods;options=jq.options;constructor(e){this._transport=e}getClosestPeers(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}getClosestRingPeers(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}ping(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}leaveNotice(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Qq{_transport;typeName=qq.typeName;methods=qq.methods;options=qq.options;constructor(e){this._transport=e}routeMessage(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}forwardMessage(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Zq{_transport;typeName=zq.typeName;methods=zq.methods;options=zq.options;constructor(e){this._transport=e}routeRequest(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Yq{_transport;typeName=Kq.typeName;methods=Kq.methods;options=Kq.options;constructor(e){this._transport=e}storeData(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}replicateData(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Xq{_transport;typeName=Gq.typeName;methods=Gq.methods;options=Gq.options;constructor(e){this._transport=e}sendResponse(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class ez{_transport;typeName=Vq.typeName;methods=Vq.methods;options=Vq.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class tz{_transport;typeName=Hq.typeName;methods=Hq.methods;options=Hq.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}rtcOffer(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}rtcAnswer(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}iceCandidate(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class rz{_transport;typeName=$q.typeName;methods=$q.methods;options=$q.options;constructor(e){this._transport=e}lockRequest(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}unlockRequest(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}gracefulDisconnect(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}setPrivate(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class nz{_transport;typeName=Wq.typeName;methods=Wq.methods;options=Wq.options;constructor(e){this._transport=e}externalFetchData(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}externalStoreData(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}externalFindClosestNodes(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}const iz={connect:!0,sendIfStopped:!1,bufferWhileConnecting:!0};class sz extends WF{targetDescriptor;sourceDescriptor;clientId;connect;sendIfStopped;bufferWhileConnecting;incomingSourceDescriptor}class oz extends nU{ownServiceId;constructor(e,t,r){super(r),this.ownServiceId=e,this.setOutgoingMessageListener(((e,r,n)=>{let i;i=n.targetDescriptor?n.targetDescriptor:n.incomingSourceDescriptor;const s={messageId:xF(),serviceId:this.ownServiceId,body:{oneofKind:"rpcMessage",rpcMessage:e},targetDescriptor:i},o=void 0!==e.header.response?{connect:!1,sendIfStopped:!0,bufferWhileConnecting:!0}:{connect:n?.connect??iz.connect,sendIfStopped:n?.sendIfStopped??iz.sendIfStopped,bufferWhileConnecting:n?.bufferWhileConnecting??iz.bufferWhileConnecting};return t(s,o)}))}handleMessageFromPeer(e){if(e.serviceId===this.ownServiceId&&"rpcMessage"===e.body.oneofKind){const t=new sz;t.incomingSourceDescriptor=e.sourceDescriptor,this.handleIncomingMessage(e.body.rpcMessage,t)}}}class az{localLocks=new Map;remoteLocks=new Map;weakLocks=new Map;remotePrivateConnections=new Set;getLocalLockedConnectionCount(){return this.localLocks.size}getRemoteLockedConnectionCount(){return this.remoteLocks.size}getWeakLockedConnectionCount(){return this.weakLocks.size}isLocalLocked(e,t){return void 0===t?this.localLocks.has(e):this.localLocks.has(e)&&this.localLocks.get(e).has(t)}isRemoteLocked(e,t){return void 0===t?this.remoteLocks.has(e):!(!this.remoteLocks.has(e)||!this.remoteLocks.get(e).has(t))}isWeakLocked(e){return this.weakLocks.has(e)}isLocked(e){return this.isLocalLocked(e)||this.isRemoteLocked(e)||this.isWeakLocked(e)}addLocalLocked(e,t){this.localLocks.has(e)||this.localLocks.set(e,new Set),this.localLocks.get(e).add(t)}addRemoteLocked(e,t){this.remoteLocks.has(e)||this.remoteLocks.set(e,new Set),this.remoteLocks.get(e).add(t)}addWeakLocked(e,t){this.weakLocks.has(e)||this.weakLocks.set(e,new Set),this.weakLocks.get(e).add(t)}removeLocalLocked(e,t){this.localLocks.has(e)&&(this.localLocks.get(e)?.delete(t),0===this.localLocks.get(e)?.size&&this.localLocks.delete(e))}removeRemoteLocked(e,t){this.remoteLocks.has(e)&&(this.remoteLocks.get(e)?.delete(t),0===this.remoteLocks.get(e)?.size&&this.remoteLocks.delete(e))}removeWeakLocked(e,t){this.weakLocks.has(e)&&(this.weakLocks.get(e)?.delete(t),0===this.weakLocks.get(e)?.size&&this.weakLocks.delete(e))}addPrivate(e){this.remotePrivateConnections.add(e)}removePrivate(e){this.remotePrivateConnections.delete(e)}getPrivateConnections(){return this.remotePrivateConnections}isPrivate(e){return this.remotePrivateConnections.has(e)}clearAllLocks(e){this.localLocks.delete(e),this.remoteLocks.delete(e),this.weakLocks.delete(e)}clear(){this.localLocks.clear(),this.remoteLocks.clear(),this.weakLocks.clear()}}const cz=e=>void 0!==e?Mj(e):"unknown",uz=()=>xF(),lz=new Bv("ManagedConnection");class hz extends Sl{connection;connectionId;remotePeerDescriptor;lastUsedTimestamp=Date.now();replacedAsDuplicate=!1;stopped=!1;openedAt=Date.now();bytesSent=0;bytesReceived=0;messagesSent=0;messagesReceived=0;constructor(e,t){super(),this.connectionId=uz(),this.connection=t,t.on("data",(e=>{this.lastUsedTimestamp=Date.now(),this.messagesReceived+=1,this.bytesReceived+=e.length,this.emit("managedData",e,this.getPeerDescriptor())})),t.on("disconnected",(e=>this.onDisconnected(e))),this.lastUsedTimestamp=Date.now(),this.remotePeerDescriptor=e}onDisconnected(e){lz.trace(cz(this.remotePeerDescriptor)+" onDisconnected() "+e),this.replacedAsDuplicate||this.emit("disconnected",e),this.removeAllListeners()}replaceAsDuplicate(){lz.trace(cz(this.remotePeerDescriptor)+" replaceAsDuplicate"),this.replacedAsDuplicate=!0}send(e){if(this.stopped)throw new Gj("ManagedConnection is stopped");this.lastUsedTimestamp=Date.now(),this.messagesSent+=1,this.bytesSent+=e.length,this.connection.send(e)}async close(e){this.stopped||(await this.connection.close(e),this.removeAllListeners())}getNodeId(){return Mj(this.remotePeerDescriptor)}getLastUsedTimestamp(){return this.lastUsedTimestamp}getPeerDescriptor(){return this.remotePeerDescriptor}getDiagnosticInfo(){return{remotePeerDescriptor:this.remotePeerDescriptor,lastUsedTimestamp:this.lastUsedTimestamp,replacedAsDuplicate:this.replacedAsDuplicate,stopped:this.stopped,openedAt:this.openedAt,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived}}}var dz;!function(e){e.WEBSOCKET_SERVER="websocket-server",e.WEBSOCKET_CLIENT="websocket-client",e.WEBRTC="webrtc",e.SIMULATOR_SERVER="simulator-server",e.SIMULATOR_CLIENT="simulator-client"}(dz||(dz={}));const fz=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8"].map((e=>hU.parseCIDR(e)));function pz(e){if(hU.IPv4.isValid(e)){const t=hU.IPv4.parse(e);for(const e of fz)if(t.match(e))return!0}return!1}const gz=e=>{const t="localhost"===e.host||pz(e.host);return e.tls||t},mz=(e,t)=>t.websocket&&(e.type!==Zj.BROWSER||gz(t.websocket))?dz.WEBSOCKET_CLIENT:e.websocket&&(t.type!==Zj.BROWSER||gz(e.websocket))?dz.WEBSOCKET_SERVER:dz.WEBRTC,yz=5e3,bz=(e,t)=>{const r=mz(e,t);return r===dz.WEBSOCKET_CLIENT?5e3:r===dz.WEBSOCKET_SERVER?7500:(dz.WEBRTC,1e4)};class wz{localPeerDescriptor;remotePeerDescriptor;client;timeout;constructor(e,t,r,n,i){this.localPeerDescriptor=e,this.remotePeerDescriptor=t,this.client=iU(new n(r.getRpcClientTransport())),this.timeout=i}getPeerDescriptor(){return this.remotePeerDescriptor}getLocalPeerDescriptor(){return this.localPeerDescriptor}getClient(){return this.client}formDhtRpcOptions(e){return{sourceDescriptor:this.localPeerDescriptor,targetDescriptor:this.remotePeerDescriptor,timeout:this.timeout??bz(this.localPeerDescriptor,this.remotePeerDescriptor),...e}}}const vz=new Bv("ConnectionLockRpcRemote");class Ez extends wz{async lockRequest(e){vz.trace(`Requesting locked connection to ${Mj(this.getPeerDescriptor())}`);const t={lockId:e},r=this.formDhtRpcOptions();try{return(await this.getClient().lockRequest(t,r)).accepted}catch(e){return vz.debug("Connection lock rejected",{err:e}),!1}}unlockRequest(e){vz.trace(`Requesting connection to be unlocked from ${Mj(this.getPeerDescriptor())}`);const t={lockId:e},r=this.formDhtRpcOptions({notification:!0});this.getClient().unlockRequest(t,r).catch((e=>{vz.trace("failed to send unlockRequest")}))}async gracefulDisconnect(e){vz.trace(`Notifying a graceful disconnect to ${Mj(this.getPeerDescriptor())}`);const t={disconnectMode:e},r=this.formDhtRpcOptions({connect:!1,sendIfStopped:!0,timeout:2e3});await this.getClient().gracefulDisconnect(t,r)}async setPrivate(e){vz.trace(`Setting isPrivate: ${e} for ${Mj(this.getPeerDescriptor())}`);const t={isPrivate:e},r=this.formDhtRpcOptions({connect:!1,notification:!0});await this.getClient().setPrivate(t,r)}}const Az=new Bv("ConnectionLockRpcLocal");class Sz{options;constructor(e){this.options=e}async lockRequest(e,t){const r=t.incomingSourceDescriptor;if(xj(r,this.options.getLocalPeerDescriptor())){return{accepted:!1}}const n=Mj(r);this.options.addRemoteLocked(n,e.lockId);return{accepted:!0}}async unlockRequest(e,t){const r=t.incomingSourceDescriptor,n=Mj(r);return this.options.removeRemoteLocked(n,e.lockId),{}}async gracefulDisconnect(e,t){const r=t.incomingSourceDescriptor;return Az.trace(cz(r)+" received gracefulDisconnect notice"),e.disconnectMode===tq.LEAVING?await this.options.closeConnection(r,!0,"graceful leave notified"):await this.options.closeConnection(r,!1,"graceful disconnect notified"),{}}async setPrivate(e,t){const r=t.incomingSourceDescriptor,n=Mj(r);return this.options.setPrivate(n,e.isPrivate),{}}}const kz=(e,t)=>Rz(e+","+t)<Rz(t+","+e)?"local":"remote",Rz=e=>_v(e).readInt32LE(0);class Cz{buffer=[];deferredPromise=new eb;push(e){return this.buffer.push(e),this.deferredPromise}getBuffer(){return this.buffer}resolve(){this.buffer.length=0,this.deferredPromise.resolve()}reject(){this.buffer.length=0,this.deferredPromise.reject(new Gj("Could not send buffered messages"))}}var Iz;!function(e){e.OPEN_INTERNET="open_internet",e.UNKNOWN="unknown"}(Iz||(Iz={}));const Pz=new Bv("ConnectionManager");var Tz;!function(e){e.IDLE="idle",e.RUNNING="running",e.STOPPING="stopping",e.STOPPED="stopped"}(Tz||(Tz={}));const _z="system/connection-manager";class Nz extends Sl{options;metricsContext;duplicateMessageDetector=new Bj(1e4);metrics;locks=new az;endpoints=new Map;connectorFacade;rpcCommunicator;disconnectorIntervalRef;state=Tz.IDLE;privateClientMode=!1;constructor(e){super(),this.options=e,this.onData=this.onData.bind(this),this.send=this.send.bind(this),this.onNewConnection=this.onNewConnection.bind(this),this.metricsContext=this.options.metricsContext??new $v,this.metrics={sendMessagesPerSecond:new Hv,sendBytesPerSecond:new Hv,receiveMessagesPerSecond:new Hv,receiveBytesPerSecond:new Hv,connectionAverageCount:new Gv(0),connectionTotalFailureCount:new qv},this.metricsContext.addMetrics("node",this.metrics),this.connectorFacade=this.options.createConnectorFacade(),this.send=this.send.bind(this),this.rpcCommunicator=new oz(_z,this.send,{rpcRequestTimeout:1e4});const t=new Sz({addRemoteLocked:(e,t)=>this.locks.addRemoteLocked(e,t),removeRemoteLocked:(e,t)=>this.locks.removeRemoteLocked(e,t),closeConnection:(e,t,r)=>this.closeConnection(e,t,r),getLocalPeerDescriptor:()=>this.getLocalPeerDescriptor(),setPrivate:(e,t)=>{this.options.allowIncomingPrivateConnections?t?this.locks.addPrivate(e):this.locks.removePrivate(e):Pz.debug(`node ${e} attemted to set a connection as private, but it is not allowed`)}});this.rpcCommunicator.registerRpcMethod(Nq,xq,"lockRequest",((e,r)=>t.lockRequest(e,r))),this.rpcCommunicator.registerRpcNotification(Mq,"unlockRequest",((e,r)=>t.unlockRequest(e,r))),this.rpcCommunicator.registerRpcNotification(Oq,"gracefulDisconnect",((e,r)=>t.gracefulDisconnect(e,r))),this.rpcCommunicator.registerRpcNotification(Dq,"setPrivate",((e,r)=>t.setPrivate(e,r)))}garbageCollectConnections(e,t){if(this.endpoints.size<=e)return;const r=new Dj({referenceId:Mj(this.getLocalPeerDescriptor()),maxSize:1e5,allowToContainReferenceId:!1});this.endpoints.forEach((e=>{if(e.connected){const n=e.connection,i=n.getNodeId();!this.locks.isLocked(i)&&!this.locks.isPrivate(i)&&Date.now()-n.getLastUsedTimestamp()>t&&(Pz.trace("disconnecting in timeout interval: "+cz(n.getPeerDescriptor())),r.addContact(n))}}));const n=r.getFurthestContacts(this.endpoints.size-e);for(const e of n){const t=e.getPeerDescriptor();Pz.trace("garbageCollecting "+Mj(t)),this.gracefullyDisconnectAsync(t,tq.NORMAL).catch((e=>{}))}}async start(){if(this.state===Tz.RUNNING||this.state===Tz.STOPPED)throw new qj(`Cannot start already ${this.state} module`);this.state=Tz.RUNNING,Pz.trace("Starting ConnectionManager..."),await this.connectorFacade.start((e=>this.onNewConnection(e)),(e=>this.hasConnection(e)),this),this.disconnectorIntervalRef=setInterval((()=>{Pz.trace("disconnectorInterval");this.garbageCollectConnections(this.options.maxConnections??80,2e4)}),5e3)}async stop(){this.state!==Tz.STOPPED&&this.state!==Tz.STOPPING&&(this.state=Tz.STOPPING,Pz.trace("Stopping ConnectionManager"),this.disconnectorIntervalRef&&clearInterval(this.disconnectorIntervalRef),await Promise.all(Array.from(this.endpoints.values()).map((async e=>{if(e.connected)try{await this.gracefullyDisconnectAsync(e.connection.getPeerDescriptor(),tq.LEAVING)}catch(e){Pz.error(e)}else{const t=e.connection;Pz.trace("handshake of connection not completed, force-closing");const r=eE(t,"disconnected",2e3);t.close(!0);try{await r,Pz.trace("resolving after receiving disconnected event from non-handshaked connection")}catch(t){e.buffer.reject(),Pz.trace("force-closing non-handshaked connection timed out "+t)}}}))),await this.connectorFacade.stop(),this.state=Tz.STOPPED,this.rpcCommunicator.stop(),this.duplicateMessageDetector.clear(),this.locks.clear(),this.removeAllListeners())}getLocalLockedConnectionCount(){return this.locks.getLocalLockedConnectionCount()}getRemoteLockedConnectionCount(){return this.locks.getRemoteLockedConnectionCount()}getWeakLockedConnectionCount(){return this.locks.getWeakLockedConnectionCount()}async send(e,t=iz){if((this.state===Tz.STOPPED||this.state===Tz.STOPPING)&&!t.sendIfStopped)return;const r=e.targetDescriptor;if(this.isConnectionToSelf(r))throw new zj("Cannot send to self");const n=Mj(r);Pz.trace(`Sending message to: ${n}`),e={...e,sourceDescriptor:this.getLocalPeerDescriptor()};let i=this.endpoints.get(n)?.connection;if(!i&&t.connect)i=this.connectorFacade.createConnection(r),this.onNewConnection(i);else if(!i||i&&!this.endpoints.get(n).connected&&!t.connect)throw new Gj("No connection to target, connect flag is false");const s=Rq.toBinary(e);if(this.metrics.sendBytesPerSecond.record(s.byteLength),this.metrics.sendMessagesPerSecond.record(1),this.endpoints.get(n).connected)i.send(s);else if(t.bufferWhileConnecting)return this.endpoints.get(n).buffer.push(s)}isConnectionToSelf(e){return xj(e,this.getLocalPeerDescriptor())||this.isOwnWebsocketServer(e)}isOwnWebsocketServer(e){const t=this.getLocalPeerDescriptor();return void 0!==e.websocket&&void 0!==t.websocket&&(e.websocket.port===t.websocket.port&&e.websocket.host===t.websocket.host)}getLocalPeerDescriptor(){return this.connectorFacade.getLocalPeerDescriptor()}hasConnection(e){return this.getConnections().some((t=>Mj(t)==e))}getConnectionCount(){return this.getConnections().length}hasLocalLockedConnection(e){return this.locks.isLocalLocked(e)}hasRemoteLockedConnection(e){return this.locks.isRemoteLocked(e)}handleMessage(e){const t=e.body.oneofKind;Pz.trace("Received message of type "+t),"rpcMessage"===t?this.duplicateMessageDetector.isMostLikelyDuplicate(e.messageId)?Pz.trace("handleMessage filtered duplicate "+Mj(e.sourceDescriptor)+" "+e.serviceId+" "+e.messageId):(this.duplicateMessageDetector.add(e.messageId),e.serviceId===_z?this.rpcCommunicator?.handleMessageFromPeer(e):(Pz.trace('emit "message" '+Mj(e.sourceDescriptor)+" "+e.serviceId+" "+e.messageId),this.emit("message",e))):Pz.trace("Filtered out non-RPC message of type "+t)}onData(e,t){if(this.state===Tz.STOPPED)return;let r;this.metrics.receiveBytesPerSecond.record(e.byteLength),this.metrics.receiveMessagesPerSecond.record(1);try{r=Rq.fromBinary(e)}catch(e){return void Pz.debug(`Parsing incoming data into Message failed: ${e}`)}r.sourceDescriptor=t;try{this.handleMessage(r)}catch(e){Pz.debug(`Handling incoming data failed: ${e}`)}}onConnected(e,t){const r=new hz(e,t);r.on("managedData",this.onData),r.once("disconnected",(t=>this.onDisconnected(e,t)));const n=Mj(e),i=this.endpoints.get(n),s=i.buffer,o=i.connection,a=s.getBuffer();for(;a.length>0;)Pz.trace("emptying buffer"),r.send(a.shift());s.resolve(),o.destroy(),this.endpoints.set(n,{connected:!0,connection:r}),this.privateClientMode&&this.setPrivateForConnection(e,this.privateClientMode).catch((()=>{})),this.emit("connected",e),this.onConnectionCountChange()}onDisconnected(e,t){const r=Mj(e);Pz.trace(r+" onDisconnected() gracefulLeave: "+t);const n=this.endpoints.get(r);n&&(this.locks.clearAllLocks(r),!1===n.connected&&n.buffer.reject(),this.endpoints.delete(r),Pz.trace(r+" deleted connection in onDisconnected() gracefulLeave: "+t),this.emit("disconnected",e,t),this.onConnectionCountChange())}onNewConnection(e){return this.state!==Tz.STOPPED&&(Pz.trace("onNewConnection()"),!!this.acceptNewConnection(e)&&(e.once("connected",((e,t)=>this.onConnected(e,t))),e.once("disconnected",(t=>this.onDisconnected(e.getPeerDescriptor(),t))),!0))}acceptNewConnection(e){const t=Mj(e.getPeerDescriptor());if(Pz.trace(t+" acceptNewConnection()"),this.endpoints.has(t)){if("remote"===kz(Mj(this.getLocalPeerDescriptor()),t)){let r;const n=this.endpoints.get(t);this.endpoints.get(t).connected?(Pz.debug("replacing connected connection",{nodeId:t}),r=new Cz):r=n.buffer;const i=n.connection;return Pz.trace("replaced: "+t),i.replaceAsDuplicate(),this.endpoints.set(t,{connected:!1,connection:e,buffer:r}),!0}return!1}return Pz.trace(t+" added to connections at acceptNewConnection"),this.endpoints.set(t,{connected:!1,buffer:new Cz,connection:e}),!0}async closeConnection(e,t,r){const n=Mj(e);if(Pz.trace(n+" closeConnection() "+r),this.locks.clearAllLocks(n),this.endpoints.has(n)){const e=this.endpoints.get(n).connection;await e.close(t)}else Pz.trace(n+" closeConnection() this.endpoints did not have the id"),this.emit("disconnected",e,!1)}lockConnection(e,t){if(this.state===Tz.STOPPED||xj(e,this.getLocalPeerDescriptor()))return;const r=Mj(e),n=new Ez(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,rz);this.locks.addLocalLocked(r,t),n.lockRequest(t).then((e=>Pz.trace("LockRequest successful"))).catch((e=>{Pz.debug(e)}))}unlockConnection(e,t){if(this.state===Tz.STOPPED||xj(e,this.getLocalPeerDescriptor()))return;const r=Mj(e);this.locks.removeLocalLocked(r,t);const n=new Ez(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,rz);this.endpoints.has(r)&&n.unlockRequest(t)}weakLockConnection(e,t){this.state!==Tz.STOPPED&&e!==Mj(this.getLocalPeerDescriptor())&&this.locks.addWeakLocked(e,t)}weakUnlockConnection(e,t){this.state!==Tz.STOPPED&&e!==Mj(this.getLocalPeerDescriptor())&&this.locks.removeWeakLocked(e,t)}async enablePrivateClientMode(){this.privateClientMode=!0,await Promise.all(this.getConnectedEndpoints().map((e=>{const t=e.connection.getPeerDescriptor();return this.setPrivateForConnection(t,!0)})))}async disablePrivateClientMode(){this.privateClientMode=!1,await Promise.all(this.getConnectedEndpoints().map((e=>{const t=e.connection.getPeerDescriptor();return this.setPrivateForConnection(t,!1)})))}getConnectedEndpoints(){return Array.from(this.endpoints.values()).filter((e=>e.connected))}isPrivateClientMode(){return this.privateClientMode}async setPrivateForConnection(e,t){const r=new Ez(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,rz);await r.setPrivate(t)}async gracefullyDisconnectAsync(e,t){const r=this.endpoints.get(Mj(e));if(r)if(r.connected){const n=r.connection,i=new Promise(((e,t)=>{eE(n,"disconnected",2e3).then((()=>{Pz.trace("disconnected event received in gracefullyDisconnectAsync()")})).catch((e=>{Pz.trace("force-closing connection after timeout "+e),n.close(!0)})).finally((()=>{Pz.trace("resolving after receiving disconnected event"),e()}))}));await Promise.all([i,this.doGracefullyDisconnectAsync(e,t)])}else r.connection.close(!0);else Pz.debug("gracefullyDisconnectedAsync() tried on a non-existing connection")}async doGracefullyDisconnectAsync(e,t){const r=Mj(e);Pz.trace(r+" gracefullyDisconnectAsync()");const n=new Ez(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,rz);try{await n.gracefulDisconnect(t)}catch(e){Pz.trace(r+" remote.gracefulDisconnect() failed"+e)}}getConnections(){return Array.from(this.endpoints.values()).map((e=>e)).filter((e=>e.connected&&!this.locks.isPrivate(Mj(e.connection.getPeerDescriptor())))).map((e=>e.connection.getPeerDescriptor()))}onConnectionCountChange(){this.metrics.connectionAverageCount.record(this.endpoints.size)}getDiagnosticInfo(){return{connections:Array.from(this.endpoints.values()).filter((e=>e.connected)).map((e=>e.connection)).map((e=>e.getDiagnosticInfo())),connectionCount:this.endpoints.size}}}new Bv("SimulatorConnection");const Mz="1.1",xz=e=>{const t=Oz(Mz).major,r=Oz(e)?.major;return!(void 0===r||r<t)},Oz=e=>{const t=e.split(".");if(2===t.length){const e=t.map((e=>Number(e)));if(!e.some((e=>isNaN(e))))return{major:e[0],minor:e[1]}}};var Dz="103.3.1";const Bz=new Bv("Handshaker"),Lz=(e,t,r,n)=>{const i=new jz(e,r),s=()=>{i.stop(),r.off("disconnected",u),r.off("connected",c),i.off("handshakeCompleted",a),i.off("handshakeFailed",o),t.off("disconnected",l)},o=e=>{e!==eq.INVALID_TARGET_PEER_DESCRIPTOR&&e!==eq.UNSUPPORTED_PROTOCOL_VERSION||(t.close(!1),s())},a=e=>{Bz.trace("handshake completed for outgoing connection, "+Mj(e)),t.onHandshakeCompleted(r),s()},c=()=>i.sendHandshakeRequest(n),u=e=>{t.close(e),s()},l=()=>{r.close(!1),s()};return i.once("handshakeFailed",o),i.once("handshakeCompleted",a),r.once("connected",c),r.once("disconnected",u),t.once("disconnected",l),i},Fz=(e,t,r,n)=>{r.sendHandshakeResponse(n),t.destroy(),e.destroy()},Uz=(e,t,r)=>{e.sendHandshakeResponse(),t.onHandshakeCompleted(r)};let jz=class extends Sl{static HANDSHAKER_SERVICE_ID="system/handshaker";localPeerDescriptor;connection;onDataListener;constructor(e,t){super(),this.localPeerDescriptor=e,this.connection=t,this.onDataListener=e=>this.onData(e),this.connection.on("data",this.onDataListener)}onData(e){try{const t=Rq.fromBinary(e);if("handshakeRequest"===t.body.oneofKind){Bz.trace("handshake request received");const e=t.body.handshakeRequest;this.emit("handshakeRequest",e.sourcePeerDescriptor,e.protocolVersion,e.targetPeerDescriptor)}if("handshakeResponse"===t.body.oneofKind){Bz.trace("handshake response received");const e=t.body.handshakeResponse,r=xz(e.protocolVersion)?e.error:eq.UNSUPPORTED_PROTOCOL_VERSION;void 0!==r?this.emit("handshakeFailed",r):this.emit("handshakeCompleted",e.sourcePeerDescriptor)}}catch(e){Bz.debug("error while parsing handshake message",e)}}sendHandshakeRequest(e){const t=((e,t)=>{const r={sourcePeerDescriptor:e,targetPeerDescriptor:t,protocolVersion:Mz,applicationVersion:Dz};return{serviceId:jz.HANDSHAKER_SERVICE_ID,messageId:xF(),body:{oneofKind:"handshakeRequest",handshakeRequest:r}}})(this.localPeerDescriptor,e);this.connection.send(Rq.toBinary(t)),Bz.trace("handshake request sent")}sendHandshakeResponse(e){const t=((e,t)=>{const r={sourcePeerDescriptor:e,error:t,protocolVersion:Mz,applicationVersion:Dz};return{serviceId:jz.HANDSHAKER_SERVICE_ID,messageId:xF(),body:{oneofKind:"handshakeResponse",handshakeResponse:r}}})(this.localPeerDescriptor,e);this.connection.send(Rq.toBinary(t)),Bz.trace("handshake response sent")}stop(){this.connection.off("data",this.onDataListener),this.removeAllListeners()}};const qz=new Bv("PendingConnection");class zz extends Sl{connectingAbortController=new AbortController;remotePeerDescriptor;replacedAsDuplicate=!1;stopped=!1;constructor(e,t=15e3){super(),this.remotePeerDescriptor=e,Yy((()=>{this.close(!1)}),t,this.connectingAbortController.signal)}replaceAsDuplicate(){qz.trace(cz(this.remotePeerDescriptor)+" replaceAsDuplicate"),this.replacedAsDuplicate=!0}onHandshakeCompleted(e){this.replacedAsDuplicate||this.emit("connected",this.remotePeerDescriptor,e)}close(e){this.stopped||(this.stopped=!0,this.connectingAbortController.abort(),this.replacedAsDuplicate||this.emit("disconnected",e))}destroy(){this.stopped||(this.stopped=!0,this.connectingAbortController.abort(),this.removeAllListeners())}getPeerDescriptor(){return this.remotePeerDescriptor}}new Bv("SimulatorConnector");class Kz extends oz{transport;messageListener;disconnectedListener;constructor(e,t,r){super(e,((e,r)=>t.send(e,r)),r),this.messageListener=e=>{this.handleMessageFromPeer(e)},this.disconnectedListener=e=>{this.getRequestIds((t=>xj(e,t.getCallContext().targetDescriptor))).forEach((e=>this.handleClientError(e,new qF.Disconnected("Peer disconnected"))))},this.transport=t,t.on("message",this.messageListener),t.on("disconnected",this.disconnectedListener)}destroy(){this.transport.off("message",this.messageListener),this.transport.off("disconnected",this.disconnectedListener),this.stop()}}var Gz;!function(e){e.OFFER="offer",e.ANSWER="answer"}(Gz||(Gz={}));var Vz;!function(e){e.DISCONNECTED="disconnected",e.FAILED="failed",e.CLOSED="closed"}(Vz||(Vz={}));const Hz=new Bv("WebrtcConnection (browser)");class $z extends Sl{connectionId;connectionType=dz.WEBRTC;lastState="connecting";iceServers;peerConnection;bufferThresholdHigh=2**17;bufferThresholdLow=32768;dataChannel;makingOffer=!1;isOffering=!1;closed=!1;earlyTimeout;messageQueue=[];constructor(e){super(),this.connectionId=uz(),this.iceServers=e.iceServers??[],this.earlyTimeout=setTimeout((()=>{this.doClose(!1,"timed out due to remote descriptor not being set")}),5e3)}start(e){this.isOffering=e;const t=this.iceServers.map((({url:e,port:t,username:r,password:n})=>({urls:`${e}:${t}`,username:r,credential:n})));if(this.peerConnection=new RTCPeerConnection({iceServers:t}),this.peerConnection.onicecandidate=e=>{null!==e.candidate&&null!==e.candidate.sdpMid&&this.emit("localCandidate",e.candidate.candidate,e.candidate.sdpMid)},this.peerConnection.onicegatheringstatechange=()=>{Hz.trace(`conn.onGatheringStateChange: ${this.peerConnection?.iceGatheringState}`)},this.peerConnection.onconnectionstatechange=()=>this.onStateChange(),e){this.peerConnection.onnegotiationneeded=async()=>{if(void 0!==this.peerConnection){this.makingOffer=!0;try{await this.peerConnection.setLocalDescription()}catch(e){Hz.warn("Failed to set local description",{err:e})}null!==this.peerConnection.localDescription&&this.emit("localDescription",this.peerConnection.localDescription?.sdp,this.peerConnection.localDescription?.type)}this.makingOffer=!1};const e=this.peerConnection.createDataChannel("streamrDataChannel");this.setupDataChannel(e)}else this.peerConnection.ondatachannel=e=>{this.setupDataChannel(e.channel)}}async setRemoteDescription(e,t){const r=t.toLowerCase()===Gz.OFFER&&(this.makingOffer||"stable"!=this.peerConnection?.signalingState);if(!(this.isOffering&&r)){try{await(this.peerConnection?.setRemoteDescription({sdp:e,type:t.toLowerCase()})),clearTimeout(this.earlyTimeout)}catch(e){Hz.warn("Failed to set remote description",{err:e})}if(t.toLowerCase()===Gz.OFFER&&void 0!==this.peerConnection){try{await this.peerConnection.setLocalDescription()}catch(e){Hz.warn("Failed to set local description",{err:e})}null!==this.peerConnection.localDescription&&this.emit("localDescription",this.peerConnection.localDescription.sdp,this.peerConnection.localDescription.type)}}}addRemoteCandidate(e,t){this.peerConnection?.addIceCandidate({candidate:e,sdpMid:t}).catch((e=>{Hz.warn("Failed to add ICE candidate",{err:e})}))}isOpen(){return"connected"===this.lastState}async close(e,t){this.doClose(e,t)}doClose(e,t){if(!this.closed){if(this.closed=!0,this.lastState="closed",clearTimeout(this.earlyTimeout),this.stopListening(),this.emit("disconnected",e,void 0,t),this.removeAllListeners(),void 0!==this.dataChannel)try{this.dataChannel.close()}catch(e){Hz.warn("Failed to close data channel",{err:e})}if(this.dataChannel=void 0,void 0!==this.peerConnection)try{this.peerConnection.close()}catch(e){Hz.warn("Failed to close connection",{err:e})}this.peerConnection=void 0}}destroy(){this.removeAllListeners(),this.doClose(!1)}send(e){"connected"===this.lastState?this.dataChannel.bufferedAmount>this.bufferThresholdHigh?this.messageQueue.push(e):this.dataChannel?.send(e):Hz.warn("Tried to send on a connection with last state "+this.lastState)}setupDataChannel(e){this.dataChannel=e,this.dataChannel.binaryType="arraybuffer",this.dataChannel.bufferedAmountLowThreshold=this.bufferThresholdLow,e.onopen=()=>{Hz.trace("dc.onOpen"),this.onDataChannelOpen()},e.onclose=()=>{Hz.trace("dc.onClosed"),this.doClose(!1)},e.onerror=e=>{Hz.warn("Data channel error",{err:e})},e.onmessage=e=>{Hz.trace("dc.onmessage"),this.emit("data",new Uint8Array(e.data))},e.onbufferedamountlow=()=>{for(Hz.trace("dc.onBufferedAmountLow");this.messageQueue.length>0&&this.dataChannel.bufferedAmount<this.bufferThresholdHigh;){const e=this.messageQueue.shift();this.dataChannel.send(e)}}}stopListening(){void 0!==this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onclose=null,this.dataChannel.onerror=null,this.dataChannel.onbufferedamountlow=null,this.dataChannel.onmessage=null),void 0!==this.peerConnection&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.onicecandidate=null,this.peerConnection.onicegatheringstatechange=null,this.peerConnection.onnegotiationneeded=null,this.peerConnection.ondatachannel=null)}onDataChannelOpen(){this.lastState="connected",this.emit("connected")}onStateChange(){this.peerConnection.connectionState!==Vz.CLOSED&&this.peerConnection.connectionState!==Vz.DISCONNECTED&&this.peerConnection.connectionState!==Vz.FAILED||this.doClose(!1)}setConnectionId(e){this.connectionId=e}}const Wz=new Bv("WebrtcConnectorRpcRemote");class Jz extends wz{requestConnection(){const e=this.formDhtRpcOptions({notification:!0});this.getClient().requestConnection({},e).catch((e=>{Wz.trace("Failed to send requestConnection")}))}sendRtcOffer(e,t){const r={connectionId:t,description:e},n=this.formDhtRpcOptions();this.getClient().rtcOffer(r,n).catch((e=>{Wz.trace("Failed to send rtcOffer")}))}sendRtcAnswer(e,t){const r={connectionId:t,description:e},n=this.formDhtRpcOptions();this.getClient().rtcAnswer(r,n).catch((e=>{Wz.trace("Failed to send rtcAnswer")}))}sendIceCandidate(e,t,r){const n={connectionId:r,mid:t,candidate:e},i=this.formDhtRpcOptions();this.getClient().iceCandidate(n,i).catch((e=>{Wz.trace("Failed to send iceCandidate")}))}}const Qz=new Bv("WebrtcConnectorRpcLocal");class Zz{options;constructor(e){this.options=e}async requestConnection(e){const t=e.incomingSourceDescriptor;if(this.options.ongoingConnectAttempts.has(Mj(t)))return{};const r=this.options.connect(t,!1);return this.options.onNewConnection(r),{}}async rtcOffer(e,t){const r=t.incomingSourceDescriptor,n=Mj(r);let i,s;return this.options.ongoingConnectAttempts.has(n)?(s=this.options.ongoingConnectAttempts.get(n).managedConnection,i=this.options.ongoingConnectAttempts.get(n).connection):(s=this.options.connect(r,!0),i=this.options.ongoingConnectAttempts.get(n).connection,this.options.onNewConnection(s)),i.setConnectionId(e.connectionId),i.setRemoteDescription(e.description,"offer"),{}}async rtcAnswer(e,t){const r=t.incomingSourceDescriptor,n=Mj(r),i=this.options.ongoingConnectAttempts.get(n)?.connection;return i?i.connectionId!==e.connectionId?(Qz.trace("Ignoring RTC answer due to connectionId mismatch"),{}):(i.setRemoteDescription(e.description,"answer"),{}):{}}async iceCandidate(e,t){const r=t.incomingSourceDescriptor,n=Mj(r),i=this.options.ongoingConnectAttempts.get(n)?.connection;return i?i.connectionId!==e.connectionId?(Qz.trace("Ignoring remote candidate due to connectionId mismatch"),{}):(this.isIceCandidateAllowed(e.candidate)&&i.addRemoteCandidate(e.candidate,e.mid),{}):{}}isIceCandidateAllowed(e){if(!this.options.allowPrivateAddresses){const t=function(e){const t=e.split(" ").filter((e=>e.length>0));return t.length>=5&&hU.isValid(t[4])?t[4]:void 0}(e);if(void 0!==t&&pz(t))return!1}return!0}}const Yz=new Bv("WebrtcConnector");class Xz{static WEBRTC_CONNECTOR_SERVICE_ID="system/webrtc-connector";rpcCommunicator;ongoingConnectAttempts=new Map;localPeerDescriptor;stopped=!1;options;constructor(e){this.options=e,this.rpcCommunicator=new Kz(Xz.WEBRTC_CONNECTOR_SERVICE_ID,e.transport,{rpcRequestTimeout:15e3}),this.registerLocalRpcMethods(e)}registerLocalRpcMethods(e){const t=new Zz({connect:(e,t)=>this.connect(e,t),onNewConnection:e=>this.options.onNewConnection(e),ongoingConnectAttempts:this.ongoingConnectAttempts,rpcCommunicator:this.rpcCommunicator,getLocalPeerDescriptor:()=>this.localPeerDescriptor,allowPrivateAddresses:e.allowPrivateAddresses??!0});this.rpcCommunicator.registerRpcNotification(Iq,"requestConnection",(async(e,r)=>this.stopped?{}:t.requestConnection(r))),this.rpcCommunicator.registerRpcNotification(Pq,"rtcOffer",(async(e,r)=>this.stopped?{}:t.rtcOffer(e,r))),this.rpcCommunicator.registerRpcNotification(Tq,"rtcAnswer",(async(e,r)=>this.stopped?{}:t.rtcAnswer(e,r))),this.rpcCommunicator.registerRpcNotification(_q,"iceCandidate",(async(e,r)=>this.stopped?{}:t.iceCandidate(e,r)))}connect(e,t){if(xj(e,this.localPeerDescriptor))throw new zj("Cannot open WebRTC Connection to self");Yz.trace(`Opening WebRTC connection to ${Mj(e)}`);const r=Mj(e),n=this.ongoingConnectAttempts.get(r);if(n)return n.managedConnection;const i=this.createConnection(e),s=Mj(this.localPeerDescriptor),o=Mj(e),a="local"===kz(s,o);let c;const u=new Jz(this.localPeerDescriptor,e,this.rpcCommunicator,tz),l=()=>{this.ongoingConnectAttempts.delete(r),i.off("disconnected",l),c.off("disconnected",l),c.off("connected",l)};if(a)c=new zz(e),Lz(this.localPeerDescriptor,c,i,e),i.once("localDescription",(e=>{Yz.trace("Sending offer to remote peer"),u.sendRtcOffer(e,i.connectionId)}));else{c=new zz(e);const t=((e,t,r)=>{const n=new jz(e,r),i=()=>{n.stop(),t.off("disconnected",s),r.off("disconnected",s)},s=e=>{t.close(e),i()};return n.on("handshakeRequest",(()=>{i()})),r.once("disconnected",s),t.once("disconnected",(()=>{r.close(!1),i()})),n})(this.localPeerDescriptor,c,i);i.once("localDescription",(e=>{u.sendRtcAnswer(e,i.connectionId)})),t.on("handshakeRequest",((e,r)=>{xz(r)?Uz(t,c,i):Fz(c,i,t,eq.UNSUPPORTED_PROTOCOL_VERSION),l()}))}return this.ongoingConnectAttempts.set(o,{managedConnection:c,connection:i}),i.on("disconnected",l),c.on("disconnected",l),c.on("connected",l),i.on("localCandidate",((e,t)=>{void 0!==this.options.externalIp&&(e=((e,t)=>{const r=e.split(" ");return"host"===r[7]&&(r[4]=t),r.join(" ")})(e,this.options.externalIp),Yz.debug(`onLocalCandidate injected external ip ${e} ${t}`)),u.sendIceCandidate(e,t,i.connectionId)})),i.start(a),t||a||u.requestConnection(),c}createConnection(e){return new $z({remotePeerDescriptor:e,iceServers:this.options.iceServers,bufferThresholdLow:this.options.bufferThresholdLow,bufferThresholdHigh:this.options.bufferThresholdHigh,portRange:this.options.portRange})}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async stop(){Yz.trace("stop()"),this.stopped=!0;const e=Array.from(this.ongoingConnectAttempts.values());await Promise.allSettled(e.map((async e=>{e.connection.destroy(),e.managedConnection.close(!1)}))),this.rpcCommunicator.destroy()}}const eK=new Bv("AbstractWebsocketClientConnection");class tK extends Sl{connectionId;connectionType=dz.WEBSOCKET_CLIENT;destroyed=!1;constructor(){super(),this.connectionId=uz()}send(e){this.destroyed?eK.debug("Tried to send() on stopped connection"):1===this.socket?.readyState?(eK.trace(`Sending data with size ${e.byteLength}`),this.socket?.send(e)):eK.debug("Tried to send data on a non-open connection",{id:this.connectionId,readyState:this.socket.readyState,destroyed:this.destroyed})}async close(e){this.emit("disconnected",e,void 0,"close() called"),this.removeAllListeners(),this.destroyed?eK.debug("Tried to close() a stopped connection",{id:this.connectionId}):(eK.trace(`Closing socket for connection ${this.connectionId}`),this.socket?.close(e?3001:void 0))}destroy(){eK.trace("destroy() a connection"),this.destroyed?eK.debug("Tried to destroy() a stopped connection"):(this.removeAllListeners(),this.socket&&(this.stopListening(),this.socket.close(),this.socket=void 0),this.destroyed=!0)}onOpen(){this.destroyed||(eK.trace("WebSocket Client Connected"),1===this.socket?.readyState&&this.emit("connected"))}onMessage(e){this.emit("data",e)}onClose(e,t){this.destroyed||(eK.trace("Websocket Closed"),this.doDisconnect(e,t))}onError(e){this.destroyed||(eK.trace("WebSocket Client error: "+e?.message,{error:e}),this.emit("error",e.name))}doDisconnect(e,t){this.destroyed=!0,this.stopListening(),this.socket=void 0;const r=1001===e||3001===e;this.emit("disconnected",r,e,t),this.removeAllListeners()}}const rK=new Bv("WebsocketClientConnection (browser)");class nK extends tK{socket;connect(e,t){this.destroyed?rK.debug("Tried to connect() a stopped connection"):(this.socket=new yU.w3cwebsocket(e,void 0,void 0,void 0,{rejectUnauthorized:!t}),this.socket.binaryType="arraybuffer",this.socket.onerror=e=>this.onError(e),this.socket.onopen=()=>this.onOpen(),this.socket.onclose=e=>this.onClose(e.code,e.reason),this.socket.onmessage=e=>{this.destroyed||("string"==typeof e.data?rK.debug("Received string data, only binary data is supported"):this.onMessage(new Uint8Array(e.data)))})}stopListening(){this.socket&&(this.socket.onopen=void 0,this.socket.onclose=void 0,this.socket.onerror=void 0,this.socket.onmessage=void 0)}}class iK{options;constructor(e){this.options=e}async requestConnection(e,t){if(this.options.abortSignal.aborted)return{};const r=t.incomingSourceDescriptor;if(!this.options.hasConnection(Mj(r))){const e=this.options.connect(r);this.options.onNewConnection(e)}return{}}}const sK=(e,t)=>(e.tls?"wss://":"ws://")+e.host+":"+e.port+(void 0!==t?"?action="+t:"");class oK{static WEBSOCKET_CONNECTOR_SERVICE_ID="system/websocket-connector";websocketServer;geoIpLocator;localPeerDescriptor;connectingConnections=new Map;abortController=new AbortController;options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new iK({connect:e=>this.connect(e),hasConnection:e=>this.connectingConnections.has(e)||this.options.hasConnection(e),onNewConnection:e=>this.options.onNewConnection(e),abortSignal:this.abortController.signal});this.options.rpcCommunicator.registerRpcNotification(Cq,"requestConnection",(async(t,r)=>this.abortController.signal.aborted?{}:e.requestConnection(t,r)))}isPossibleToFormConnection(e){return mz(this.localPeerDescriptor,e)===dz.WEBSOCKET_CLIENT}connect(e){const t=Mj(e),r=this.connectingConnections.get(t);if(r)return r;const n=new nK,i=sK(e.websocket),s=new zz(e);Lz(this.localPeerDescriptor,s,n,e),this.connectingConnections.set(t,s);const o=()=>{this.connectingConnections.has(t)&&this.connectingConnections.delete(t),n.off("disconnected",o),s.off("disconnected",o),s.off("connected",o)};return n.on("disconnected",o),s.on("disconnected",o),s.on("connected",o),n.connect(i,!1),s}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async destroy(){this.abortController.abort();Array.from(this.connectingConnections.values()).forEach((e=>e.close(!0))),await(this.websocketServer?.stop()),this.geoIpLocator?.stop()}}class aK extends Sl{constructor(e){super()}async start(){throw new Error("WebsocketServer is not supported in browser environment")}async stop(){throw new Error("WebsocketServer is not supported in browser environment")}updateCertificate(e,t){throw new Error("WebsocketServer is not supported in browser environment")}}const cK=new Bv("AutoCertifierClientFacade");class uK{autoCertifierClient;rpcCommunicator;options;constructor(e){this.options=e,this.rpcCommunicator=new Kz("system/auto-certificer",e.transport),this.autoCertifierClient=e.createClientFactory?e.createClientFactory():(()=>{throw new Error("AutoCertifierClient is not supported in browser environment")})(e.configFile,e.url,this.rpcCommunicator,e.wsServerPort)}async start(){this.autoCertifierClient.on("updatedCertificate",(e=>{this.options.setHost(e.fqdn),this.options.updateCertificate(e.certificate,e.privateKey),cK.trace("Updated certificate")})),await Promise.all([eE(this.autoCertifierClient,"updatedCertificate",6e4),this.autoCertifierClient.start()])}stop(){this.autoCertifierClient.stop(),this.rpcCommunicator.destroy()}}const lK=new Bv("connectivityChecker"),hK=async({url:e,allowSelfSignedCertificate:t,timeoutMs:r=1e3})=>{const n=new nK;let i;try{const s=tE(n,["connected","error"],r);n.connect(e,t),i=await s}catch{throw new Uj("WebSocket connection timed out")}if("error"===i.winnerName)throw new Uj("Could not open WebSocket connection");return n},dK="system/connectivity-checker",fK=async(e,t)=>{let r;const n={host:t.websocket.host,port:t.websocket.port,tls:t.websocket.tls},i=sK(n,"connectivityRequest");lK.debug(`Attempting connectivity check with entrypoint ${i}`);try{r=await hK({url:i,allowSelfSignedCertificate:e.allowSelfSignedCertificate})}catch(e){throw new Uj(`Failed to connect to entrypoint for connectivity check: ${i}`,e)}const s={serviceId:dK,messageId:xF(),body:{oneofKind:"connectivityRequest",connectivityRequest:e}};try{const e=new Promise(((e,t)=>{const n=setTimeout((()=>{r.close(!1),t(new Kj("timeout"))}),5e3),i=s=>{r.close(!1);try{const o=Rq.fromBinary(s);if("connectivityResponse"===o.body.oneofKind){lK.debug("ConnectivityResponse received: "+JSON.stringify(Rq.toJson(o)));const s=o.body.connectivityResponse,a=s.protocolVersion;r.off("data",i),clearTimeout(n),xz(a)?e(s):t(`Unsupported version: ${a}`)}}catch(e){lK.trace("Could not parse message",{err:e})}};r.on("data",i)}));return r.send(Rq.toBinary(s)),lK.trace("ConnectivityRequest sent: "+JSON.stringify(Rq.toJson(s))),await e}catch(e){throw lK.error("error getting connectivityresponse"),e}},pK=new Bv("connectivityRequestHandler"),gK=async(e,t,r)=>{const n=t.host??e.getRemoteIpAddress(),i=e.getRemoteIpAddress();let s;if(0!==t.port?s=await mK(t,i,n):(pK.trace("ConnectivityRequest port is 0, replying without connectivityProbe"),s={host:n,natType:Iz.UNKNOWN,ipAddress:mE(i),protocolVersion:Mz}),void 0!==r){const e=r.lookup(i);void 0!==e&&(s.latitude=e.latitude,s.longitude=e.longitude)}const o={serviceId:dK,messageId:xF(),body:{oneofKind:"connectivityResponse",connectivityResponse:s}};e.send(Rq.toBinary(o)),pK.trace("ConnectivityResponse sent: "+JSON.stringify(Rq.toJson(o)))},mK=async(e,t,r)=>{let n,i;try{const s={host:r,port:e.port,tls:e.tls},o=sK(s,"connectivityProbe");pK.trace(`Attempting Connectivity Check to ${o}`),n=await hK({url:o,allowSelfSignedCertificate:e.allowSelfSignedCertificate}),pK.trace("Connectivity test produced positive result, communicating reply to the requester "+r+":"+e.port),i={host:r,natType:Iz.OPEN_INTERNET,websocket:{host:r,port:e.port,tls:e.tls},ipAddress:mE(t),protocolVersion:Mz}}catch(e){pK.debug("error",{err:e}),i={host:r,natType:Iz.UNKNOWN,ipAddress:mE(t),protocolVersion:Mz}}return n&&n.close(!1),i},yK=new Bv("WebsocketClientConnectorRpcRemote");class bK extends wz{async requestConnection(){yK.trace(`Requesting WebSocket connection from ${Mj(this.getLocalPeerDescriptor())}`);const e=this.formDhtRpcOptions();return this.getClient().requestConnection({},e)}}const wK=new Bv("WebsocketServerConnector");class vK{websocketServer;geoIpLocator;ongoingConnectRequests=new Map;host;autoCertifierClient;selectedPort;localPeerDescriptor;abortController=new AbortController;options;constructor(e){this.options=e,this.websocketServer=e.portRange?new aK({portRange:e.portRange,tlsCertificate:e.tlsCertificate,maxMessageSize:e.maxMessageSize,enableTls:e.serverEnableTls}):void 0,this.host=e.host}async start(){if(!this.abortController.signal.aborted&&this.websocketServer){if(this.websocketServer.on("connected",(e=>{const t=e,r=new URLSearchParams(t.resourceURL.query??"").get("action");var n,i;wK.trace("WebSocket client connected",{action:r,remoteAddress:t.getRemoteIpAddress()}),"connectivityRequest"===r?(n=t,i=this.geoIpLocator,n.on("data",(async e=>{pK.trace("server received data");try{const t=Rq.fromBinary(e);if("connectivityRequest"===t.body.oneofKind){pK.trace("ConnectivityRequest received: "+JSON.stringify(Rq.toJson(t)));try{await gK(n,t.body.connectivityRequest,i),pK.trace("handleIncomingConnectivityRequest ok")}catch(e){pK.error("handleIncomingConnectivityRequest",{err:e})}}}catch(e){pK.trace("Could not parse message",{err:e})}}))):"connectivityProbe"===r||(void 0!==this.localPeerDescriptor?this.attachHandshaker(e):(wK.trace("incoming Websocket connection before localPeerDescriptor was set, closing connection"),e.close(!1).catch((()=>{}))))})),this.options.geoIpDatabaseFolder)try{this.geoIpLocator=await(()=>{throw new Error("GeoIpLocator is not supported in browser environment")})(this.options.geoIpDatabaseFolder)}catch(e){wK.error("Failed to start GeoIpLocator",{err:e})}const e=await this.websocketServer.start();this.selectedPort=e}}attachHandshaker(e){const t=new jz(this.localPeerDescriptor,e);t.once("handshakeRequest",((r,n,i)=>{this.onServerSocketHandshakeRequest(r,e,t,n,i)}))}onServerSocketHandshakeRequest(e,t,r,n,i){const s=Mj(e);if(this.ongoingConnectRequests.has(s)){const{pendingConnection:e,delFunc:o}=this.ongoingConnectRequests.get(s);xz(n)?i&&!xj(this.localPeerDescriptor,i)?(Fz(e,t,r,eq.INVALID_TARGET_PEER_DESCRIPTOR),o()):Uz(r,e,t):(Fz(e,t,r,eq.UNSUPPORTED_PROTOCOL_VERSION),o())}else{const s=new zz(e);xz(n)?i&&!xj(this.localPeerDescriptor,i)?Fz(s,t,r,eq.INVALID_TARGET_PEER_DESCRIPTOR):this.options.onNewConnection(s)?Uz(r,s,t):Fz(s,t,r,eq.DUPLICATE_CONNECTION):Fz(s,t,r,eq.UNSUPPORTED_PROTOCOL_VERSION)}}async checkConnectivity(e){if(this.abortController.signal.aborted)return{host:"127.0.0.1",natType:Iz.UNKNOWN,ipAddress:mE("127.0.0.1"),protocolVersion:Mz};if(!this.options.entrypoints||0===this.options.entrypoints.length)return{host:this.host,natType:Iz.OPEN_INTERNET,websocket:{host:this.host,port:this.selectedPort,tls:void 0!==this.options.tlsCertificate},ipAddress:mE("127.0.0.1"),protocolVersion:Mz};const t=PU(this.options.entrypoints);for(;t.length>0&&!this.abortController.signal.aborted;){const r=t[0];try{const t={port:this.selectedPort??0,host:this.host,tls:!!this.websocketServer&&this.options.serverEnableTls,allowSelfSignedCertificate:e};if(this.abortController.signal.aborted)throw new Uj("ConnectivityChecker is destroyed");return await fK(t,r)}catch(e){const n=`Failed to connect to entrypoint with id ${Mj(r)} and URL ${sK(r.websocket)}`;wK.error(n,{err:e}),t.shift(),await Qv(2e3,this.abortController.signal)}}throw new jj(`Failed to connect to the entrypoints after ${this.options.entrypoints.length} attempts\nAttempted hosts: ${this.options.entrypoints.map((e=>`${e.websocket.host}:${e.websocket.port}`)).join(", ")}`)}async autoCertify(){this.autoCertifierClient=new uK({configFile:this.options.autoCertifierConfigFile,transport:this.options.autoCertifierTransport,url:this.options.autoCertifierUrl,wsServerPort:this.selectedPort,setHost:e=>this.setHost(e),updateCertificate:(e,t)=>this.websocketServer.updateCertificate(e,t)}),wK.trace("AutoCertifying subdomain..."),await this.autoCertifierClient.start()}setHost(e){wK.trace(`Setting host name to ${e}`),this.host=e}connect(e){const t=Mj(e);return this.ongoingConnectRequests.has(t)?this.ongoingConnectRequests.get(t).pendingConnection:this.requestConnectionFromPeer(this.localPeerDescriptor,e)}requestConnectionFromPeer(e,t){setImmediate((()=>{new bK(e,t,this.options.rpcCommunicator,ez).requestConnection().then((()=>{wK.trace("Sent WebsocketConnectionRequest notification to peer",{targetPeerDescriptor:t})}),(e=>{wK.debug("Failed to send WebsocketConnectionRequest notification to peer ",{error:e,targetPeerDescriptor:t})}))}));const r=new zz(t),n=Mj(t),i=()=>{r.off("connected",i),r.off("disconnected",i),this.ongoingConnectRequests.delete(n)};return r.on("connected",i),r.on("disconnected",i),this.ongoingConnectRequests.set(n,{pendingConnection:r,delFunc:i}),r}isPossibleToFormConnection(e){return mz(this.localPeerDescriptor,e)===dz.WEBSOCKET_SERVER}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async destroy(){this.abortController.abort();Array.from(this.ongoingConnectRequests.values()).forEach((e=>e.pendingConnection.close(!0))),await(this.websocketServer?.stop()),this.geoIpLocator?.stop()}}const EK=new Bv("ConnectorFacade");class AK{options;localPeerDescriptor;websocketConnectorRpcCommunicator;websocketClientConnector;websocketServerConnector;webrtcConnector;constructor(e){this.options=e}async start(e,t,r){EK.trace("Creating WebsocketConnectorRpcLocal"),this.websocketConnectorRpcCommunicator=new Kz(oK.WEBSOCKET_CONNECTOR_SERVICE_ID,this.options.transport,{rpcRequestTimeout:15e3});const n={onNewConnection:e,hasConnection:t,rpcCommunicator:this.websocketConnectorRpcCommunicator};this.websocketClientConnector=new oK(n);const i={rpcCommunicator:this.websocketConnectorRpcCommunicator,onNewConnection:e,hasConnection:t,portRange:this.options.websocketPortRange,host:this.options.websocketHost,entrypoints:this.options.entryPoints,tlsCertificate:this.options.tlsCertificate,serverEnableTls:this.options.websocketServerEnableTls,autoCertifierUrl:this.options.autoCertifierUrl,autoCertifierConfigFile:this.options.autoCertifierConfigFile,autoCertifierTransport:r,maxMessageSize:this.options.maxMessageSize,geoIpDatabaseFolder:this.options.geoIpDatabaseFolder};this.websocketServerConnector=new vK(i),this.webrtcConnector=new Xz({onNewConnection:e,transport:this.options.transport,iceServers:this.options.iceServers,allowPrivateAddresses:this.options.webrtcAllowPrivateAddresses,bufferThresholdLow:this.options.webrtcDatachannelBufferThresholdLow,bufferThresholdHigh:this.options.webrtcDatachannelBufferThresholdHigh,externalIp:this.options.externalIp,portRange:this.options.webrtcPortRange,maxMessageSize:this.options.maxMessageSize}),await this.websocketServerConnector.start();const s=!this.options.tlsCertificate&&!0===this.options.websocketServerEnableTls,o=await this.websocketServerConnector.checkConnectivity(s),a=await this.options.createLocalPeerDescriptor(o);if(this.setLocalPeerDescriptor(a),a.websocket&&!this.options.tlsCertificate&&this.options.websocketServerEnableTls)try{await this.websocketServerConnector.autoCertify();const e=await this.websocketServerConnector.checkConnectivity(!1),t=await this.options.createLocalPeerDescriptor(e);void 0!==t.websocket?this.setLocalPeerDescriptor(t):(EK.warn("Connectivity check failed after auto-certification, disabling WebSocket server TLS"),await this.restartWebsocketServerConnector({...i,serverEnableTls:!1}))}catch(e){EK.warn("Failed to auto-certify, disabling WebSocket server TLS",{err:e}),await this.restartWebsocketServerConnector({...i,serverEnableTls:!1})}}setLocalPeerDescriptor(e){this.localPeerDescriptor=e,this.websocketServerConnector.setLocalPeerDescriptor(e),this.websocketClientConnector.setLocalPeerDescriptor(e),this.webrtcConnector.setLocalPeerDescriptor(e)}async restartWebsocketServerConnector(e){await this.websocketServerConnector.destroy(),this.websocketServerConnector=new vK(e),await this.websocketServerConnector.start();const t=await this.websocketServerConnector.checkConnectivity(!1),r=await this.options.createLocalPeerDescriptor(t);this.setLocalPeerDescriptor(r)}createConnection(e){return this.websocketClientConnector.isPossibleToFormConnection(e)?this.websocketClientConnector.connect(e):this.websocketServerConnector.isPossibleToFormConnection(e)?this.websocketServerConnector.connect(e):this.webrtcConnector.connect(e,!1)}getLocalPeerDescriptor(){return this.localPeerDescriptor}async stop(){this.websocketConnectorRpcCommunicator.destroy(),await this.websocketServerConnector.destroy(),await this.websocketClientConnector.destroy(),await this.webrtcConnector.stop()}}function SK(e){const t=Buffer.alloc(4);return t.writeUInt32BE(e),t}const kK=new TE,RK=async(e,t,r)=>{const n=so(32),i=so(20);let s;s=void 0!==r?Nj(r):await(async(e,t)=>{const r=Buffer.alloc(4);r.writeUInt32BE(e);const n=kK.keccakHash(r),i=await kK.createSignature(r,t);return Buffer.concat([n.subarray(n.length-13,n.length),i.subarray(i.length-7,i.length)])})(e.ipAddress,n);const o={nodeId:s,type:Zj.BROWSER,ipAddress:e.ipAddress,region:t,publicKey:i};return e.websocket&&(o.websocket={host:e.websocket.host,port:e.websocket.port,tls:e.websocket.tls}),o.signature=await kK.createSignature((e=>{const t=Buffer.from(","),r=[void 0!==e.type?SK(e.type):new Uint8Array(0),t,void 0!==e.udp?bq.toBinary(e.udp):new Uint8Array(0),t,void 0!==e.tcp?bq.toBinary(e.tcp):new Uint8Array(0),t,void 0!==e.websocket?bq.toBinary(e.websocket):new Uint8Array(0),t,void 0!==e.region?SK(e.region):new Uint8Array(0),t,void 0!==e.ipAddress?SK(e.ipAddress):new Uint8Array(0),t,void 0!==e.publicKey?Buffer.from(e.publicKey):new Uint8Array(0)];return Buffer.concat(r)})(o),n),o};class CK{peerDescriptor;constructor(e){this.peerDescriptor=e}getPeerDescriptor(){return this.peerDescriptor}getNodeId(){return Mj(this.peerDescriptor)}}const IK=(e,t,r)=>{const n=new Dj({referenceId:e,allowToContainReferenceId:!0,excludedNodeIds:r?.excludedNodeIds,maxSize:r?.maxCount});for(const e of t)n.addContact(new CK(e));return n.getClosestContacts().map((e=>e.getPeerDescriptor()))},PK=new Bv("DhtNodeRpcLocal");class TK{options;constructor(e){this.options=e}async getClosestPeers(e,t){this.options.addContact(t.incomingSourceDescriptor);return{peers:IK(_j(e.nodeId),this.options.getNeighbors(),{maxCount:this.options.peerDiscoveryQueryBatchSize}),requestId:e.requestId}}async getClosestRingPeers(e,t){this.options.addContact(t.incomingSourceDescriptor);const r=this.options.getClosestRingContactsTo(e.ringId,this.options.peerDiscoveryQueryBatchSize);return{leftPeers:r.left,rightPeers:r.right,requestId:e.requestId}}async ping(e,t){PK.trace("received ping request: "+Mj(t.incomingSourceDescriptor)),setImmediate((()=>{this.options.addContact(t.incomingSourceDescriptor)}));return{requestId:e.requestId}}async leaveNotice(e){const t=e.incomingSourceDescriptor,r=Mj(t);return PK.trace("received leave notice: "+r),this.options.removeContact(r),{}}}const _K=new Bv("DhtNodeRpcRemote");class NK extends wz{static counter=0;vectorClock;id;serviceId;constructor(e,t,r,n,i){super(e,t,n,Jq,i),this.id=this.getPeerDescriptor().nodeId,this.vectorClock=NK.counter++,this.serviceId=r}async getClosestPeers(e){_K.trace(`Requesting getClosestPeers on ${this.serviceId} from ${this.getNodeId()}`);const t={nodeId:Nj(e),requestId:xF()};try{return(await this.getClient().getClosestPeers(t,this.formDhtRpcOptions())).peers}catch(e){throw _K.trace(`getClosestPeers error ${this.serviceId}`,{err:e}),e}}async getClosestRingPeers(e){_K.trace(`Requesting getClosestRingPeers on ${this.serviceId} from ${this.getNodeId()}`);const t={ringId:e,requestId:xF()};try{const e=await this.getClient().getClosestRingPeers(t,this.formDhtRpcOptions());return{left:e.leftPeers??[],right:e.rightPeers??[]}}catch(e){throw _K.trace(`getClosestRingPeers error ${this.serviceId}`,{err:e}),e}}async ping(){_K.trace(`Requesting ping on ${this.serviceId} from ${this.getNodeId()}`);const e={requestId:xF()},t=this.formDhtRpcOptions();try{if((await this.getClient().ping(e,t)).requestId===e.requestId)return!0}catch(e){_K.trace(`ping failed on ${this.serviceId} to ${this.getNodeId()}`,{err:e})}return!1}leaveNotice(){_K.trace(`Sending leaveNotice on ${this.serviceId} from ${this.getNodeId()}`);const e=this.formDhtRpcOptions({notification:!0});this.getClient().leaveNotice({},e).catch((e=>{_K.trace("Failed to send leaveNotice"+e)}))}getNodeId(){return Mj(this.getPeerDescriptor())}}class MK{options;constructor(e){this.options=e}async externalFetchData(e,t){const r=t.incomingSourceDescriptor,n=await this.options.executeRecursiveOperation(_j(e.key),Qj.FETCH_DATA,Mj(r));return Lq.create({entries:n.dataEntries??[]})}async externalStoreData(e,t){const r=t.incomingSourceDescriptor,n=await this.options.storeDataToDht(_j(e.key),e.data,Mj(r));return sq.create({storers:n})}async externalFindClosestNodes(e,t){const r=t.incomingSourceDescriptor,n=await this.options.executeRecursiveOperation(_j(e.nodeId),Qj.FIND_CLOSEST_NODES,Mj(r));return Uq.create({closestNodes:n.closestNodes})}}const xK=1e4;class OK extends wz{async externalFetchData(e){const t={key:Nj(e)},r=this.formDhtRpcOptions({timeout:xK});try{return(await this.getClient().externalFetchData(t,r)).entries}catch{return[]}}async storeData(e,t){const r={key:Nj(e),data:t},n=this.formDhtRpcOptions({timeout:xK});try{return(await this.getClient().externalStoreData(r,n)).storers}catch{return[]}}async externalFindClosestNode(e){const t={nodeId:Nj(e)},r=this.formDhtRpcOptions({timeout:xK});try{return(await this.getClient().externalFindClosestNodes(t,r)).closestNodes}catch{return[]}}}class DK extends Sl{contactsById=new Map;contactIds=[];localNodeId;maxSize;constructor(e,t){super(),this.localNodeId=e,this.maxSize=t}getContact(e){return this.contactsById.get(e)}getSize(){return this.contactIds.length}clear(){this.contactsById.clear(),this.contactIds=[]}stop(){this.removeAllListeners(),this.clear()}}class BK extends DK{randomness;constructor(e,t,r=.2){super(e,t),this.randomness=r}addContact(e){if(this.localNodeId!==e.getNodeId()&&!this.contactsById.has(e.getNodeId())){if(Math.random()<this.randomness){if(this.getSize()===this.maxSize&&this.getSize()>0){const e=this.contactIds[0];this.removeContact(e)}this.contactIds.push(e.getNodeId()),this.contactsById.set(e.getNodeId(),e),this.emit("contactAdded",e)}}}removeContact(e){if(this.contactsById.has(e)){const t=this.contactsById.get(e),r=this.contactIds.findIndex((t=>t===e));return this.contactIds.splice(r,1),this.contactsById.delete(e),this.emit("contactRemoved",t),!0}return!1}getContacts(e){return(void 0===e?this.contactIds:this.contactIds.slice(0,Math.max(e,0))).map((e=>this.contactsById.get(e)))}}const LK=2**120-1,FK=e=>e.reduce(((e,t)=>e<<BigInt(8)|BigInt(t)),BigInt(0)),UK=e=>Number(FK(e)),jK=e=>{const t=Buffer.alloc(4);t.writeUInt32BE(e.region??0,0);const r=Buffer.alloc(4);r.writeUInt32BE(e.ipAddress??0,0);const n=[t,r,Buffer.from(e.nodeId.subarray(e.nodeId.length-7,e.nodeId.length))],i=Buffer.concat(n);return new Uint8Array(i)},qK=e=>{const t=jK(e);return Number(FK(t))},zK=(e,t)=>{const r=Math.abs(e-t);return e>t?r:LK-r},KK=(e,t)=>{const r=Math.abs(e-t);return e>t?LK-r:r};class GK extends Sl{numNeighborsPerSide=5;referenceId;excludedIds;leftNeighbors;rightNeighbors;constructor(e,t){super(),this.referenceId=UK(e),this.excludedIds=t??new Set,this.leftNeighbors=new qU,this.rightNeighbors=new qU}addContact(e){const t=qK(e.getPeerDescriptor());if(t===this.referenceId||this.excludedIds.has(Mj(e.getPeerDescriptor())))return;let r=!1,n=!1;const i=zK(this.referenceId,t),s=this.leftNeighbors.back();(void 0===s||i<s[0])&&(this.leftNeighbors.setElement(i,e),r=!0,this.leftNeighbors.size()>this.numNeighborsPerSide&&(this.leftNeighbors.eraseElementByIterator(this.leftNeighbors.rBegin()),n=!0));const o=KK(this.referenceId,t),a=this.rightNeighbors.back();(void 0===a||o<a[0])&&(this.rightNeighbors.setElement(o,e),r=!0,this.rightNeighbors.size()>this.numNeighborsPerSide&&(this.rightNeighbors.eraseElementByIterator(this.rightNeighbors.rBegin()),n=!0)),this.hasEventListeners()&&(r||n)&&(r&&this.emit("contactAdded",e),n&&this.emit("contactRemoved",e))}removeContact(e){if(void 0===e)return;const t=qK(e.getPeerDescriptor()),r=zK(this.referenceId,t),n=KK(this.referenceId,t);let i=!1;this.leftNeighbors.eraseElementByKey(r)&&(i=!0),this.rightNeighbors.eraseElementByKey(n)&&(i=!0),this.hasEventListeners()&&i&&this.emit("contactRemoved",e)}getContact(e){const t=qK(e),r=zK(this.referenceId,t),n=KK(this.referenceId,t);return this.leftNeighbors.getElementByKey(r)?this.leftNeighbors.getElementByKey(r):this.rightNeighbors.getElementByKey(n)?this.rightNeighbors.getElementByKey(n):void 0}getClosestContacts(e){const t=[],r=[];let n=0;for(const r of this.leftNeighbors){if(null!=e&&n>=e)break;t.push(r[1]),n++}let i=0;for(const t of this.rightNeighbors){if(null!=e&&i>=e)break;r.push(t[1]),i++}return{left:t,right:r}}getAllContacts(){const e=[];for(const t of this.leftNeighbors)e.push(t[1]);for(const t of this.rightNeighbors)e.push(t[1]);return e}hasEventListeners(){return this.eventNames().length>0}}const VK=new Bv("PeerManager");class HK extends Sl{neighbors;nearbyContacts;activeContacts;ringContacts;randomContacts;stopped=!1;options;constructor(e){super(),this.options=e,this.neighbors=new yL({localNodeId:Nj(this.options.localNodeId),numberOfNodesPerKBucket:this.options.numberOfNodesPerKBucket,numberOfNodesToPing:this.options.numberOfNodesPerKBucket}),this.ringContacts=new GK(jK(this.options.localPeerDescriptor)),this.ringContacts.on("contactAdded",(e=>{this.emit("ringContactAdded",e.getPeerDescriptor())})),this.ringContacts.on("contactRemoved",(e=>{this.emit("ringContactRemoved",e.getPeerDescriptor())})),this.neighbors.on("ping",((e,t)=>this.onKBucketPing(e,t))),this.neighbors.on("removed",(e=>this.onKBucketRemoved(Mj(e.getPeerDescriptor())))),this.neighbors.on("added",(e=>this.onKBucketAdded(e))),this.neighbors.on("updated",(()=>{})),this.nearbyContacts=new Dj({referenceId:this.options.localNodeId,maxSize:this.options.maxContactCount,allowToContainReferenceId:!1}),this.nearbyContacts.on("contactRemoved",(e=>{this.stopped||(this.emit("nearbyContactRemoved",e.getPeerDescriptor()),this.randomContacts.addContact(this.options.createDhtNodeRpcRemote(e.getPeerDescriptor())))})),this.nearbyContacts.on("contactAdded",(e=>this.emit("nearbyContactAdded",e.getPeerDescriptor()))),this.activeContacts=new Set,this.randomContacts=new BK(this.options.localNodeId,this.options.maxContactCount),this.randomContacts.on("contactRemoved",(e=>this.emit("randomContactRemoved",e.getPeerDescriptor()))),this.randomContacts.on("contactAdded",(e=>this.emit("randomContactAdded",e.getPeerDescriptor())))}onKBucketPing(e,t){if(this.stopped)return;const r=new Dj({referenceId:this.options.localNodeId,allowToContainReferenceId:!1});r.addContacts(e);const n=r.getFurthestContacts(1)[0].getNodeId();this.options.connectionLocker?.weakUnlockConnection(n,this.options.lockId),this.neighbors.remove(Nj(n)),this.neighbors.add(t)}onKBucketRemoved(e){this.stopped||(this.options.connectionLocker?.weakUnlockConnection(e,this.options.lockId),VK.trace(`Removed contact ${e}`),0===this.neighbors.count()&&this.emit("kBucketEmpty"))}onKBucketAdded(e){if(!this.stopped&&e.getNodeId()!==this.options.localNodeId){const t=e.getPeerDescriptor(),r=Mj(t);this.options.connectionLocker?.weakLockConnection(r,this.options.lockId),this.options.hasConnection(e.getNodeId())||void 0!==this.options.neighborPingLimit&&this.neighbors.count()>this.options.neighborPingLimit?VK.trace(`Added new contact ${r}`):(VK.trace("starting ping "+r),e.ping().then((e=>{e?VK.trace(`Added new contact ${r}`):(VK.trace("ping failed "+r),this.options.connectionLocker?.weakUnlockConnection(r,this.options.lockId),this.removeContact(r),this.addNearbyContactToNeighbors())})).catch((e=>{this.options.connectionLocker?.weakUnlockConnection(r,this.options.lockId),this.removeContact(r),this.addNearbyContactToNeighbors()})))}}addNearbyContactToNeighbors(){if(this.stopped)return;const e=this.getNearbyActiveContactNotInNeighbors();e&&this.addContact(e.getPeerDescriptor())}getNearbyActiveContactNotInNeighbors(){for(const e of this.nearbyContacts.getContactIds())if(!this.neighbors.get(Nj(e))&&this.activeContacts.has(e))return this.nearbyContacts.getContact(e)}removeContact(e){this.stopped||(VK.trace(`Removing contact ${e}`),this.ringContacts.removeContact(this.nearbyContacts.getContact(e)),this.neighbors.remove(Nj(e)),this.nearbyContacts.removeContact(e),this.activeContacts.delete(e),this.randomContacts.removeContact(e))}removeNeighbor(e){this.neighbors.remove(Nj(e))}async pruneOfflineNodes(e){VK.trace("Pruning offline nodes",{nodes:e.length});const t=await(async(e,t)=>{const r=[];return await Promise.allSettled(e.map((async e=>{await e.ping()?t.add(e.getNodeId()):(t.delete(e.getNodeId()),r.push(e.getPeerDescriptor()))}))),r})(e,this.activeContacts);t.forEach((e=>{VK.trace("Removing offline node",{node:Mj(e)}),this.removeContact(Mj(e))}))}stop(){this.stopped=!0,this.neighbors.toArray().forEach((e=>{e.leaveNotice(),this.neighbors.remove(e.id)})),this.neighbors.removeAllListeners(),this.ringContacts.getAllContacts().forEach((e=>{e.leaveNotice(),this.ringContacts.removeContact(e)})),this.nearbyContacts.stop(),this.randomContacts.stop()}getNearbyContacts(){return this.nearbyContacts}getClosestRingContactsTo(e,t,r){const n=new GK(e,r);return this.ringContacts.getAllContacts().map((e=>n.addContact(e))),n.getClosestContacts(t??8)}getRandomContacts(){return this.randomContacts}getRingContacts(){return this.ringContacts}getNearbyContactCount(e){return this.nearbyContacts.getSize(e)}getNeighborCount(){return this.neighbors.count()}getNeighbors(){return this.neighbors.toArray()}setContactActive(e){this.activeContacts.add(e)}addContact(e){if(this.stopped)return;const t=Mj(e);if(t!==this.options.localNodeId){VK.trace(`Adding new contact ${t}`);const r=this.options.createDhtNodeRpcRemote(e),n=null!==this.neighbors.get(e.nodeId),i=void 0!==this.nearbyContacts.getContact(t),s=void 0!==this.ringContacts.getContact(e);(n||i)&&this.randomContacts.addContact(r),n||this.neighbors.add(r),i||this.nearbyContacts.addContact(r),s||this.ringContacts.addContact(r)}}}const $K=new Bv("DiscoverySession");class WK{id=xF();noProgressCounter=0;ongoingRequests=new Set;doneGate=new uE(!1);options;constructor(e){this.options=e}addContacts(e){if(!this.options.abortSignal.aborted&&!this.doneGate.isOpen())for(const t of e)this.options.peerManager.addContact(t)}async fetchClosestNeighborsFromRemote(e){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return[];const t=Mj(e);$K.trace(`Getting closest neighbors from remote: ${t}`),this.options.contactedPeers.add(t);const r=this.options.createDhtNodeRpcRemote(e),n=await r.getClosestPeers(this.options.targetId);return this.options.peerManager.setContactActive(t),n}onRequestSucceeded(e,t){if(!this.ongoingRequests.has(e))return;this.ongoingRequests.delete(e);const r=Nj(this.options.targetId),n=this.getClosestNeighbor(),i=Tj(r,n.nodeId);this.addContacts(t);const s=this.getClosestNeighbor();Tj(r,s.nodeId)>=i&&this.noProgressCounter++}getClosestNeighbor(){return IK(this.options.targetId,this.options.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),{maxCount:1})[0]}onRequestFailed(e){this.ongoingRequests.has(e)&&(this.ongoingRequests.delete(e),this.options.peerManager.removeContact(e))}findMoreContacts(){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return;const e=IK(this.options.targetId,Array.from(this.options.peerManager.getNearbyContacts().getAllContactsInUndefinedOrder(),(e=>e.getPeerDescriptor())),{maxCount:this.options.parallelism,excludedNodeIds:this.options.contactedPeers});if(0===e.length&&0===this.ongoingRequests.size||this.noProgressCounter>=this.options.noProgressLimit)this.doneGate.open();else for(const t of e){if(this.ongoingRequests.size>=this.options.parallelism)break;const e=Mj(t);this.ongoingRequests.add(e),this.fetchClosestNeighborsFromRemote(t).then((t=>this.onRequestSucceeded(e,t))).catch((()=>this.onRequestFailed(e))).finally((()=>{this.findMoreContacts()}))}}async findClosestNodes(e){0!==this.options.peerManager.getNearbyContactCount(this.options.contactedPeers)&&(setImmediate((()=>{this.findMoreContacts()})),await Xv(this.doneGate.waitUntilOpen(),e,"discovery session timed out",this.options.abortSignal))}}const JK=new Bv("RingDiscoverySession");class QK{id=xF();noProgressCounter=0;ongoingRequests=new Set;doneGate=new uE(!1);options;numContactedPeers=0;targetIdAsRingId;constructor(e){this.options=e,this.targetIdAsRingId=UK(this.options.targetId)}addContacts(e){if(!this.options.abortSignal.aborted&&!this.doneGate.isOpen())for(const t of e)this.options.peerManager.addContact(t)}async fetchClosestContactsFromRemote(e){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return{left:[],right:[]};JK.trace(`Getting closest ring peers from contact: ${Mj(e.getPeerDescriptor())}`),this.numContactedPeers++,this.options.contactedPeers.add(e.getNodeId());const t=await e.getClosestRingPeers(this.options.targetId);return this.options.peerManager.setContactActive(e.getNodeId()),t}onRequestSucceeded(e,t){if(!this.ongoingRequests.has(e))return;this.ongoingRequests.delete(e);const r=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,1),n=zK(this.targetIdAsRingId,qK(r.left[0].getPeerDescriptor())),i=zK(this.targetIdAsRingId,qK(r.right[0].getPeerDescriptor()));this.addContacts(t.left.concat(t.right));const s=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,1),o=zK(this.targetIdAsRingId,qK(s.left[0].getPeerDescriptor())),a=zK(this.targetIdAsRingId,qK(s.right[0].getPeerDescriptor()));o>=n&&a>=i&&this.noProgressCounter++}onRequestFailed(e){this.ongoingRequests.has(e.getNodeId())&&(this.ongoingRequests.delete(e.getNodeId()),this.options.peerManager.removeContact(e.getNodeId()))}findMoreContacts(){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return;const e=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,this.options.parallelism,this.options.contactedPeers);if(0===e.left.length&&0===e.right.length||this.noProgressCounter>=this.options.noProgressLimit)return void this.doneGate.open();const t=[],r=new Set,n=Math.max(e.left.length,e.right.length);for(let i=0;i<n;i++)i<e.left.length&&(r.has(e.left[i].getNodeId())||(t.push(e.left[i]),r.add(e.left[i].getNodeId()))),i<e.right.length&&(r.has(e.right[i].getNodeId())||(t.push(e.right[i]),r.add(e.right[i].getNodeId())));for(const e of t){if(this.ongoingRequests.size>=this.options.parallelism)break;this.ongoingRequests.add(e.getNodeId()),this.fetchClosestContactsFromRemote(e).then((t=>this.onRequestSucceeded(e.getNodeId(),t))).catch((()=>this.onRequestFailed(e))).finally((()=>{this.findMoreContacts()}))}}async findClosestNodes(e){0!==this.options.peerManager.getNearbyContactCount(this.options.contactedPeers)&&(setImmediate((()=>{this.findMoreContacts()})),await Xv(this.doneGate.waitUntilOpen(),e,"discovery session timed out",this.options.abortSignal))}}const ZK="layer0",YK=new Bv("PeerDiscovery");class XK{ongoingDiscoverySessions=new Map;ongoingRingDiscoverySessions=new Map;rejoinOngoing=!1;joinCalled=!1;recoveryIntervalStarted=!1;options;constructor(e){this.options=e}async joinDht(e,t=!0,r=!0){const n=new Set,i=t?{enabled:!0,contactedPeers:new Set}:{enabled:!1};await Promise.all(e.map((e=>this.joinThroughEntryPoint(e,n,i,r))))}async joinThroughEntryPoint(e,t,r,n=!0){if(this.isStopped())return;if(this.joinCalled=!0,YK.debug("Joining "+(this.options.serviceId===ZK?"The Streamr Network":`Control Layer for ${this.options.serviceId}`)+` via entrypoint ${Mj(e)}`),xj(e,this.options.localPeerDescriptor))return;this.options.connectionLocker?.lockConnection(e,`${this.options.serviceId}::joinDht`),this.options.peerManager.addContact(e);const i=Mj(this.options.localPeerDescriptor),s=[this.createSession(i,t)];r.enabled&&s.push(this.createSession((e=>{const t=Nj(e).map((e=>~e));return _j(t)})(i),r.contactedPeers)),await this.runSessions(s,e,n),this.options.connectionLocker?.unlockConnection(e,`${this.options.serviceId}::joinDht`)}async joinRing(){const e=new Set,t=[this.createRingSession(jK(this.options.localPeerDescriptor),e)];await this.runRingSessions(t)}createSession(e,t){const r={targetId:e,parallelism:this.options.parallelism,noProgressLimit:this.options.joinNoProgressLimit,peerManager:this.options.peerManager,contactedPeers:t,abortSignal:this.options.abortSignal,createDhtNodeRpcRemote:this.options.createDhtNodeRpcRemote};return new WK(r)}createRingSession(e,t){const r={targetId:e,parallelism:this.options.parallelism,noProgressLimit:this.options.joinNoProgressLimit,peerManager:this.options.peerManager,contactedPeers:t,abortSignal:this.options.abortSignal,createDhtNodeRpcRemote:this.options.createDhtNodeRpcRemote};return new QK(r)}async runSessions(e,t,r){try{for(const t of e)this.ongoingDiscoverySessions.set(t.id,t),await t.findClosestNodes(this.options.joinTimeout)}catch(e){YK.debug(`DHT join on ${this.options.serviceId} timed out`)}finally{this.isStopped()||(0===this.options.peerManager.getNeighborCount()?r&&Yy((()=>this.rejoinDht(t)),1e3,this.options.abortSignal):await this.ensureRecoveryIntervalIsRunning()),e.forEach((e=>this.ongoingDiscoverySessions.delete(e.id)))}}async runRingSessions(e){try{for(const t of e)this.ongoingRingDiscoverySessions.set(t.id,t),await t.findClosestNodes(this.options.joinTimeout)}catch(e){YK.debug(`Ring join on ${this.options.serviceId} timed out`)}finally{e.forEach((e=>this.ongoingDiscoverySessions.delete(e.id)))}}async rejoinDht(e,t=new Set,r=new Set){if(!this.isStopped()&&!this.rejoinOngoing){YK.debug(`Rejoining DHT ${this.options.serviceId}`),this.rejoinOngoing=!0;try{await this.joinThroughEntryPoint(e,t,{enabled:!0,contactedPeers:r}),YK.debug(`Rejoined DHT successfully ${this.options.serviceId}!`)}catch{YK.warn(`Rejoining DHT ${this.options.serviceId} failed`),this.isStopped()||Yy((()=>this.rejoinDht(e)),5e3,this.options.abortSignal)}finally{this.rejoinOngoing=!1}}}async ensureRecoveryIntervalIsRunning(){this.recoveryIntervalStarted||(this.recoveryIntervalStarted=!0,await Jv((()=>this.fetchClosestAndRandomNeighbors()),6e4,!0,this.options.abortSignal))}async fetchClosestAndRandomNeighbors(){if(this.isStopped())return;const e=Mj(this.options.localPeerDescriptor),t=this.getClosestNeighbors(e,this.options.parallelism),r=this.getClosestNeighbors(Oj(),1);await Promise.allSettled([...t.map((async t=>{const r=this.options.createDhtNodeRpcRemote(t),n=await r.getClosestPeers(e);for(const e of n)this.options.peerManager.addContact(e)})),...r.map((async e=>{const t=this.options.createDhtNodeRpcRemote(e),r=await t.getClosestPeers(Oj());for(const e of r)this.options.peerManager.addContact(e)}))])}getClosestNeighbors(e,t){return IK(e,this.options.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),{maxCount:t})}isJoinOngoing(){return!this.joinCalled||this.ongoingDiscoverySessions.size>0}isJoinCalled(){return this.joinCalled}isStopped(){return this.options.abortSignal.aborted}}const eG=e=>ZU(e.routingPath),tG=new Bv("RouterRpcRemote");class rG extends wz{async routeMessage(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{const n=await this.getClient().routeMessage(t,r);if(n.error===Xj.DUPLICATE&&yw(e.target,this.getPeerDescriptor().nodeId))return!0;if(void 0!==n.error)return!1}catch(t){const r=eG(e),n=Mj(r||e.sourcePeer),i=Mj(this.getPeerDescriptor());return tG.trace(`Failed to send routeMessage from ${n} to ${i}`,{err:t}),!1}return!0}async forwardMessage(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{if(void 0!==(await this.getClient().forwardMessage(t,r)).error)return!1}catch(t){const r=eG(e),n=Mj(r||e.sourcePeer),i=Mj(this.getPeerDescriptor());return tG.trace(`Failed to send forwardMessage from ${n} to ${i}`,{err:t}),!1}return!0}}const nG=new Bv("RecursiveOperationRpcRemote");class iG extends wz{async routeRequest(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{const e=await this.getClient().routeRequest(t,r);if(void 0!==e.error)return nG.trace("Next hop responded with error "+e.error),!1}catch(t){const r=eG(e),n=Mj(r||e.sourcePeer),i=Mj(this.getPeerDescriptor());return nG.debug(`Failed to send routeRequest message from ${n} to ${i}`,{err:t}),!1}return!0}}const sG=new Bv("RoutingSession");class oG extends CK{routerRpcRemote;recursiveOperationRpcRemote;constructor(e,t,r){super(e),this.routerRpcRemote=new rG(t,e,r,Qq,2e3),this.recursiveOperationRpcRemote=new iG(t,e,r,Zq,2e3)}getRouterRpcRemote(){return this.routerRpcRemote}getRecursiveOperationRpcRemote(){return this.recursiveOperationRpcRemote}}var aG;!function(e){e[e.ROUTE=0]="ROUTE",e[e.FORWARD=1]="FORWARD",e[e.RECURSIVE=2]="RECURSIVE"}(aG||(aG={}));class cG extends Sl{sessionId=xF();ongoingRequests=new Set;contactedPeers=new Set;failedHopCounter=0;successfulHopCounter=0;stopped=!1;options;constructor(e){super(),this.options=e}onRequestFailed(e){if(sG.trace("onRequestFailed() sessionId: "+this.sessionId),this.stopped)return;if(this.ongoingRequests.has(e)&&this.ongoingRequests.delete(e),this.deleteParallelRootIfSource(e),this.failedHopCounter+=1,this.failedHopCounter>=2)return sG.trace(`Stopping routing after 2 failed attempts for sessionId: ${this.sessionId}`),void this.emitFailure();const t=this.updateAndGetRoutablePeers();0===t.length&&0===this.ongoingRequests.size?(sG.trace("routing failed, emitting routingFailed sessionId: "+this.sessionId),this.emitFailure()):(sG.trace("routing failed, retrying to route sessionId: "+this.sessionId+" failedHopCounter: "+this.failedHopCounter),this.sendMoreRequests(t))}emitFailure(){this.successfulHopCounter>=1?this.emit("partialSuccess"):this.emit("routingFailed")}onRequestSucceeded(){if(sG.trace("onRequestSucceeded() sessionId: "+this.sessionId),this.stopped)return;if(this.successfulHopCounter+=1,this.successfulHopCounter>=this.options.parallelism)return void this.emit("routingSucceeded");const e=this.updateAndGetRoutablePeers();0===e.length?this.emit("routingSucceeded"):e.length>0&&0===this.ongoingRequests.size&&this.sendMoreRequests(e)}async sendRouteMessageRequest(e){if(this.stopped)return!1;const t={...this.options.routedMessage,routingPath:this.options.routedMessage.routingPath.concat([this.options.localPeerDescriptor])};return this.options.mode===aG.FORWARD?e.getRouterRpcRemote().forwardMessage(t):this.options.mode===aG.RECURSIVE?e.getRecursiveOperationRpcRemote().routeRequest(t):e.getRouterRpcRemote().routeMessage(t)}updateAndGetRoutablePeers(){sG.trace("getRoutablePeers() sessionId: "+this.sessionId);const e=eG(this.options.routedMessage),t=e?Mj(e):void 0,r=_j(this.options.routedMessage.target);let n;if(this.options.routingTablesCache.has(r,t)&&this.options.routingTablesCache.get(r,t).getSize()>0)n=this.options.routingTablesCache.get(r,t);else{n=new Dj({referenceId:_j(this.options.routedMessage.target),maxSize:5,allowToContainReferenceId:!0,nodeIdDistanceLimit:t});const e=this.options.getConnections().map((e=>new oG(e,this.options.localPeerDescriptor,this.options.rpcCommunicator)));n.addContacts(e),this.options.routingTablesCache.set(r,n,t)}return n.getClosestContacts().filter((e=>!this.contactedPeers.has(e.getNodeId())&&!this.options.excludedNodeIds.has(e.getNodeId())))}sendMoreRequests(e){if(sG.trace("sendMoreRequests() sessionId: "+this.sessionId),!this.stopped)if(0!==e.length)for(;this.ongoingRequests.size<this.options.parallelism&&e.length>0&&!this.stopped;){const t=e.shift();sG.trace(`Sending routeMessage request to contact: ${Mj(t.getPeerDescriptor())} (sessionId=${this.sessionId})`),this.contactedPeers.add(t.getNodeId()),this.ongoingRequests.add(t.getNodeId()),this.addParallelRootIfSource(t.getNodeId()),setImmediate((async()=>{try{await this.sendRouteMessageRequest(t)?this.onRequestSucceeded():this.onRequestFailed(t.getNodeId())}catch(e){sG.debug("Unable to route message ",{err:e})}finally{sG.trace("sendRouteMessageRequest returned")}}))}else this.emitFailure()}addParallelRootIfSource(e){this.options.mode===aG.RECURSIVE&&xj(this.options.localPeerDescriptor,this.options.routedMessage.sourcePeer)&&this.options.routedMessage.parallelRootNodeIds.push(e)}deleteParallelRootIfSource(e){this.options.mode===aG.RECURSIVE&&xj(this.options.localPeerDescriptor,this.options.routedMessage.sourcePeer)&&ej(this.options.routedMessage.parallelRootNodeIds,e)}stop(){this.stopped=!0,this.emit("stopped"),this.removeAllListeners()}}const uG=new Bv("RecursiveOperationSessionRpcRemote");class lG extends wz{sendResponse(e,t,r,n){const i={routingPath:e,closestConnectedNodes:t,dataEntries:r,noCloserNodesFound:n};this.getClient().sendResponse(i,this.formDhtRpcOptions()).catch((e=>{uG.trace("Failed to send RecursiveOperationResponse")}))}}const hG=new Bv("RecursiveOperationSessionRpcLocal");class dG{options;constructor(e){this.options=e}async sendResponse(e,t){const r=Mj(t.incomingSourceDescriptor);return hG.trace("RecursiveOperationResponse arrived: "+JSON.stringify(e)),this.options.onResponseReceived(r,e.routingPath,e.closestConnectedNodes,e.dataEntries,e.noCloserNodesFound),{}}}const fG=1e4;class pG extends Sl{id=xF();rpcCommunicator;results;foundData=new Map;allKnownHops=new Set;reportedHops=new Set;timeoutTask;completionEventEmitted=!1;noCloserNodesReceivedCounter=0;noCloserNodesReceivedFrom=new Set;options;constructor(e){super(),this.options=e,this.results=new Dj({referenceId:e.targetId,maxSize:10,allowToContainReferenceId:!0}),this.rpcCommunicator=new Kz(this.id,e.transport,{rpcRequestTimeout:fG}),this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new dG({onResponseReceived:(e,t,r,n,i)=>{this.onResponseReceived(e,t,r,n,i)}});this.rpcCommunicator.registerRpcNotification(fq,"sendResponse",((t,r)=>e.sendResponse(t,r)))}start(e){const t=this.wrapRequest(e);this.options.doRouteRequest(t)}wrapRequest(e){const t={sessionId:this.getId(),operation:this.options.operation};return{message:{messageId:xF(),serviceId:e,body:{oneofKind:"recursiveOperationRequest",recursiveOperationRequest:t}},requestId:xF(),target:Nj(this.options.targetId),sourcePeer:this.options.localPeerDescriptor,reachableThrough:[],routingPath:[],parallelRootNodeIds:[]}}isCompleted(){const e=new Set(this.allKnownHops);return this.reportedHops.forEach((t=>{e.delete(t)})),this.noCloserNodesReceivedCounter>=1&&0===e.size&&(!(this.options.operation!==Qj.FETCH_DATA||!(this.hasNonStaleData()||this.noCloserNodesReceivedCounter>=this.options.waitedRoutingPathCompletions))||this.options.operation!==Qj.FETCH_DATA)}hasNonStaleData(){return Array.from(this.foundData.values()).some((e=>!1===e.stale))}onResponseReceived(e,t,r,n,i){this.addKnownHops(t),t.length>=1&&this.setHopAsReported(t[t.length-1]),r.forEach((e=>{this.results.addContact(new CK(e))})),this.processFoundData(n),(i||this.noCloserNodesReceivedFrom.has(e))&&this.onNoCloserPeersFound(e)}addKnownHops(e){const t=Mj(this.options.localPeerDescriptor);e.forEach((e=>{const r=Mj(e);t!==r&&this.allKnownHops.add(r)}))}setHopAsReported(e){const t=Mj(this.options.localPeerDescriptor),r=Mj(e);t!==r&&this.reportedHops.add(r),this.isCompleted()&&!this.completionEventEmitted&&this.isCompleted()&&(this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0),this.emit("completed"),this.completionEventEmitted=!0)}processFoundData(e){e.forEach((e=>{const t=_j(e.creator),r=this.foundData.get(t);(!r||r.createdAt<e.createdAt||r.createdAt<=e.createdAt&&e.deleted)&&this.foundData.set(t,e)}))}onNoCloserPeersFound(e){this.noCloserNodesReceivedCounter+=1,this.noCloserNodesReceivedFrom.add(e),this.isCompleted()?(this.emit("completed"),this.completionEventEmitted=!0,this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0)):this.timeoutTask||this.completionEventEmitted||(this.timeoutTask=setTimeout((()=>{this.completionEventEmitted||(this.emit("completed"),this.completionEventEmitted=!0)}),4e3))}getResults(){return{closestNodes:this.results.getClosestContacts().map((e=>e.getPeerDescriptor())),dataEntries:Array.from(this.foundData.values())}}getId(){return this.id}stop(){this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0),this.rpcCommunicator.destroy(),this.emit("completed")}}const gG=new Bv("RouterRpcLocal"),mG=(e,t)=>({requestId:e.requestId,error:t});class yG{options;constructor(e){this.options=e}async routeMessage(e){return this.options.duplicateRequestDetector.isMostLikelyDuplicate(e.requestId)?(gG.trace(`Routing message ${e.requestId} from ${Mj(e.sourcePeer)} to ${_j(e.target)} is likely a duplicate`),mG(e,Xj.DUPLICATE)):(gG.trace(`Processing received routeMessage ${e.requestId}`),this.options.duplicateRequestDetector.add(e.requestId),yw(this.options.localPeerDescriptor.nodeId,e.target)?(gG.trace(`routing message targeted to self ${e.requestId}`),this.options.setForwardingEntries(e),this.options.handleMessage(e.message),mG(e)):this.options.doRouteMessage(e))}async forwardMessage(e){return this.options.duplicateRequestDetector.isMostLikelyDuplicate(e.requestId)?(gG.trace(`Forwarding message ${e.requestId} from ${Mj(e.sourcePeer)} to ${_j(e.target)} is likely a duplicate`),mG(e,Xj.DUPLICATE)):(gG.trace(`Processing received forward routeMessage ${e.requestId}`),this.options.duplicateRequestDetector.add(e.requestId),yw(this.options.localPeerDescriptor.nodeId,e.target)?this.forwardToDestination(e):this.options.doRouteMessage(e,aG.FORWARD))}forwardToDestination(e){gG.trace(`Forwarding found message targeted to self ${e.requestId}`);const t=e.message;return xj(this.options.localPeerDescriptor,t.targetDescriptor)?(this.options.handleMessage(t),mG(e)):this.options.doRouteMessage({...e,requestId:xF(),target:t.targetDescriptor.nodeId})}}const bG=new Bv("RecursiveOperationRpcLocal");class wG{options;constructor(e){this.options=e}async routeRequest(e){if(this.options.isMostLikelyDuplicate(e.requestId))return mG(e,Xj.DUPLICATE);const t=Mj(eG(e)??e.sourcePeer);return bG.trace(`Received routeRequest call from ${t}`),this.options.addToDuplicateDetector(e.requestId),this.options.doRouteRequest(e)}}const vG=new Bv("RecursiveOperationManager");class EG{ongoingSessions=new Map;stopped=!1;options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new wG({doRouteRequest:e=>this.doRouteRequest(e),addContact:e=>this.options.addContact(e),isMostLikelyDuplicate:e=>this.options.router.isMostLikelyDuplicate(e),addToDuplicateDetector:e=>this.options.router.addToDuplicateDetector(e)});this.options.rpcCommunicator.registerRpcMethod(wq,vq,"routeRequest",(async t=>this.stopped?mG(t,Xj.STOPPED):e.routeRequest(t)))}async execute(e,t,r,n=!0){if(this.stopped)return{closestNodes:[]};const i=new pG({transport:this.options.sessionTransport,targetId:e,localPeerDescriptor:this.options.localPeerDescriptor,waitedRoutingPathCompletions:this.options.connectionsView.getConnectionCount()>1?2:1,operation:t,doRouteRequest:e=>this.doRouteRequest(e,r)});if(0===this.options.connectionsView.getConnectionCount()){const t=Array.from(this.options.localDataStore.values(e));return i.onResponseReceived(Mj(this.options.localPeerDescriptor),[this.options.localPeerDescriptor],[this.options.localPeerDescriptor],t,!0),i.getResults()}if(this.ongoingSessions.set(i.getId(),i),!0===n)try{const e=eE(i,"completed",fG);i.start(this.options.serviceId),await e}catch(e){vG.debug("start failed",{err:e})}else i.start(this.options.serviceId),await Qv(50);if(t===Qj.FETCH_DATA){const t=Array.from(this.options.localDataStore.values(e));t.length>0&&this.sendResponse([this.options.localPeerDescriptor],this.options.localPeerDescriptor,i.getId(),[],t,!0)}else t===Qj.DELETE_DATA&&this.options.localDataStore.markAsDeleted(e,Mj(this.options.localPeerDescriptor));return this.ongoingSessions.delete(i.getId()),i.stop(),i.getResults()}sendResponse(e,t,r,n,i,s=!1){if(xj(this.options.localPeerDescriptor,t)&&this.ongoingSessions.has(r))this.ongoingSessions.get(r).onResponseReceived(Mj(this.options.localPeerDescriptor),e,n,i,s);else{const o=new Kz(r,this.options.sessionTransport,{rpcRequestTimeout:fG});new lG(this.options.localPeerDescriptor,t,o,Xq,1e4).sendResponse(e,n,i,s),o.destroy()}}doRouteRequest(e,t){if(this.stopped)return mG(e,Xj.STOPPED);const r=_j(e.target),n=e.message.body.recursiveOperationRequest,i=this.getClosestConnectedNodes(r,5),s=n.operation===Qj.FETCH_DATA?Array.from(this.options.localDataStore.values(r)):[];if(n.operation===Qj.DELETE_DATA&&this.options.localDataStore.markAsDeleted(r,Mj(e.sourcePeer)),yw(this.options.localPeerDescriptor.nodeId,e.target))return this.sendResponse(e.routingPath,e.sourcePeer,n.sessionId,i,s,!0),mG(e);{const o=this.options.router.doRouteMessage(e,aG.RECURSIVE,t);if(void 0===o.error||o.error===Xj.NO_TARGETS){const t=o.error===Xj.NO_TARGETS||i.length>0&&eG(e)&&!this.isPeerCloserToIdThanSelf(i[0],r);this.sendResponse(e.routingPath,e.sourcePeer,n.sessionId,i,s,t)}return o}}getClosestConnectedNodes(e,t){const r=this.options.connectionsView.getConnections().map((e=>this.options.createDhtNodeRpcRemote(e))),n=new Dj({referenceId:e,maxSize:t,allowToContainReferenceId:!0});return n.addContacts(r),n.getClosestContacts(t).map((e=>e.getPeerDescriptor()))}isPeerCloserToIdThanSelf(e,t){const r=Nj(t);return Tj(e.nodeId,r)<Tj(this.options.localPeerDescriptor.nodeId,r)}stop(){this.stopped=!0,this.ongoingSessions.forEach(((e,t)=>{e.stop()})),this.ongoingSessions.clear()}}const AG=(e,t)=>e+(t??""),SG={max:1e3,maxAge:15e3};class kG{tables=new hj(SG);get(e,t){return this.tables.get(AG(e,t))}set(e,t,r){this.tables.set(AG(e,r),t)}has(e,t){return this.tables.has(AG(e,t))}onNodeDisconnected(e){this.tables.forEach((t=>t.removeContact(e)))}onNodeConnected(e){this.tables.forEach((t=>t.addContact(e)))}reset(){this.tables.forEach((e=>e.stop())),this.tables.clear()}}const RG=new Bv("Router");class CG{forwardingTable=new Map;routingTablesCache=new kG;ongoingRoutingSessions=new Map;duplicateRequestDetector=new Bj(1e4);stopped=!1;options;messagesRouted=0;messagesSent=0;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new yG({doRouteMessage:(e,t)=>this.doRouteMessage(e,t),setForwardingEntries:e=>this.setForwardingEntries(e),duplicateRequestDetector:this.duplicateRequestDetector,localPeerDescriptor:this.options.localPeerDescriptor,handleMessage:this.options.handleMessage});this.options.rpcCommunicator.registerRpcMethod(wq,vq,"routeMessage",(async t=>this.stopped?mG(t,Xj.STOPPED):e.routeMessage(t))),this.options.rpcCommunicator.registerRpcMethod(wq,vq,"forwardMessage",(async t=>this.stopped?mG(t,Xj.STOPPED):e.forwardMessage(t)))}send(e,t){e.sourceDescriptor=this.options.localPeerDescriptor;const r=e.targetDescriptor,n=this.forwardingTable.get(Mj(r));if(n&&n.peerDescriptors.length>0){const r={message:e,requestId:xF(),target:n.peerDescriptors[0].nodeId,sourcePeer:this.options.localPeerDescriptor,reachableThrough:t,routingPath:[],parallelRootNodeIds:[]},i=this.doRouteMessage(r,aG.FORWARD);if(void 0!==i.error){const e="Could not forward message with error "+i.error;throw RG.debug(e),new Error(e)}}else{const n={message:e,requestId:xF(),target:r.nodeId,sourcePeer:this.options.localPeerDescriptor,reachableThrough:t,routingPath:[],parallelRootNodeIds:[]},i=this.doRouteMessage(n,aG.ROUTE);if(void 0!==i.error){const e="Could not route message with error "+i.error;throw RG.debug(e),new Error(e)}}this.messagesSent+=1}doRouteMessage(e,t=aG.ROUTE,r){if(this.stopped)return mG(e,Xj.STOPPED);RG.trace(`Routing message ${e.requestId} from ${Mj(e.sourcePeer)} to ${_j(e.target)}`);const n=this.createRoutingSession(e,t,r),i=n.updateAndGetRoutablePeers();if(i.length>0){this.addRoutingSession(n),RG.trace("starting to raceForEvent from routingSession: "+n.sessionId);const t=tE(n,["routingSucceeded","partialSuccess","routingFailed","stopped"],1e4);return setImmediate((async()=>{try{await t,RG.trace("raceForEvent ended from routingSession: "+n.sessionId)}catch{RG.trace("raceForEvent timed out for routingSession "+n.sessionId)}n.stop(),this.removeRoutingSession(n.sessionId)})),n.sendMoreRequests(i),this.messagesRouted+=1,mG(e)}return RG.trace("no targets",{sessionId:n.sessionId}),mG(e,Xj.NO_TARGETS)}createRoutingSession(e,t,r){const n=new Set(e.routingPath.map((e=>Mj(e))));return r&&n.add(r),e.parallelRootNodeIds.forEach((e=>{n.add(e)})),new cG({rpcCommunicator:this.options.rpcCommunicator,localPeerDescriptor:this.options.localPeerDescriptor,routedMessage:e,parallelism:xj(this.options.localPeerDescriptor,e.sourcePeer)?2:1,mode:t,excludedNodeIds:n,routingTablesCache:this.routingTablesCache,getConnections:this.options.getConnections})}isMostLikelyDuplicate(e){return this.duplicateRequestDetector.isMostLikelyDuplicate(e)}addToDuplicateDetector(e){this.duplicateRequestDetector.add(e)}addRoutingSession(e){this.ongoingRoutingSessions.set(e.sessionId,e)}removeRoutingSession(e){this.ongoingRoutingSessions.delete(e)}onNodeConnected(e){const t=new oG(e,this.options.localPeerDescriptor,this.options.rpcCommunicator);this.routingTablesCache.onNodeConnected(t)}onNodeDisconnected(e){this.routingTablesCache.onNodeDisconnected(Mj(e))}resetCache(){this.routingTablesCache.reset()}stop(){this.stopped=!0,this.ongoingRoutingSessions.forEach(((e,t)=>{e.stop()})),this.ongoingRoutingSessions.clear(),this.forwardingTable.forEach((e=>{clearTimeout(e.timeout)})),this.forwardingTable.clear(),this.duplicateRequestDetector.clear(),this.routingTablesCache.reset()}getDiagnosticInfo(){return{messagesRouted:this.messagesRouted,messagesSent:this.messagesSent}}setForwardingEntries(e){const t=e.reachableThrough.filter((e=>!xj(e,this.options.localPeerDescriptor)));if(t.length>0){const r=Mj(e.sourcePeer);if(this.forwardingTable.has(r)){const e=this.forwardingTable.get(r);clearTimeout(e.timeout),this.forwardingTable.delete(r)}const n={peerDescriptors:t,timeout:setTimeout((()=>{this.forwardingTable.delete(r)}),1e4)};this.forwardingTable.set(r,n)}}}class IG{maxTtl;constructor(e){this.maxTtl=e}store=new Map;storeEntry(e){const t=_j(e.key),r=_j(e.creator);if(this.store.has(t)||this.store.set(t,new yE((e=>Math.min(e.ttl,this.maxTtl)))),this.store.get(t).has(r)){const n=1e3*e.createdAt.seconds+e.createdAt.nanos/1e6,i=this.store.get(t).get(r);if(1e3*i.createdAt.seconds+i.createdAt.nanos/1e6>=n)return!1}return this.store.get(t).set(r,e),!0}markAsDeleted(e,t){const r=this.store.get(e);if(!r?.has(t))return!1;return r.get(t).deleted=!0,!0}*values(e){if(void 0!==e){const t=this.store.get(e);void 0!==t&&(yield*t.values())}else for(const e of this.store.values())yield*e.values()}keys(){return this.store.keys()}setAllEntriesAsStale(e){this.store.get(e)?.forEach((e=>{e.stale=!0}))}deleteEntry(e,t){const r=this.store.get(e)?.get(t);r&&(this.store.get(e)?.delete(t),0===this.store.get(e)?.size()&&this.store.delete(e))}clear(){this.store.forEach((e=>e.clear())),this.store.clear()}}const PG=new Bv("StoreRpcLocal");class TG{options;constructor(e){this.options=e}async storeData(e){PG.trace("storeData()");const t=_j(e.key),r=this.isLocalNodeStorer(t);return this.options.localDataStore.storeEntry({key:e.key,data:e.data,creator:e.creator,createdAt:e.createdAt,storedAt:Jj.now(),ttl:e.ttl,stale:!r,deleted:!1}),r||this.options.localDataStore.setAllEntriesAsStale(t),{}}async replicateData(e,t){PG.trace("server-side replicateData()");const r=e.entry;this.options.localDataStore.storeEntry(r)&&this.replicateDataToNeighbors(t.incomingSourceDescriptor,e.entry);const n=_j(r.key);return this.isLocalNodeStorer(n)||this.options.localDataStore.setAllEntriesAsStale(n),PG.trace("server-side replicateData() at end"),{}}isLocalNodeStorer(e){return this.options.getStorers(e).some((e=>xj(e,this.options.localPeerDescriptor)))}replicateDataToNeighbors(e,t){const r=_j(t.key),n=this.options.getStorers(r);(xj(n[0],this.options.localPeerDescriptor)?n:[n[0]]).filter((t=>!xj(t,e)&&!xj(t,this.options.localPeerDescriptor))).forEach((e=>{setImmediate((()=>{pE((()=>this.options.replicateDataToContact(t,e)))}))}))}}const _G=new Bv("StoreManager");class NG{options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new TG({localPeerDescriptor:this.options.localPeerDescriptor,localDataStore:this.options.localDataStore,replicateDataToContact:(e,t)=>this.replicateDataToContact(e,t),getStorers:e=>this.getStorers(e)});this.options.rpcCommunicator.registerRpcMethod(rq,nq,"storeData",(t=>e.storeData(t))),this.options.rpcCommunicator.registerRpcNotification(oq,"replicateData",((t,r)=>e.replicateData(t,r)))}onContactAdded(e){for(const t of this.options.localDataStore.keys())this.replicateAndUpdateStaleState(t,e)}replicateAndUpdateStaleState(e,t){const r=this.getStorers(e),n=r.filter((e=>!xj(e,t)));xj(n[0],this.options.localPeerDescriptor)?r.some((e=>xj(e,t)))&&setImmediate((async()=>{const r=Array.from(this.options.localDataStore.values(e));await Promise.all(r.map((async e=>this.replicateDataToContact(e,t))))})):r.some((e=>xj(e,this.options.localPeerDescriptor)))||this.options.localDataStore.setAllEntriesAsStale(e)}async replicateDataToContact(e,t){const r=this.options.createRpcRemote(t);try{await r.replicateData({entry:e},!0)}catch(e){_G.trace("replicateData() threw an exception "+e)}}async storeDataToDht(e,t,r){_G.debug(`Storing data to DHT ${this.options.serviceId}`);const n=(await this.options.recursiveOperationManager.execute(e,Qj.FIND_CLOSEST_NODES)).closestNodes,i=[],s=this.options.highestTtl,o=Jj.now();for(let a=0;a<n.length&&i.length<this.options.redundancyFactor;a++){const c=Nj(e),u=Nj(r);if(xj(this.options.localPeerDescriptor,n[a])){this.options.localDataStore.storeEntry({key:c,data:t,creator:u,createdAt:o,storedAt:Jj.now(),ttl:s,stale:!1,deleted:!1}),i.push(n[a]);continue}const l=this.options.createRpcRemote(n[a]);try{await l.storeData({key:c,data:t,creator:u,createdAt:o,ttl:s}),i.push(n[a]),_G.trace("remote.storeData() success")}catch(e){_G.trace("remote.storeData() threw an exception "+e)}}return i}async replicateDataToClosestNodes(){const e=Array.from(this.options.localDataStore.values());await Promise.all(e.map((async e=>{const t=_j(e.key),r=IK(t,this.options.getNeighbors(),{maxCount:this.options.redundancyFactor});await Promise.all(r.map((async t=>{const r=this.options.createRpcRemote(t);try{await r.replicateData({entry:e},!1)}catch(e){_G.trace("Failed to replicate data in replicateDataToClosestNodes",{err:e})}})))})))}getStorers(e,t){return IK(e,[...this.options.getNeighbors(),this.options.localPeerDescriptor],{maxCount:this.options.redundancyFactor,excludedNodeIds:void 0!==t?new Set([Mj(t)]):void 0})}async destroy(){await this.replicateDataToClosestNodes()}}class MG extends wz{async storeData(e){const t=this.formDhtRpcOptions();try{await this.getClient().storeData(e,t)}catch(e){const t=Mj(this.getPeerDescriptor()),r=Mj(this.getLocalPeerDescriptor());throw new Error(`Could not store data to ${t} from ${r} ${e}`)}}async replicateData(e,t){const r=this.formDhtRpcOptions({timeout:yz,notification:!0,connect:t});return this.getClient().replicateData(e,r)}}const xG=new Bv("DhtNode");class OG extends Sl{options;rpcCommunicator;transport;localPeerDescriptor;router;storeManager;localDataStore;recursiveOperationManager;peerDiscovery;peerManager;connectionsView;connectionLocker;started=!1;abortController=new AbortController;constructor(e){super(),this.options=aE({serviceId:ZK,joinParallelism:3,maxContactCount:200,numberOfNodesPerKBucket:8,joinNoProgressLimit:5,dhtJoinTimeout:6e4,peerDiscoveryQueryBatchSize:5,maxConnections:80,storeHighestTtl:6e4,storeMaxTtl:6e4,networkConnectivityTimeout:1e4,storageRedundancyFactor:5,metricsContext:new $v},e),this.validateOptions(),this.localDataStore=new IG(this.options.storeMaxTtl),this.send=this.send.bind(this)}validateOptions(){if(void 0!==this.options.nodeId){if(!/^[0-9a-fA-F]+$/.test(this.options.nodeId))throw new Error("Invalid nodeId, the nodeId should be a hex string");if(40!==this.options.nodeId.length)throw new Error("Invalid nodeId, the length of the nodeId should be 40")}if(void 0!==this.options.peerDescriptor&&20!==this.options.peerDescriptor.nodeId.length)throw new Error("Invalid peerDescriptor, the length of the nodeId should be 20 bytes");if(void 0!==this.options.transport&&void 0===this.options.connectionsView)throw new Error("connectionsView is required when transport is given")}async start(){if(this.started||this.abortController.signal.aborted)return;if(xG.trace(`Starting new Streamr Network DHT Node with serviceId ${this.options.serviceId}`),this.started=!0,this.options.websocketPortRange=void 0,this.options.peerDescriptor&&(this.options.peerDescriptor.websocket=void 0),this.options.transport)this.transport=this.options.transport,this.connectionsView=this.options.connectionsView,this.connectionLocker=this.options.connectionLocker,this.localPeerDescriptor=this.transport.getLocalPeerDescriptor();else{const e={transport:this,entryPoints:this.options.entryPoints,iceServers:this.options.iceServers,webrtcAllowPrivateAddresses:this.options.webrtcAllowPrivateAddresses,webrtcDatachannelBufferThresholdLow:this.options.webrtcDatachannelBufferThresholdLow,webrtcDatachannelBufferThresholdHigh:this.options.webrtcDatachannelBufferThresholdHigh,webrtcPortRange:this.options.webrtcPortRange,maxMessageSize:this.options.maxMessageSize,websocketServerEnableTls:this.options.websocketServerEnableTls,tlsCertificate:this.options.tlsCertificate,externalIp:this.options.externalIp,autoCertifierUrl:this.options.autoCertifierUrl,autoCertifierConfigFile:this.options.autoCertifierConfigFile,geoIpDatabaseFolder:this.options.geoIpDatabaseFolder,createLocalPeerDescriptor:e=>this.generatePeerDescriptorCallBack(e)};this.options.peerDescriptor?.websocket?(e.websocketHost=this.options.peerDescriptor.websocket.host,e.websocketPortRange={min:this.options.peerDescriptor.websocket.port,max:this.options.peerDescriptor.websocket.port}):this.options.websocketPortRange&&(e.websocketHost=this.options.websocketHost,e.websocketPortRange=this.options.websocketPortRange);const t=new Nz({createConnectorFacade:()=>new AK(e),maxConnections:this.options.maxConnections,metricsContext:this.options.metricsContext,allowIncomingPrivateConnections:this.options.allowIncomingPrivateConnections??!1});await t.start(),this.connectionsView=t,this.connectionLocker=t,this.transport=t}this.rpcCommunicator=new oz(this.options.serviceId,((e,t)=>this.transport.send(e,t)),{rpcRequestTimeout:this.options.rpcRequestTimeout}),oE(this.transport,"message",(e=>this.handleMessageFromTransport(e)),this.abortController.signal),this.initPeerManager(),this.peerDiscovery=new XK({localPeerDescriptor:this.localPeerDescriptor,joinNoProgressLimit:this.options.joinNoProgressLimit,joinTimeout:this.options.dhtJoinTimeout,serviceId:this.options.serviceId,parallelism:this.options.joinParallelism,connectionLocker:this.connectionLocker,peerManager:this.peerManager,abortSignal:this.abortController.signal,createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e)}),this.router=new CG({rpcCommunicator:this.rpcCommunicator,localPeerDescriptor:this.localPeerDescriptor,handleMessage:e=>this.handleMessageFromRouter(e),getConnections:()=>this.connectionsView.getConnections()}),this.recursiveOperationManager=new EG({rpcCommunicator:this.rpcCommunicator,router:this.router,sessionTransport:this,connectionsView:this.connectionsView,localPeerDescriptor:this.localPeerDescriptor,serviceId:this.options.serviceId,localDataStore:this.localDataStore,addContact:e=>this.peerManager.addContact(e),createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e)}),this.storeManager=new NG({rpcCommunicator:this.rpcCommunicator,recursiveOperationManager:this.recursiveOperationManager,localPeerDescriptor:this.localPeerDescriptor,serviceId:this.options.serviceId,highestTtl:this.options.storeHighestTtl,redundancyFactor:this.options.storageRedundancyFactor,localDataStore:this.localDataStore,getNeighbors:()=>this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),createRpcRemote:e=>new MG(this.localPeerDescriptor,e,this.rpcCommunicator,Yq,this.options.rpcRequestTimeout)}),this.on("nearbyContactAdded",(e=>{this.storeManager.onContactAdded(e)})),this.bindRpcLocalMethods();const e=[];!0===this.options.periodicallyPingNeighbors&&e.push((()=>this.peerManager.getNeighbors().map((e=>this.createDhtNodeRpcRemote(e.getPeerDescriptor()))))),!0===this.options.periodicallyPingRingContacts&&e.push((()=>this.peerManager.getRingContacts().getAllContacts()));for(const t of e)await Jv((async()=>{const e=t();await this.peerManager.pruneOfflineNodes(e)}),6e4,!1,this.abortController.signal)}initPeerManager(){this.peerManager=new HK({numberOfNodesPerKBucket:this.options.numberOfNodesPerKBucket,maxContactCount:this.options.maxContactCount,localNodeId:this.getNodeId(),localPeerDescriptor:this.localPeerDescriptor,connectionLocker:this.connectionLocker,lockId:this.options.serviceId,createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e),hasConnection:e=>this.connectionsView.hasConnection(e),neighborPingLimit:this.options.neighborPingLimit}),this.peerManager.on("nearbyContactRemoved",(e=>{this.emit("nearbyContactRemoved",e)})),this.peerManager.on("nearbyContactAdded",(e=>this.emit("nearbyContactAdded",e))),this.peerManager.on("randomContactRemoved",(e=>this.emit("randomContactRemoved",e))),this.peerManager.on("randomContactAdded",(e=>this.emit("randomContactAdded",e))),this.peerManager.on("ringContactRemoved",(e=>{this.emit("ringContactRemoved",e)})),this.peerManager.on("ringContactAdded",(e=>{this.emit("ringContactAdded",e)})),this.peerManager.on("kBucketEmpty",(()=>{this.peerDiscovery.isJoinOngoing()||(this.options.entryPoints&&this.options.entryPoints.length>0?setImmediate((async()=>{const e=new Set,t=new Set;await Promise.all(this.options.entryPoints.map((r=>this.peerDiscovery.rejoinDht(r,e,t))))})):this.emit("manualRejoinRequired"))})),oE(this.transport,"connected",(e=>{this.router.onNodeConnected(e),this.emit("connected",e)}),this.abortController.signal),oE(this.transport,"disconnected",((e,t)=>{if(void 0!==this.connectionLocker){const r=Mj(e);t?this.peerManager.removeContact(r):this.peerManager.removeNeighbor(r)}this.router.onNodeDisconnected(e),this.emit("disconnected",e,t)}),this.abortController.signal)}bindRpcLocalMethods(){if(!this.started||this.abortController.signal.aborted)return;const e=new TK({peerDiscoveryQueryBatchSize:this.options.peerDiscoveryQueryBatchSize,getNeighbors:()=>this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),getClosestRingContactsTo:(e,t)=>this.getClosestRingContactsTo(e,t),addContact:e=>this.peerManager.addContact(e),removeContact:e=>this.removeContact(e)});this.rpcCommunicator.registerRpcMethod(cq,uq,"getClosestPeers",((t,r)=>e.getClosestPeers(t,r))),this.rpcCommunicator.registerRpcMethod(lq,hq,"getClosestRingPeers",((t,r)=>e.getClosestRingPeers(t,r))),this.rpcCommunicator.registerRpcMethod(pq,gq,"ping",((t,r)=>e.ping(t,r))),this.rpcCommunicator.registerRpcNotification(mq,"leaveNotice",((t,r)=>e.leaveNotice(r)));const t=new MK({executeRecursiveOperation:(e,t,r)=>this.recursiveOperationManager.execute(e,t,r),storeDataToDht:(e,t,r)=>this.storeDataToDht(e,t,r)});this.rpcCommunicator.registerRpcMethod(Bq,Lq,"externalFetchData",((e,r)=>t.externalFetchData(e,r)),{timeout:1e4}),this.rpcCommunicator.registerRpcMethod(iq,sq,"externalStoreData",((e,r)=>t.externalStoreData(e,r)),{timeout:1e4})}handleMessageFromTransport(e){e.serviceId===this.options.serviceId&&this.rpcCommunicator?.handleMessageFromPeer(e)}handleMessageFromRouter(e){e.serviceId===this.options.serviceId?this.rpcCommunicator?.handleMessageFromPeer(e):this.emit("message",e)}async generatePeerDescriptorCallBack(e){if(void 0!==this.options.peerDescriptor)this.localPeerDescriptor=this.options.peerDescriptor;else{let t;void 0!==this.options.region?(t=this.options.region,xG.debug(`Using region ${t} from options when generating local PeerDescriptor`)):void 0!==e.latitude&&void 0!==e.longitude?(t=((e,t)=>{const r=[];return Object.keys(mj).forEach((n=>{const i=mj[n],s=gj({latitude:e,longitude:t},{latitude:i[1],longitude:i[2]});r.push([i[0],s])})),r.sort(((e,t)=>e[1]-t[1])),r[0][0]})(e.latitude,e.longitude),xG.debug(`Using region ${t} from GeoIP when generating local PeerDescriptor`)):(t=await(async(e=36e5)=>{if(void 0===Ej||void 0===Aj||Date.now()-Aj>e){const e=await Sj();return Ej=e,Aj=Date.now(),e}return Ej})(),xG.debug(`Using region ${t} from CDN when generating local PeerDescriptor`)),this.localPeerDescriptor=await RK(e,t,this.options.nodeId)}return this.localPeerDescriptor}getClosestContacts(e){return this.peerManager.getNearbyContacts().getClosestContacts(e).map((e=>e.getPeerDescriptor()))}getRandomContacts(e){return this.peerManager.getRandomContacts().getContacts(e).map((e=>e.getPeerDescriptor()))}getRingContacts(){const e=this.peerManager.getRingContacts().getClosestContacts();return{left:e.left.map((e=>e.getPeerDescriptor())),right:e.right.map((e=>e.getPeerDescriptor()))}}getClosestRingContactsTo(e,t){const r=this.peerManager.getClosestRingContactsTo(e,t);return{left:r.left.map((e=>e.getPeerDescriptor())),right:r.right.map((e=>e.getPeerDescriptor()))}}getNodeId(){return Mj(this.localPeerDescriptor)}getNeighborCount(){return this.peerManager.getNeighborCount()}removeContact(e){this.started&&this.peerManager.removeContact(e)}async send(e){if(!this.started||this.abortController.signal.aborted)return;const t=this.peerDiscovery.isJoinOngoing()?this.getConnectedEntryPoints():[];this.router.send(e,t)}getConnectedEntryPoints(){return void 0!==this.options.entryPoints?this.options.entryPoints.filter((e=>this.connectionsView.hasConnection(Mj(e)))):[]}async joinDht(e,t,r){if(!this.started)throw new Error("Cannot join DHT before calling start() on DhtNode");await this.peerDiscovery.joinDht(e,t,r)}async joinRing(){if(!this.started)throw new Error("Cannot join ring before calling start() on DhtNode");await this.peerDiscovery.joinRing()}async storeDataToDht(e,t,r){return this.executeRecursiveOperation((()=>this.storeManager.storeDataToDht(e,t,r??this.getNodeId())),(r=>this.storeDataToDhtViaPeer(e,t,r)))}async storeDataToDhtViaPeer(e,t,r){const n=new OK(this.localPeerDescriptor,r,this.rpcCommunicator,nz);return await n.storeData(e,t)}async fetchDataFromDht(e){return this.executeRecursiveOperation((async()=>(await this.recursiveOperationManager.execute(e,Qj.FETCH_DATA)).dataEntries??[]),(t=>this.fetchDataFromDhtViaPeer(e,t)))}async fetchDataFromDhtViaPeer(e,t){const r=new OK(this.localPeerDescriptor,t,this.rpcCommunicator,nz);return await r.externalFetchData(e)}async executeRecursiveOperation(e,t){const r=this.getConnectedEntryPoints();return this.peerDiscovery.isJoinOngoing()&&r.length>0?t(oA(r)):e()}async deleteDataFromDht(e,t){this.abortController.signal.aborted||await this.recursiveOperationManager.execute(e,Qj.DELETE_DATA,void 0,t)}async findClosestNodesFromDht(e){return this.executeRecursiveOperation((async()=>(await this.recursiveOperationManager.execute(e,Qj.FIND_CLOSEST_NODES)).closestNodes),(t=>this.findClosestNodesViaPeer(e,t)))}async findClosestNodesViaPeer(e,t){const r=new OK(this.localPeerDescriptor,t,this.rpcCommunicator,nz);return await r.externalFindClosestNode(e)}getTransport(){return this.transport}getLocalPeerDescriptor(){return this.localPeerDescriptor}getNeighbors(){return this.started?this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())):[]}getConnectionsView(){return this.connectionsView}getLocalLockedConnectionCount(){return this.connectionLocker.getLocalLockedConnectionCount()}getRemoteLockedConnectionCount(){return this.connectionLocker.getRemoteLockedConnectionCount()}getWeakLockedConnectionCount(){return this.connectionLocker.getWeakLockedConnectionCount()}async waitForNetworkConnectivity(){await iE((()=>this.connectionsView.getConnectionCount()>0),this.options.networkConnectivityTimeout,100,this.abortController.signal)}hasJoined(){return this.peerDiscovery.isJoinCalled()}getDiagnosticInfo(){return{localPeerDescriptor:this.localPeerDescriptor,transport:this.transport.getDiagnosticInfo(),router:this.router.getDiagnosticInfo(),neighborCount:this.getNeighborCount(),nearbyContactCount:Array.from(this.peerManager.getNearbyContacts().getAllContactsInUndefinedOrder()).length,randomContactCount:this.peerManager.getRandomContacts().getSize()}}async stop(){!this.abortController.signal.aborted&&this.started&&(xG.trace("stop()"),this.abortController.abort(),await this.storeManager.destroy(),this.localDataStore.clear(),this.peerManager?.stop(),this.rpcCommunicator.stop(),this.router.stop(),this.recursiveOperationManager.stop(),void 0===this.options.transport&&await this.transport.stop(),this.transport=void 0,this.connectionLocker=void 0,this.removeAllListeners())}createDhtNodeRpcRemote(e){return new NK(this.localPeerDescriptor,e,this.options.serviceId,this.rpcCommunicator,this.options.rpcRequestTimeout)}}var DG,BG,LG,FG,UG,jG,qG,zG,KG,GG;function VG(){if(FG)return LG;return FG=1,LG=function(e,t,r){return e==e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e},LG}!function(e){e[e.eu_central_1=0]="eu_central_1",e[e.eu_west_1=1]="eu_west_1",e[e.eu_west_2=2]="eu_west_2",e[e.eu_west_3=3]="eu_west_3",e[e.eu_north_1=4]="eu_north_1",e[e.us_east_1=5]="us_east_1",e[e.us_east_2=6]="us_east_2",e[e.us_west_1=7]="us_west_1",e[e.us_west_2=8]="us_west_2",e[e.ca_central_1=9]="ca_central_1",e[e.ap_south_1=10]="ap_south_1",e[e.ap_northeast_2=11]="ap_northeast_2",e[e.ap_southeast_1=12]="ap_southeast_1",e[e.ap_southeast_2=13]="ap_southeast_2",e[e.ap_northeast_1=14]="ap_northeast_1",e[e.sa_east_1=15]="sa_east_1"}(DG||(DG={})),new Bv("Simulator"),function(e){e.NONE="NONE",e.RANDOM="RANDOM",e.REAL="REAL",e.FIXED="FIXED"}(BG||(BG={}));var HG=function(){if(GG)return KG;GG=1;var e=function(){if(jG)return UG;jG=1;var e=VG(),t=Th(),r=CU();return UG=function(n,i){return r(t(n),e(i,0,n.length))},UG}(),t=function(){if(zG)return qG;zG=1;var e=VG(),t=CU(),r=nA();return qG=function(n,i){var s=r(n);return t(s,e(i,0,s.length))},qG}(),r=qu(),n=_d(),i=Ue();return KG=function(s,o,a){return o=(a?n(s,o,a):void 0===o)?1:i(o),(r(s)?e:t)(s,o)},KG}(),$G=n(HG);class WG{tail;head;length=0;static create(e=[]){return new WG(e)}constructor(e=[]){for(const t of e)this.push(t)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");const t=e.next,r=e.prev;return t&&(t.prev=r),r&&(r.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=r),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,t}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);const t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);const t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let t=0,r=e.length;t<r;t++)QG(this,e[t]);return this.length}unshift(...e){for(var t=0,r=e.length;t<r;t++)ZG(this,e[t]);return this.length}pop(){if(!this.tail)return;const e=this.tail.value,t=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,t.list=void 0,this.length--,e}shift(){if(!this.head)return;const e=this.head.value,t=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,t.list=void 0,this.length--,e}forEach(e,t){t=t||this;for(let r=this.head,n=0;r;n++)e.call(t,r.value,n,this),r=r.next}forEachReverse(e,t){t=t||this;for(let r=this.tail,n=this.length-1;r;n--)e.call(t,r.value,n,this),r=r.prev}get(e){let t=0,r=this.head;for(;r&&t<e;t++)r=r.next;if(t===e&&r)return r.value}getReverse(e){let t=0,r=this.tail;for(;r&&t<e;t++)r=r.prev;if(t===e&&r)return r.value}map(e,t){t=t||this;const r=new WG;for(let n=this.head;n;)r.push(e.call(t,n.value,this)),n=n.next;return r}mapReverse(e,t){t=t||this;var r=new WG;for(let n=this.tail;n;)r.push(e.call(t,n.value,this)),n=n.prev;return r}reduce(e,t){let r,n=this.head;if(arguments.length>1)r=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;n;i++)r=e(r,n.value,i),n=n.next;return r}reduceReverse(e,t){let r,n=this.tail;if(arguments.length>1)r=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(let t=this.length-1;n;t--)r=e(r,n.value,t),n=n.prev;return r}toArray(){const e=new Array(this.length);for(let t=0,r=this.head;r;t++)e[t]=r.value,r=r.next;return e}toArrayReverse(){const e=new Array(this.length);for(let t=0,r=this.tail;r;t++)e[t]=r.value,r=r.prev;return e}slice(e=0,t=this.length){t<0&&(t+=this.length),e<0&&(e+=this.length);const r=new WG;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);let n=this.head,i=0;for(i=0;n&&i<e;i++)n=n.next;for(;n&&i<t;i++,n=n.next)r.push(n.value);return r}sliceReverse(e=0,t=this.length){t<0&&(t+=this.length),e<0&&(e+=this.length);const r=new WG;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);let n=this.length,i=this.tail;for(;i&&n>t;n--)i=i.prev;for(;i&&n>e;n--,i=i.prev)r.push(i.value);return r}splice(e,t=0,...r){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let n=this.head;for(let t=0;n&&t<e;t++)n=n.next;const i=[];for(let e=0;n&&e<t;e++)i.push(n.value),n=this.removeNode(n);n?n!==this.tail&&(n=n.prev):n=this.tail;for(const e of r)n=JG(this,n,e);return i}reverse(){const e=this.head,t=this.tail;for(let t=e;t;t=t.prev){const e=t.prev;t.prev=t.next,t.next=e}return this.head=t,this.tail=e,this}}function JG(e,t,r){const n=t,i=t?t.next:e.head,s=new YG(r,n,i,e);return void 0===s.next&&(e.tail=s),void 0===s.prev&&(e.head=s),e.length++,s}function QG(e,t){e.tail=new YG(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function ZG(e,t){e.head=new YG(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}class YG{list;next;prev;value;constructor(e,t,r,n){this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}}class XG{rpcCommunicator;constructor(e){this.rpcCommunicator=new Kz("external-network-service",e)}registerRpcMethod(e,t,r,n){this.rpcCommunicator.registerRpcMethod(e,t,r,n)}createRpcClient(e){return iU(new e(this.rpcCommunicator.getRpcClientTransport()))}destroy(){this.rpcCommunicator.destroy()}}const eV=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}},tV=new Bv("PeerDescriptorStoreManager");class rV{abortController;options;isLocalNodeStored_=!1;constructor(e){this.options=e,this.abortController=new AbortController}async fetchNodes(){tV.trace("Fetch data",{key:this.options.key});try{const e=await this.options.fetchDataFromDht(this.options.key);return e.filter((e=>!e.deleted)).map((e=>eV.unpack(e.data,yq)))}catch{return[]}}async storeAndKeepLocalNode(){this.abortController.signal.aborted||(this.isLocalNodeStored_=!0,await this.storeLocalNode(),await this.keepLocalNode())}async storeLocalNode(){const e=this.options.localPeerDescriptor,t=eV.pack(e,yq);try{await this.options.storeDataToDht(this.options.key,t)}catch{tV.warn("Failed to store local node",{key:this.options.key})}}async keepLocalNode(){await Jv((async()=>{tV.trace("Attempting to keep local node",{key:this.options.key});try{const e=await this.fetchNodes();(e.length<8||e.some((e=>xj(e,this.options.localPeerDescriptor))))&&await this.storeLocalNode()}catch{tV.debug("Failed to keep local node",{key:this.options.key})}}),this.options.storeInterval??6e4,!1,this.abortController.signal)}isLocalNodeStored(){return this.isLocalNodeStored_}async destroy(){this.abortController.abort(),await this.options.deleteDataFromDht(this.options.key,!1)}}const nV=new Bv("StreamPartNetworkSplitAvoidance");class iV{abortController;options;excludedNodes=new Set;running=!1;constructor(e){this.options=e,this.abortController=new AbortController}async avoidNetworkSplit(){this.running=!0,await(async(e,t,r,n=500,i=6)=>{for(let s=1;s<=i;s++){if(r.aborted)return;const i=n*2**s;try{await e()}catch{nV.trace(`${t} failed, retrying in ${i} ms`)}try{await Qv(i,r)}catch(e){nV.trace(`${e}`)}}})((async()=>{const e=(await this.options.discoverEntryPoints()).filter((e=>!this.excludedNodes.has(Mj(e))));if(await this.options.discoveryLayerNode.joinDht(e,!1,!1),this.options.discoveryLayerNode.getNeighborCount()<4){throw e.filter((e=>!this.options.discoveryLayerNode.getNeighbors().some((t=>xj(t,e))))).map((e=>Mj(e))).forEach((e=>this.excludedNodes.add(e))),new Error("Network split is still possible")}}),"avoid network split",this.abortController.signal,this.options.exponentialRunOfBaseDelay),this.running=!1,this.excludedNodes.clear(),nV.trace("Network split avoided")}isRunning(){return this.running}destroy(){this.abortController.abort()}}class sV{abortController;discoveryLayerNode;peerDescriptorStoreManager;constructor(e,t){this.discoveryLayerNode=e,this.peerDescriptorStoreManager=t}async reconnect(e=3e4){this.abortController=new AbortController,await Jv((async()=>{const e=await this.peerDescriptorStoreManager.fetchNodes();await this.discoveryLayerNode.joinDht(e),!this.peerDescriptorStoreManager.isLocalNodeStored()&&e.length<8&&await this.peerDescriptorStoreManager.storeAndKeepLocalNode(),this.discoveryLayerNode.getNeighborCount()>0&&this.abortController.abort()}),e,!0,this.abortController.signal)}isRunning(){return!!this.abortController&&!this.abortController.signal.aborted}destroy(){this.abortController?.abort()}}const oV=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var aV;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(aV||(aV={}));const cV=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>eV},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",aV]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>oV}])}};const uV=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var lV,hV,dV,fV,pV,gV;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(lV||(lV={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(hV||(hV={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}(dV||(dV={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(fV||(fV={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(pV||(pV={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(gV||(gV={}));const mV=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>eV},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>uV},{no:5,name:"ttl",kind:"scalar",T:13}])}};const yV=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const bV=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>eV}])}};const wV=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>NV}])}};const vV=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>EV}])}};const EV=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>eV},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>uV},{no:5,name:"storedAt",kind:"message",T:()=>uV},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const AV=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const SV=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>NV},{no:2,name:"requestId",kind:"scalar",T:9}])}};const kV=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const RV=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>NV},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>NV},{no:3,name:"requestId",kind:"scalar",T:9}])}};const CV=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",lV]}])}};const IV=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>NV},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>EV},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>NV}])}};const PV=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const TV=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const _V=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const NV=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",hV]},{no:3,name:"udp",kind:"message",T:()=>MV},{no:4,name:"tcp",kind:"message",T:()=>MV},{no:5,name:"websocket",kind:"message",T:()=>MV},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const MV=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const xV=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>NV},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>UV},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>NV},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>NV},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const OV=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",fV]}])}};const DV=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const BV=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>MV},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const LV=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>NV},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>NV},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const FV=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>NV},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",pV]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const UV=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>NV},{no:3,name:"targetDescriptor",kind:"message",T:()=>NV},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>cV},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>DV},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>BV},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>LV},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>FV},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>CV}])}};const jV=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const qV=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const zV=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const KV=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const GV=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const VV=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const HV=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const $V=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const WV=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",gV]}])}};const JV=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const QV=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const ZV=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>EV}])}};const YV=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const XV=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>NV}])}};var eH,tH,rH,nH,iH;new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:AV,O:SV},{name:"getClosestRingPeers",options:{},I:kV,O:RV},{name:"ping",options:{},I:PV,O:TV},{name:"leaveNotice",options:{},I:_V,O:oV}]),new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:xV,O:OV},{name:"forwardMessage",options:{},I:xV,O:OV}]),new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:xV,O:OV}]),new vF("dht.StoreRpc",[{name:"storeData",options:{},I:mV,O:yV},{name:"replicateData",options:{},I:vV,O:oV}]),new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:IV,O:oV}]),new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:jV,O:oV}]),new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:qV,O:oV},{name:"rtcOffer",options:{},I:zV,O:oV},{name:"rtcAnswer",options:{},I:KV,O:oV},{name:"iceCandidate",options:{},I:GV,O:oV}]),new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:VV,O:$V},{name:"unlockRequest",options:{},I:HV,O:oV},{name:"gracefulDisconnect",options:{},I:WV,O:oV},{name:"setPrivate",options:{},I:JV,O:oV}]),new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:QV,O:ZV},{name:"externalStoreData",options:{},I:bV,O:wV},{name:"externalFindClosestNodes",options:{},I:YV,O:XV}]),e.ContentType=void 0,(eH=e.ContentType||(e.ContentType={}))[eH.JSON=0]="JSON",eH[eH.BINARY=1]="BINARY",e.EncryptionType=void 0,(tH=e.EncryptionType||(e.EncryptionType={}))[tH.NONE=0]="NONE",tH[tH.AES=1]="AES",function(e){e[e.RSA=0]="RSA",e[e.ML_KEM=1]="ML_KEM"}(rH||(rH={})),e.SignatureType=void 0,(nH=e.SignatureType||(e.SignatureType={}))[nH.ECDSA_SECP256K1_LEGACY=0]="ECDSA_SECP256K1_LEGACY",nH[nH.ECDSA_SECP256K1_EVM=1]="ECDSA_SECP256K1_EVM",nH[nH.ERC_1271=2]="ERC_1271",nH[nH.ML_DSA_87=3]="ML_DSA_87",nH[nH.ECDSA_SECP256R1=4]="ECDSA_SECP256R1",e.ProxyDirection=void 0,(iH=e.ProxyDirection||(e.ProxyDirection={}))[iH.PUBLISH=0]="PUBLISH",iH[iH.SUBSCRIBE=1]="SUBSCRIBE";const sH=new class extends wF{constructor(){super("MessageID",[{no:1,name:"streamId",kind:"scalar",T:9},{no:2,name:"streamPartition",kind:"scalar",T:5},{no:3,name:"timestamp",kind:"scalar",T:3,L:2},{no:4,name:"sequenceNumber",kind:"scalar",T:5},{no:5,name:"publisherId",kind:"scalar",T:12},{no:6,name:"messageChainId",kind:"scalar",T:9}])}};const oH=new class extends wF{constructor(){super("MessageRef",[{no:1,name:"timestamp",kind:"scalar",T:3,L:2},{no:2,name:"sequenceNumber",kind:"scalar",T:5}])}};const aH=new class extends wF{constructor(){super("StreamMessage",[{no:1,name:"messageId",kind:"message",T:()=>sH},{no:2,name:"previousMessageRef",kind:"message",T:()=>oH},{no:3,name:"signature",kind:"scalar",T:12},{no:4,name:"signatureType",kind:"enum",T:()=>["SignatureType",e.SignatureType]},{no:5,name:"contentMessage",kind:"message",oneof:"body",T:()=>cH},{no:6,name:"groupKeyRequest",kind:"message",oneof:"body",T:()=>uH},{no:7,name:"groupKeyResponse",kind:"message",oneof:"body",T:()=>lH}])}};const cH=new class extends wF{constructor(){super("ContentMessage",[{no:1,name:"content",kind:"scalar",T:12},{no:2,name:"contentType",kind:"enum",T:()=>["ContentType",e.ContentType]},{no:3,name:"encryptionType",kind:"enum",T:()=>["EncryptionType",e.EncryptionType]},{no:4,name:"groupKeyId",kind:"scalar",opt:!0,T:9},{no:5,name:"newGroupKey",kind:"message",T:()=>hH}])}};const uH=new class extends wF{constructor(){super("GroupKeyRequest",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"recipientId",kind:"scalar",T:12},{no:3,name:"publicKey",kind:"scalar",T:12},{no:4,name:"groupKeyIds",kind:"scalar",repeat:2,T:9},{no:5,name:"encryptionType",kind:"enum",T:()=>["AsymmetricEncryptionType",rH]}])}};const lH=new class extends wF{constructor(){super("GroupKeyResponse",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"recipientId",kind:"scalar",T:12},{no:3,name:"groupKeys",kind:"message",repeat:2,T:()=>hH},{no:4,name:"encryptionType",kind:"enum",T:()=>["AsymmetricEncryptionType",rH]}])}};const hH=new class extends wF{constructor(){super("EncryptedGroupKey",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:12}])}};const dH=new class extends wF{constructor(){super("StreamPartHandshakeRequest",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"requestId",kind:"scalar",T:9},{no:3,name:"concurrentHandshakeNodeId",kind:"scalar",opt:!0,T:12},{no:4,name:"neighborNodeIds",kind:"scalar",repeat:2,T:12},{no:5,name:"interleaveNodeId",kind:"scalar",opt:!0,T:12}])}};const fH=new class extends wF{constructor(){super("StreamPartHandshakeResponse",[{no:1,name:"accepted",kind:"scalar",T:8},{no:2,name:"requestId",kind:"scalar",T:9},{no:3,name:"interleaveTargetDescriptor",kind:"message",T:()=>NV}])}};const pH=new class extends wF{constructor(){super("InterleaveRequest",[{no:1,name:"interleaveTargetDescriptor",kind:"message",T:()=>NV}])}};const gH=new class extends wF{constructor(){super("InterleaveResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const mH=new class extends wF{constructor(){super("LeaveStreamPartNotice",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"isEntryPoint",kind:"scalar",T:8}])}};const yH=new class extends wF{constructor(){super("NeighborUpdate",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"removeMe",kind:"scalar",T:8},{no:3,name:"neighborDescriptors",kind:"message",repeat:2,T:()=>NV}])}};const bH=new class extends wF{constructor(){super("ProxyConnectionRequest",[{no:1,name:"direction",kind:"enum",opt:!0,T:()=>["ProxyDirection",e.ProxyDirection]},{no:2,name:"userId",kind:"scalar",T:12}])}};const wH=new class extends wF{constructor(){super("ProxyConnectionResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const vH=new class extends wF{constructor(){super("TemporaryConnectionRequest",[])}};const EH=new class extends wF{constructor(){super("TemporaryConnectionResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const AH=new class extends wF{constructor(){super("CloseTemporaryConnection",[])}};const SH=new class extends wF{constructor(){super("StreamPartitionInfo",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"controlLayerNeighbors",kind:"message",repeat:2,T:()=>NV},{no:3,name:"deprecatedContentDeliveryLayerNeighbors",kind:"message",repeat:2,T:()=>NV},{no:4,name:"contentDeliveryLayerNeighbors",kind:"message",repeat:2,T:()=>kH}])}};const kH=new class extends wF{constructor(){super("ContentDeliveryLayerNeighborInfo",[{no:1,name:"peerDescriptor",kind:"message",T:()=>NV},{no:2,name:"rtt",kind:"scalar",opt:!0,T:5}])}};const RH=new class extends wF{constructor(){super("ControlLayerInfo",[{no:1,name:"neighbors",kind:"message",repeat:2,T:()=>NV},{no:2,name:"connections",kind:"message",repeat:2,T:()=>NV}])}};const CH=new class extends wF{constructor(){super("NodeInfoRequest",[])}};const IH=new class extends wF{constructor(){super("NodeInfoResponse",[{no:1,name:"peerDescriptor",kind:"message",T:()=>NV},{no:2,name:"streamPartitions",kind:"message",repeat:2,T:()=>SH},{no:3,name:"controlLayer",kind:"message",T:()=>RH},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const PH=new class extends wF{constructor(){super("PauseNeighborRequest",[{no:1,name:"messageChainId",kind:"scalar",T:9}])}};const TH=new class extends wF{constructor(){super("ResumeNeighborRequest",[{no:1,name:"messageChainId",kind:"scalar",T:9},{no:2,name:"fromTimestamp",kind:"scalar",T:3,L:2}])}},_H=new vF("ContentDeliveryRpc",[{name:"sendStreamMessage",options:{},I:aH,O:oV},{name:"leaveStreamPartNotice",options:{},I:mH,O:oV}]),NH=new vF("ProxyConnectionRpc",[{name:"requestConnection",options:{},I:bH,O:wH}]),MH=new vF("HandshakeRpc",[{name:"handshake",options:{},I:dH,O:fH},{name:"interleaveRequest",options:{},I:pH,O:gH}]),xH=new vF("NeighborUpdateRpc",[{name:"neighborUpdate",options:{},I:yH,O:yH}]),OH=new vF("TemporaryConnectionRpc",[{name:"openConnection",options:{},I:vH,O:EH},{name:"closeConnection",options:{},I:AH,O:oV}]),DH=new vF("NodeInfoRpc",[{name:"getInfo",options:{},I:CH,O:IH}]),BH=new vF("PlumtreeRpc",[{name:"pauseNeighbor",options:{},I:PH,O:oV},{name:"resumeNeighbor",options:{},I:TH,O:oV},{name:"sendMetadata",options:{},I:sH,O:oV}]);class LH{_transport;typeName=_H.typeName;methods=_H.methods;options=_H.options;constructor(e){this._transport=e}sendStreamMessage(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}leaveStreamPartNotice(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class FH{_transport;typeName=NH.typeName;methods=NH.methods;options=NH.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class UH{_transport;typeName=MH.typeName;methods=MH.methods;options=MH.options;constructor(e){this._transport=e}handshake(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}interleaveRequest(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class jH{_transport;typeName=xH.typeName;methods=xH.methods;options=xH.options;constructor(e){this._transport=e}neighborUpdate(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class qH{_transport;typeName=OH.typeName;methods=OH.methods;options=OH.options;constructor(e){this._transport=e}openConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}closeConnection(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class zH{_transport;typeName=DH.typeName;methods=DH.methods;options=DH.options;constructor(e){this._transport=e}getInfo(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class KH{_transport;typeName=BH.typeName;methods=BH.methods;options=BH.options;constructor(e){this._transport=e}pauseNeighbor(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}resumeNeighbor(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}sendMetadata(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}const GH=new Bv("ContentDeliveryRpcRemote");class VH extends wz{rtt;async sendStreamMessage(e,t){const r=this.formDhtRpcOptions({notification:!0,bufferWhileConnecting:t});this.getClient().sendStreamMessage(e,r).catch((()=>{GH.trace("Failed to sendStreamMessage")}))}leaveStreamPartNotice(e,t){const r={streamPartId:e,isEntryPoint:t},n=this.formDhtRpcOptions({notification:!0});this.getClient().leaveStreamPartNotice(r,n).catch((()=>{GH.debug("Failed to send leaveStreamPartNotice")}))}setRtt(e){this.rtt=e}getRtt(){return this.rtt}}const HH=new Bv("HandshakeRpcLocal");class $H{options;constructor(e){this.options=e}async handshake(e,t){return this.handleRequest(e,t)}handleRequest(e,t){const r=t.incomingSourceDescriptor,n=Mj(r);return this.options.ongoingInterleaves.has(n)?this.rejectHandshake(e):this.options.neighbors.has(n)||this.options.ongoingHandshakes.has(n)||this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount?this.acceptHandshake(e,r):this.options.neighbors.size(void 0!==e.interleaveNodeId?[_j(e.interleaveNodeId)]:[])-this.options.ongoingInterleaves.size>=2&&this.options.neighbors.size()<=this.options.maxNeighborCount?this.acceptHandshakeWithInterleaving(e,r):this.rejectHandshake(e)}acceptHandshake(e,t){const r={requestId:e.requestId,accepted:!0};return this.options.neighbors.add(this.options.createContentDeliveryRpcRemote(t)),r}rejectHandshake(e){return{requestId:e.requestId,accepted:!1}}acceptHandshakeWithInterleaving(e,t){const r=[];e.neighborNodeIds.forEach((e=>r.push(_j(e)))),this.options.ongoingInterleaves.forEach((e=>r.push(e))),r.push(Mj(t)),void 0!==e.interleaveNodeId&&r.push(_j(e.interleaveNodeId));const n=this.options.neighbors.getLast(r),i=n?n.getPeerDescriptor():void 0;if(n){const e=Mj(n.getPeerDescriptor()),r=this.options.createRpcRemote(n.getPeerDescriptor());this.options.ongoingInterleaves.add(e),r.interleaveRequest(t).then((e=>{e.accepted&&this.options.neighbors.remove(Mj(i))})).catch((()=>{})).finally((()=>{this.options.ongoingInterleaves.delete(e)}))}return this.options.neighbors.add(this.options.createContentDeliveryRpcRemote(t)),{requestId:e.requestId,accepted:!0,interleaveTargetDescriptor:i}}async interleaveRequest(e,t){const r=t.incomingSourceDescriptor,n=Mj(r);try{return await this.options.handshakeWithInterleaving(e.interleaveTargetDescriptor,n),this.options.neighbors.remove(n),{accepted:!0}}catch(t){return HH.debug(`interleaveRequest to ${Mj(e.interleaveTargetDescriptor)} failed`,{err:t}),{accepted:!1}}}}const WH=new Bv("HandshakeRpcRemote");class JH extends wz{async handshake(e,t,r,n){const i={streamPartId:e,requestId:xF(),neighborNodeIds:t.map((e=>Nj(e))),concurrentHandshakeNodeId:void 0!==r?Nj(r):void 0,interleaveNodeId:void 0!==n?Nj(n):void 0};try{const e=await this.getClient().handshake(i,this.formDhtRpcOptions());return{accepted:e.accepted,interleaveTargetDescriptor:e.interleaveTargetDescriptor}}catch(e){return WH.debug(`handshake to ${Mj(this.getPeerDescriptor())} failed`,{err:e}),{accepted:!1}}}async interleaveRequest(e){const t={interleaveTargetDescriptor:e},r=this.formDhtRpcOptions({connect:!1,timeout:1e4});try{return{accepted:(await this.getClient().interleaveRequest(t,r)).accepted}}catch(e){return WH.debug(`interleaveRequest to ${Mj(this.getPeerDescriptor())} failed`,{err:e}),{accepted:!1}}}}const QH=new Bv("Handshaker");class ZH{options;rpcLocal;constructor(e){this.options=e,this.rpcLocal=new $H({streamPartId:this.options.streamPartId,neighbors:this.options.neighbors,ongoingHandshakes:this.options.ongoingHandshakes,ongoingInterleaves:new Set,maxNeighborCount:this.options.maxNeighborCount,handshakeWithInterleaving:(e,t)=>this.handshakeWithInterleaving(e,t),createRpcRemote:e=>this.createRpcRemote(e),createContentDeliveryRpcRemote:e=>this.createContentDeliveryRpcRemote(e)}),this.options.rpcCommunicator.registerRpcMethod(pH,gH,"interleaveRequest",((e,t)=>this.rpcLocal.interleaveRequest(e,t)),{timeout:1e4}),this.options.rpcCommunicator.registerRpcMethod(dH,fH,"handshake",((e,t)=>this.rpcLocal.handshake(e,t)))}async attemptHandshakesOnContacts(e){return this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount-2?(QH.trace("Attempting parallel handshakes with 2 targets"),this.selectParallelTargetsAndHandshake(e)):this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount?(QH.trace("Attempting handshake with new target"),this.selectNewTargetAndHandshake(e)):e}async selectParallelTargetsAndHandshake(e){const t=e.concat(this.options.neighbors.getIds()),r=this.selectParallelTargets(t);return r.forEach((e=>this.options.ongoingHandshakes.add(Mj(e.getPeerDescriptor())))),this.doParallelHandshakes(r,t)}selectParallelTargets(e){const t=new Map,r=()=>[...e,...Array.from(t.keys())];if(0===this.options.neighbors.size()){const e=this.options.nearbyNodeView.getFirst(r(),!0);if(e){const r=Mj(e.getPeerDescriptor());t.set(r,e)}}const n=this.options.leftNodeView.getFirst(r()),i=this.options.rightNodeView.getFirst(r());if(n&&t.set(Mj(n.getPeerDescriptor()),n),i&&t.set(Mj(i.getPeerDescriptor()),i),t.size<2){const e=this.options.nearbyNodeView.getFirst(r());e&&t.set(Mj(e.getPeerDescriptor()),e)}for(;t.size<2;){const e=this.options.randomNodeView.getRandom(r());if(!e)break;t.set(Mj(e.getPeerDescriptor()),e)}return Array.from(t.values()).map((e=>this.createRpcRemote(e.getPeerDescriptor())))}async doParallelHandshakes(e,t){return(await Promise.allSettled(Array.from(e.values()).map((async(t,r)=>{const n=0===r?e[1]:e[0],i=n?Mj(n.getPeerDescriptor()):void 0;return this.handshakeWithTarget(t,i)})))).forEach(((r,n)=>{"fulfilled"===r.status&&r.value||t.push(Mj(e[n].getPeerDescriptor()))})),t}async selectNewTargetAndHandshake(e){const t=e.concat(this.options.neighbors.getIds()),r=this.options.leftNodeView.getFirst(t)??this.options.rightNodeView.getFirst(t)??this.options.nearbyNodeView.getFirst(t)??this.options.randomNodeView.getRandom(t);if(r){await this.handshakeWithTarget(this.createRpcRemote(r.getPeerDescriptor()))||e.push(Mj(r.getPeerDescriptor()))}return e}async handshakeWithTarget(e,t){const r=Mj(e.getPeerDescriptor());this.options.ongoingHandshakes.add(r);const n=await e.handshake(this.options.streamPartId,this.options.neighbors.getIds(),t);return n.accepted&&this.options.neighbors.add(this.createContentDeliveryRpcRemote(e.getPeerDescriptor())),n.interleaveTargetDescriptor&&await this.handshakeWithInterleaving(n.interleaveTargetDescriptor,r),this.options.ongoingHandshakes.delete(r),n.accepted}async handshakeWithInterleaving(e,t){const r=this.createRpcRemote(e),n=Mj(r.getPeerDescriptor());this.options.ongoingHandshakes.add(n);const i=await r.handshake(this.options.streamPartId,this.options.neighbors.getIds(),void 0,t);return i.accepted&&this.options.neighbors.add(this.createContentDeliveryRpcRemote(r.getPeerDescriptor())),this.options.ongoingHandshakes.delete(n),i.accepted}createRpcRemote(e){return new JH(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,UH,this.options.rpcRequestTimeout)}createContentDeliveryRpcRemote(e){return new VH(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,LH,this.options.rpcRequestTimeout)}getOngoingHandshakes(){return this.options.ongoingHandshakes}}const YH=new Bv("NeighborFinder");class XH{abortController;options;running=!1;constructor(e){this.options=e,this.abortController=new AbortController}async findNeighbors(e){if(!this.running)return;const t=await this.options.doFindNeighbors(e),r=new Set([...this.options.nearbyNodeView.getIds(),...this.options.leftNodeView.getIds(),...this.options.rightNodeView.getIds(),...this.options.randomNodeView.getIds()]).size;this.options.neighbors.size()<this.options.minCount&&t.length<r?Yy((()=>this.findNeighbors(t)),250,this.abortController.signal):0===this.options.neighbors.size()&&r>0?(YH.debug("No neighbors found yet contacts are available, restarting handshaking process"),Yy((()=>this.findNeighbors([])),250,this.abortController.signal)):this.running=!1}isRunning(){return this.running}start(e=[]){this.running||(this.running=!0,Yy((async()=>{await Promise.all([this.findNeighbors(e),this.findNeighbors(e)])}),100,this.abortController.signal))}stop(){this.running&&(this.running=!1,this.abortController.abort())}}class e${options;constructor(e){this.options=e}updateContacts(e){const t=Mj(this.options.localPeerDescriptor);e.filter((e=>{const r=Mj(e);return r!==t&&!this.options.neighbors.getIds().includes(r)})).forEach((e=>this.options.nearbyNodeView.add(new VH(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,LH))))}createResponse(e){return{streamPartId:this.options.streamPartId,neighborDescriptors:this.options.neighbors.getAll().map((e=>e.getPeerDescriptor())),removeMe:e}}async neighborUpdate(e,t){const r=t.incomingSourceDescriptor,n=Mj(r);if(this.updateContacts(e.neighborDescriptors),this.options.neighbors.has(n)||this.options.ongoingHandshakes.has(n)){const t=this.options.neighbors.size()>this.options.neighborTargetCount&&e.neighborDescriptors.length>this.options.neighborTargetCount;return t?this.options.neighbors.remove(n):this.options.neighborFinder.start(),this.createResponse(t)}return this.createResponse(!0)}}const t$=new Bv("NeighborUpdateRpcRemote");class r$ extends wz{async updateNeighbors(e,t){const r={streamPartId:e,neighborDescriptors:t,removeMe:!1};try{const e=await this.getClient().neighborUpdate(r,this.formDhtRpcOptions());return{peerDescriptors:e.neighborDescriptors,removeMe:e.removeMe}}catch(e){return t$.debug(`updateNeighbors to ${Mj(this.getPeerDescriptor())} failed`,{err:e}),{peerDescriptors:[],removeMe:!0}}}}const n$=new Bv("NeighborUpdateManager");class i${abortController;options;rpcLocal;constructor(e){this.abortController=new AbortController,this.rpcLocal=new e$(e),this.options=e,this.options.rpcCommunicator.registerRpcMethod(yH,yH,"neighborUpdate",((e,t)=>this.rpcLocal.neighborUpdate(e,t)))}async start(){await Jv((()=>this.updateNeighborInfo()),this.options.neighborUpdateInterval,!1,this.abortController.signal)}stop(){this.abortController.abort()}async updateNeighborInfo(){n$.trace("Updating neighbor info to nodes");const e=this.options.neighbors.getAll().map((e=>e.getPeerDescriptor())),t=Date.now();await Promise.allSettled(this.options.neighbors.getAll().map((async r=>{const n=await this.createRemote(r.getPeerDescriptor()).updateNeighbors(this.options.streamPartId,e),i=Mj(r.getPeerDescriptor());this.options.neighbors.get(i).setRtt(Date.now()-t),n.removeMe&&(this.options.neighbors.remove(i),this.options.neighborFinder.start([i]))})))}createRemote(e){return new r$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,jH)}}class s${options;constructor(e){this.options=e}async sendStreamMessage(e,t){const r=t.incomingSourceDescriptor,n=Mj(r);return this.options.markForInspection(n,e.messageId),void 0===this.options.plumtreeManager?this.options.markAndCheckDuplicate(e.messageId,e.previousMessageRef)&&this.options.broadcast(e,n):this.options.markAndCheckDuplicate(e.messageId,e.previousMessageRef)?this.options.plumtreeManager.broadcast(e,n):await this.options.plumtreeManager.pauseNeighbor(r,e.messageId.messageChainId),oV}async leaveStreamPartNotice(e,t){if(e.streamPartId===this.options.streamPartId){const r=t.incomingSourceDescriptor,n=Mj(r);this.options.onLeaveNotice(n,e.isEntryPoint)}return oV}}class o${a;b;constructor(e,t){this.a=e,this.b=t}greaterThanOrEqual(e){return this.greaterThan(e)||this.equalTo(e)}greaterThan(e){return 1===this.compareTo(e)}equalTo(e){return 0===this.compareTo(e)}compareTo(e){return this.a>e.a?1:this.a<e.a?-1:this.b>e.b?1:this.b<e.b?-1:0}toString(){return`${this.a}|${this.b}`}}class a$ extends Error{constructor(){super("pre-condition: previousNumber < number")}}class c$ extends Error{constructor(e,t,r){super(`pre-condition: gap overlap in given numbers: previousNumber=${t.toString()}, number=${r.toString()}, state=${e}`)}}class u${maxGapCount;gaps;constructor(e=1e4){this.maxGapCount=e,this.gaps=[]}markAndCheck(e,t){if(e?.greaterThanOrEqual(t))throw new a$;if(0===this.gaps.length)return this.gaps.push([t,new o$(1/0,1/0)]),!0;if(null===e)return!!t.greaterThan(this.gaps[this.gaps.length-1][0])&&(this.gaps[this.gaps.length-1][0]=t,!0);for(let r=this.gaps.length-1;r>=0;--r){const[n,i]=this.gaps[r];if(e.greaterThanOrEqual(i))return!1;if(e.greaterThanOrEqual(n)){if(t.greaterThan(i))throw new c$(this.toString(),e,t);return e.equalTo(n)?t.equalTo(i)?this.gaps.splice(r,1):this.gaps[r]=[t,i]:t.equalTo(i)?this.gaps[r]=[n,e]:this.gaps.splice(r,1,[n,e],[t,i]),this.dropLowestGapIfOverMaxGapCount(),!0}if(t.greaterThan(n))throw new c$(this.toString(),e,t)}return!1}dropLowestGapIfOverMaxGapCount(){this.gaps.length>this.maxGapCount&&this.gaps.shift()}toString(){return this.gaps.map((([e,t])=>`(${e.toString()}, ${t.toString()}]`)).join(", ")}}const l$=(e,t,r)=>{const n=`${kE(t.publisherId)}-${t.messageChainId}`,i=r?new o$(Number(r.timestamp),r.sequenceNumber):null,s=new o$(Number(t.timestamp),t.sequenceNumber);return e.has(n)||e.set(n,new u$),e.get(n).markAndCheck(i,s)},h$=new Bv("ContentDeliveryLayerNode");class d$ extends Sl{started=!1;duplicateDetectors;options;contentDeliveryRpcLocal;abortController=new AbortController;messagesPropagated=0;constructor(e){super(),this.options=e,this.duplicateDetectors=new Map,this.contentDeliveryRpcLocal=new s$({localPeerDescriptor:this.options.localPeerDescriptor,streamPartId:this.options.streamPartId,rpcCommunicator:this.options.rpcCommunicator,markAndCheckDuplicate:(e,t)=>l$(this.duplicateDetectors,e,t),broadcast:(e,t)=>this.broadcast(e,t),onLeaveNotice:(e,t)=>{if(this.abortController.signal.aborted)return;(this.options.nearbyNodeView.get(e)??this.options.randomNodeView.get(e)??this.options.neighbors.get(e)??this.options.proxyConnectionRpcLocal?.getConnection(e)?.remote)&&(this.options.discoveryLayerNode.removeContact(e),this.options.neighbors.remove(e),this.options.nearbyNodeView.remove(e),this.options.randomNodeView.remove(e),this.options.leftNodeView.remove(e),this.options.rightNodeView.remove(e),this.options.neighborFinder.start([e]),this.options.proxyConnectionRpcLocal?.removeConnection(e)),t&&this.emit("entryPointLeaveDetected")},markForInspection:(e,t)=>this.options.inspector.markMessage(e,t),plumtreeManager:this.options.plumtreeManager})}async start(){this.started=!0,this.registerDefaultServerMethods(),oE(this.options.discoveryLayerNode,"nearbyContactAdded",(()=>this.onNearbyContactAdded()),this.abortController.signal),oE(this.options.discoveryLayerNode,"nearbyContactRemoved",(()=>this.onNearbyContactRemoved()),this.abortController.signal),oE(this.options.discoveryLayerNode,"randomContactAdded",(()=>this.onRandomContactAdded()),this.abortController.signal),oE(this.options.discoveryLayerNode,"randomContactRemoved",(()=>this.onRandomContactRemoved()),this.abortController.signal),oE(this.options.discoveryLayerNode,"ringContactAdded",(()=>this.onRingContactsUpdated()),this.abortController.signal),oE(this.options.discoveryLayerNode,"ringContactRemoved",(()=>this.onRingContactsUpdated()),this.abortController.signal),oE(this.options.transport,"disconnected",(e=>this.onNodeDisconnected(e)),this.abortController.signal),oE(this.options.neighbors,"nodeAdded",((e,t)=>{this.options.propagation.onNeighborJoined(e),this.options.connectionLocker.weakLockConnection(Mj(t.getPeerDescriptor()),this.options.streamPartId),this.emit("neighborConnected",e)}),this.abortController.signal),oE(this.options.neighbors,"nodeRemoved",((e,t)=>{this.options.connectionLocker.weakUnlockConnection(Mj(t.getPeerDescriptor()),this.options.streamPartId)}),this.abortController.signal),void 0!==this.options.proxyConnectionRpcLocal&&oE(this.options.proxyConnectionRpcLocal,"newConnection",(e=>this.options.propagation.onNeighborJoined(e)),this.abortController.signal),this.options.plumtreeManager&&oE(this.options.plumtreeManager,"message",(e=>this.emit("message",e)),this.abortController.signal),this.options.neighborFinder.start(),await this.options.neighborUpdateManager.start()}registerDefaultServerMethods(){this.options.rpcCommunicator.registerRpcNotification(aH,"sendStreamMessage",((e,t)=>this.contentDeliveryRpcLocal.sendStreamMessage(e,t))),this.options.rpcCommunicator.registerRpcNotification(mH,"leaveStreamPartNotice",((e,t)=>this.contentDeliveryRpcLocal.leaveStreamPartNotice(e,t))),this.options.rpcCommunicator.registerRpcMethod(vH,EH,"openConnection",((e,t)=>this.options.temporaryConnectionRpcLocal.openConnection(e,t))),this.options.rpcCommunicator.registerRpcNotification(AH,"closeConnection",((e,t)=>this.options.temporaryConnectionRpcLocal.closeConnection(e,t)))}onRingContactsUpdated(){if(h$.trace("onRingContactsUpdated"),this.isStopped())return;const e=this.options.discoveryLayerNode.getRingContacts();this.options.leftNodeView.replaceAll(e.left.map((e=>new VH(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,LH,this.options.rpcRequestTimeout)))),this.options.rightNodeView.replaceAll(e.right.map((e=>new VH(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,LH,this.options.rpcRequestTimeout))))}onNearbyContactAdded(){if(h$.trace("New nearby contact found"),this.isStopped())return;const e=this.options.discoveryLayerNode.getClosestContacts();this.updateNearbyNodeView(e),this.options.neighbors.size()<this.options.neighborTargetCount&&this.options.neighborFinder.start()}onNearbyContactRemoved(){if(h$.trace("Nearby contact removed"),this.isStopped())return;const e=this.options.discoveryLayerNode.getClosestContacts();this.updateNearbyNodeView(e)}updateNearbyNodeView(e){this.options.nearbyNodeView.replaceAll(Array.from(e).map((e=>new VH(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,LH,this.options.rpcRequestTimeout))));for(const e of this.options.discoveryLayerNode.getNeighbors()){if(this.options.nearbyNodeView.size()>=this.options.nodeViewSize)break;this.options.nearbyNodeView.add(new VH(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,LH,this.options.rpcRequestTimeout))}}onRandomContactAdded(){if(this.isStopped())return;const e=this.options.discoveryLayerNode.getRandomContacts(this.options.nodeViewSize);this.options.randomNodeView.replaceAll(e.map((e=>new VH(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,LH,this.options.rpcRequestTimeout)))),this.options.neighbors.size()<this.options.neighborTargetCount&&this.options.neighborFinder.start()}onRandomContactRemoved(){if(h$.trace("New random contact removed"),this.isStopped())return;const e=this.options.discoveryLayerNode.getRandomContacts(this.options.nodeViewSize);this.options.randomNodeView.replaceAll(e.map((e=>new VH(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,LH,this.options.rpcRequestTimeout))))}onNodeDisconnected(e){const t=Mj(e);this.options.neighbors.has(t)&&(this.options.neighbors.remove(t),this.options.neighborFinder.start([t]),this.options.temporaryConnectionRpcLocal.removeNode(t))}hasProxyConnection(e){return!!this.options.proxyConnectionRpcLocal&&this.options.proxyConnectionRpcLocal.hasConnection(e)}stop(){this.started&&(this.abortController.abort(),this.options.proxyConnectionRpcLocal?.stop(),this.options.neighbors.getAll().map((e=>{e.leaveStreamPartNotice(this.options.streamPartId,this.options.isLocalNodeEntryPoint()),this.options.connectionLocker.weakUnlockConnection(Mj(e.getPeerDescriptor()),this.options.streamPartId)})),this.options.rpcCommunicator.destroy(),this.removeAllListeners(),this.options.plumtreeManager?.stop(),this.options.nearbyNodeView.stop(),this.options.neighbors.stop(),this.options.randomNodeView.stop(),this.options.neighborFinder.stop(),this.options.neighborUpdateManager.stop(),this.options.inspector.stop())}broadcast(e,t){t||l$(this.duplicateDetectors,e.messageId,e.previousMessageRef),this.emit("message",e);const r=void 0!==t&&!this.options.temporaryConnectionRpcLocal.hasNode(t);this.options.propagation.feedUnseenMessage(e,this.getPropagationTargets(e),r?t:null),this.messagesPropagated+=1}inspect(e){return this.options.inspector.inspect(e)}getPropagationTargets(e){let t=this.options.neighbors.getIds();return this.options.proxyConnectionRpcLocal&&(t=t.concat(this.options.proxyConnectionRpcLocal.getPropagationTargets(e))),t=t.concat(this.options.temporaryConnectionRpcLocal.getNodes().getIds()),t}getOwnNodeId(){return Mj(this.options.localPeerDescriptor)}getOutgoingHandshakeCount(){return this.options.handshaker.getOngoingHandshakes().size}getNeighbors(){return!this.started&&this.isStopped()?[]:this.options.neighbors.getAll().map((e=>e.getPeerDescriptor()))}getInfos(){return this.options.neighbors.getAll().map((e=>({peerDescriptor:e.getPeerDescriptor(),rtt:e.getRtt()})))}getNearbyNodeView(){return this.options.nearbyNodeView}getDiagnosticInfo(){return{neighborCount:this.options.neighbors.size(),nearbyNodeViewCount:this.options.nearbyNodeView.size(),randomNodeViewCount:this.options.randomNodeView.size(),leftNodeViewCount:this.options.leftNodeView.size(),rightNodeViewCount:this.options.rightNodeView.size(),messagesPropagated:this.messagesPropagated}}isStopped(){return this.abortController.signal.aborted}}const f$=(e,t,r=!1)=>{const n=r?Array.from(e.entries()).filter((([e,t])=>void 0!==t.getPeerDescriptor().websocket)):Array.from(e.entries());return n.filter((([e])=>!t.includes(e))).map((([e,t])=>t))};class p$ extends Sl{nodes;limit;ownId;constructor(e,t){super(),this.nodes=new Map,this.limit=t,this.ownId=e}add(e){const t=Mj(e.getPeerDescriptor());if(this.ownId!==t&&this.nodes.size<this.limit){const r=this.nodes.has(t);this.nodes.set(t,e),r||this.emit("nodeAdded",t,e)}}remove(e){if(this.nodes.has(e)){const t=this.nodes.get(e);this.nodes.delete(e),this.emit("nodeRemoved",e,t)}}has(e){return this.nodes.has(e)}replaceAll(e){this.nodes.clear();e.splice(0,this.limit).forEach((e=>{this.add(e)}))}getIds(){return Array.from(this.nodes.keys())}get(e){return this.nodes.get(e)}size(e=[]){return Array.from(this.nodes.keys()).filter((t=>!e.includes(t))).length}getRandom(e){return oA(f$(this.nodes,e))}getFirst(e,t=!1){return f$(this.nodes,e,t)[0]}getFirstAndLast(e){const t=f$(this.nodes,e);return 0===t.length?[]:t.length>1?[this.getFirst(e),this.getLast(e)]:[this.getFirst(e)]}getLast(e){const t=f$(this.nodes,e);return t[t.length-1]}getAll(){return Array.from(this.nodes.values())}stop(){this.nodes.forEach((e=>this.remove(Mj(e.getPeerDescriptor())))),this.removeAllListeners()}}class g${items=new Map;dropQueue=WG.create();ttlInMs;maxSize;onItemDropped;timeProvider;constructor({ttlInMs:e,maxSize:t,onItemDropped:r=()=>{},timeProvider:n=Date.now}){if(e<0)throw new Error(`ttlInMs (${e}) cannot be < 0`);if(t<0)throw new Error(`maxSize (${t}) cannot be < 0`);this.ttlInMs=e,this.maxSize=t,this.onItemDropped=r,this.timeProvider=n}set(e,t){if(0===this.maxSize)return;if(this.items.size>this.maxSize)throw new Error("assertion error: maximum size exceeded");if(this.delete(e),this.items.size===this.maxSize){const e=this.dropQueue.shift();if(void 0===e)throw new Error("assertion error: queue empty but still have items");this.items.delete(e),this.onItemDropped(e)}const r=new YG(e);this.dropQueue.pushNode(r),this.items.set(e,{value:t,dropQueueNode:r,expiresAt:this.timeProvider()+this.ttlInMs})}delete(e){const t=this.items.get(e);void 0!==t&&(this.items.delete(e),this.dropQueue.removeNode(t.dropQueueNode),this.onItemDropped(e))}get(e){const t=this.items.get(e);if(void 0!==t){if(!(t.expiresAt<=this.timeProvider()))return t.value;this.delete(e)}}values(){const e=[...this.items.keys()],t=[];for(const r of e){const e=this.get(r);void 0!==e&&t.push(e)}return t}}class m${tasks;constructor(e,t){this.tasks=new g$({ttlInMs:e,maxSize:t})}get(){return this.tasks.values()}add(e){const t=e.message.messageId;this.tasks.set(t,e)}delete(e){this.tasks.delete(e)}}class y${sendToNeighbor;minPropagationTargets;activeTaskStore;constructor({sendToNeighbor:e,minPropagationTargets:t,maxMessages:r,ttl:n}){this.sendToNeighbor=e,this.minPropagationTargets=t,this.activeTaskStore=new m$(n,r)}feedUnseenMessage(e,t,r){const n={message:e,source:r,handledNeighbors:new Set};this.activeTaskStore.add(n);for(const e of t)this.sendAndAwaitThenMark(n,e)}onNeighborJoined(e){const t=this.activeTaskStore.get();for(const r of t)this.sendAndAwaitThenMark(r,e)}sendAndAwaitThenMark({message:e,source:t,handledNeighbors:r},n){r.has(n)||n===t||(async()=>{try{await this.sendToNeighbor(n,e)}catch{return}r.add(n),r.size>=this.minPropagationTargets&&this.activeTaskStore.delete(e.messageId)})()}}const b$=new Bv("ProxyConnectionRpcLocal");class w$ extends Sl{options;connections=new Map;constructor(e){super(),this.options=e,this.options.rpcCommunicator.registerRpcMethod(bH,wH,"requestConnection",((e,t)=>this.requestConnection(e,t)))}getConnection(e){return this.connections.get(e)}hasConnection(e){return this.connections.has(e)}removeConnection(e){this.connections.delete(e)}stop(){this.connections.forEach((e=>e.remote.leaveStreamPartNotice(this.options.streamPartId,!1))),this.connections.clear(),this.removeAllListeners()}getPropagationTargets(e){if("groupKeyRequest"!==e.body.oneofKind)return this.getSubscribers();try{const t=e.body.groupKeyRequest.recipientId;return this.getNodeIdsForUserId(kE(t))}catch(e){return b$.trace("Could not parse GroupKeyRequest",{err:e}),[]}}getNodeIdsForUserId(e){return Array.from(this.connections.keys()).filter((t=>this.connections.get(t).userId===e))}getSubscribers(){return Array.from(this.connections.keys()).filter((t=>{const r=this.connections.get(t).direction;return void 0===r||r===e.ProxyDirection.SUBSCRIBE}))}async requestConnection(e,t){const r=t.incomingSourceDescriptor,n=Mj(r);this.connections.set(n,{direction:e.direction,userId:kE(e.userId),remote:new VH(this.options.localPeerDescriptor,r,this.options.rpcCommunicator,LH)});return b$.trace(`Accepted connection request from ${n} to ${this.options.streamPartId}`),this.emit("newConnection",n),{accepted:!0}}}const v$=new Bv("TemporaryConnectionRpcRemote");class E$ extends wz{async openConnection(){try{return(await this.getClient().openConnection({},this.formDhtRpcOptions())).accepted}catch(e){return v$.debug(`temporaryConnection to ${Mj(this.getPeerDescriptor())} failed`,{err:e}),!1}}async closeConnection(){try{await this.getClient().closeConnection({},this.formDhtRpcOptions({connect:!1,notification:!0}))}catch(e){v$.trace(`closeConnection to ${Mj(this.getPeerDescriptor())} failed`,{err:e})}}}class A$ extends Sl{inspectionMessages=new Map;inspectedNode;constructor(e){super(),this.inspectedNode=e.inspectedNode}markMessage(e,t){const r=(e=>`${kE(e.publisherId)}:${e.messageChainId}:${e.timestamp}:${e.sequenceNumber}`)(t);this.inspectionMessages.has(r)?(this.inspectionMessages.has(r)&&!1===this.inspectionMessages.get(r)&&e===this.inspectedNode||this.inspectionMessages.has(r)&&!0===this.inspectionMessages.get(r))&&this.emit("done"):this.inspectionMessages.set(r,e===this.inspectedNode)}getInspectedMessageCount(){return this.inspectionMessages.size}onlyMarkedByInspectedNode(){return Array.from(this.inspectionMessages.values()).every((e=>!0===e))}stop(){this.emit("done")}}const S$=new Bv("Inspector");class k${sessions=new Map;streamPartId;localPeerDescriptor;rpcCommunicator;connectionLocker;inspectionTimeout;openInspectConnection;closeInspectConnection;constructor(e){this.streamPartId=e.streamPartId,this.localPeerDescriptor=e.localPeerDescriptor,this.rpcCommunicator=e.rpcCommunicator,this.connectionLocker=e.connectionLocker,this.inspectionTimeout=e.inspectionTimeout??6e4,this.openInspectConnection=e.openInspectConnection??this.defaultOpenInspectConnection,this.closeInspectConnection=e.closeInspectConnection??this.defaultCloseInspectConnection}async defaultOpenInspectConnection(e,t){const r=new E$(this.localPeerDescriptor,e,this.rpcCommunicator,qH);await r.openConnection(),this.connectionLocker.weakLockConnection(Mj(e),t)}async defaultCloseInspectConnection(e,t){const r=new E$(this.localPeerDescriptor,e,this.rpcCommunicator,qH);await r.closeConnection(),this.connectionLocker.weakUnlockConnection(Mj(e),t)}async inspect(e){const t=Mj(e),r=new A$({inspectedNode:t}),n=`inspector-${this.streamPartId}`;this.sessions.set(t,r),await this.openInspectConnection(e,n);let i=!1;try{await eE(r,"done",this.inspectionTimeout),i=!0}catch{S$.trace("Inspect session timed out, removing")}finally{await this.closeInspectConnection(e,n),this.sessions.delete(t)}return i||r.getInspectedMessageCount()<1||r.onlyMarkedByInspectedNode()}markMessage(e,t){this.sessions.forEach((r=>r.markMessage(e,t)))}isInspected(e){return this.sessions.has(e)}stop(){this.sessions.forEach((e=>{e.stop()})),this.sessions.clear()}}class R${options;temporaryNodes;lockId;constructor(e){this.options=e,this.temporaryNodes=new p$(Mj(e.localPeerDescriptor),10),this.lockId="system/content-delivery/temporary-connection/"+e.streamPartId}getNodes(){return this.temporaryNodes}hasNode(e){return this.temporaryNodes.has(e)}removeNode(e){this.temporaryNodes.remove(e),this.options.connectionLocker.weakUnlockConnection(e,this.lockId)}async openConnection(e,t){const r=t.incomingSourceDescriptor,n=new VH(this.options.localPeerDescriptor,r,this.options.rpcCommunicator,LH);return this.temporaryNodes.add(n),this.options.connectionLocker.weakLockConnection(Mj(r),this.lockId),{accepted:!0}}async closeConnection(e,t){const r=Mj(t.incomingSourceDescriptor);return this.removeNode(r),{}}}const C$=e=>`stream-part-delivery-${e}`;class I${neighbors;pausedNodes;onMetadataCb;sendBuffer;constructor(e,t,r,n){this.neighbors=e,this.pausedNodes=t,this.onMetadataCb=r,this.sendBuffer=n}async sendMetadata(e,t){const r=t.incomingSourceDescriptor;return await this.onMetadataCb(e,r),oV}async pauseNeighbor(e,t){const r=Mj(t.incomingSourceDescriptor);return this.neighbors.has(r)&&this.pausedNodes.add(r,e.messageChainId),oV}async resumeNeighbor(e,t){const r=t.incomingSourceDescriptor;return this.pausedNodes.delete(Mj(r),e.messageChainId),await this.sendBuffer(e.fromTimestamp,e.messageChainId,r),oV}}class P$ extends wz{async sendMetadata(e){const t=this.formDhtRpcOptions({notification:!0});await this.getClient().sendMetadata(e,t)}async pauseNeighbor(e){const t=this.formDhtRpcOptions({notification:!0});await this.getClient().pauseNeighbor({messageChainId:e},t)}async resumeNeighbor(e,t){const r=this.formDhtRpcOptions({notification:!0});await this.getClient().resumeNeighbor({fromTimestamp:e,messageChainId:t},r)}}class T${pausedNeighbors;limit;constructor(e){this.pausedNeighbors=new Map,this.limit=e}add(e,t){this.pausedNeighbors.has(t)||this.pausedNeighbors.set(t,new Set),this.pausedNeighbors.get(t).size>=this.limit||this.pausedNeighbors.get(t).add(e)}delete(e,t){this.pausedNeighbors.get(t)?.delete(e),0===this.pausedNeighbors.get(t)?.size&&this.pausedNeighbors.delete(t)}deleteAll(e){this.pausedNeighbors.forEach(((t,r)=>{t.delete(e),0===t.size&&this.pausedNeighbors.delete(r)}))}isPaused(e,t){return!!this.pausedNeighbors.has(t)&&this.pausedNeighbors.get(t).has(e)}forEach(e){this.pausedNeighbors.forEach(((t,r)=>{e(t,r)}))}size(e){return this.pausedNeighbors.get(e)?.size??0}}const _$=new Bv("PlumtreeManager");class N$ extends Sl{neighbors;localPeerDescriptor;localPausedNeighbors;remotePausedNeighbors;rpcLocal;latestMessages=new Map;rpcCommunicator;metadataTimestampsAheadOfRealData=new Map;maxPausedNeighbors;constructor(e){super(),this.neighbors=e.neighbors,this.maxPausedNeighbors=e.maxPausedNeighbors??3,this.localPeerDescriptor=e.localPeerDescriptor,this.localPausedNeighbors=new T$(e.maxPausedNeighbors??3),this.remotePausedNeighbors=new T$(e.maxPausedNeighbors??3),this.rpcLocal=new I$(this.neighbors,this.localPausedNeighbors,((e,t)=>this.onMetadata(e,t)),((e,t,r)=>this.sendBuffer(e,t,r))),this.neighbors.on("nodeRemoved",(e=>this.onNeighborRemoved(e))),this.rpcCommunicator=e.rpcCommunicator,this.rpcCommunicator.registerRpcNotification(sH,"sendMetadata",((e,t)=>this.rpcLocal.sendMetadata(e,t))),this.rpcCommunicator.registerRpcNotification(PH,"pauseNeighbor",((e,t)=>this.rpcLocal.pauseNeighbor(e,t))),this.rpcCommunicator.registerRpcNotification(TH,"resumeNeighbor",((e,t)=>this.rpcLocal.resumeNeighbor(e,t)))}async pauseNeighbor(e,t){if(this.neighbors.has(Mj(e))&&!this.remotePausedNeighbors.isPaused(Mj(e),t)&&this.remotePausedNeighbors.size(t)<this.maxPausedNeighbors){_$.debug(`Pausing neighbor ${Mj(e)}`),this.remotePausedNeighbors.add(Mj(e),t);const r=this.createRemote(e);await r.pauseNeighbor(t)}}async resumeNeighbor(e,t,r){if(this.remotePausedNeighbors.isPaused(Mj(e),t)){_$.debug(`Resuming neighbor ${Mj(e)}`),this.remotePausedNeighbors.delete(Mj(e),t);const n=this.createRemote(e);await n.resumeNeighbor(r,t)}}onNeighborRemoved(e){this.localPausedNeighbors.deleteAll(e),this.remotePausedNeighbors.deleteAll(e),this.neighbors.size()>0&&this.remotePausedNeighbors.forEach(((e,t)=>{if(e.size>=this.neighbors.size()){_$.debug("All neighbors are paused, resuming first neighbor");const e=this.neighbors.getFirst([]).getPeerDescriptor();setImmediate((()=>this.resumeNeighbor(e,t,this.getLatestMessageTimestamp(t))))}}))}getLatestMessageTimestamp(e){return this.latestMessages.has(e)&&0!==this.latestMessages.get(e).length?this.latestMessages.get(e)[this.latestMessages.get(e).length-1].messageId.timestamp:0}async sendBuffer(e,t,r){const n=new VH(this.localPeerDescriptor,r,this.rpcCommunicator,LH),i=this.latestMessages.get(t)?.filter((t=>t.messageId.timestamp>e))??[];await Promise.all(i.map((e=>n.sendStreamMessage(e))))}async onMetadata(e,t){this.getLatestMessageTimestamp(e.messageChainId)<e.timestamp&&(this.metadataTimestampsAheadOfRealData.has(e.messageChainId)||this.metadataTimestampsAheadOfRealData.set(e.messageChainId,new Set),this.metadataTimestampsAheadOfRealData.get(e.messageChainId).add(e.timestamp),this.metadataTimestampsAheadOfRealData.get(e.messageChainId).size>1&&(await this.resumeNeighbor(t,e.messageChainId,this.getLatestMessageTimestamp(e.messageChainId)),this.metadataTimestampsAheadOfRealData.get(e.messageChainId).forEach((t=>{this.metadataTimestampsAheadOfRealData.get(e.messageChainId).delete(t)}))))}createRemote(e){return new P$(this.localPeerDescriptor,e,this.rpcCommunicator,KH)}broadcast(e,t){const r=e.messageId.messageChainId;this.latestMessages.has(r)||this.latestMessages.set(r,[]),this.latestMessages.get(r).length<20||this.latestMessages.get(r).shift(),this.latestMessages.get(r).push(e),this.metadataTimestampsAheadOfRealData.has(e.messageId.messageChainId)&&this.metadataTimestampsAheadOfRealData.get(e.messageId.messageChainId).delete(e.messageId.timestamp),this.emit("message",e);const n=this.neighbors.getAll().filter((e=>Mj(e.getPeerDescriptor())!==t));for(const t of n)if(this.localPausedNeighbors.isPaused(Mj(t.getPeerDescriptor()),e.messageId.messageChainId)){const r=this.createRemote(t.getPeerDescriptor());setImmediate((()=>r.sendMetadata(e.messageId)))}else setImmediate((()=>t.sendStreamMessage(e)))}isNeighborPaused(e,t){return this.localPausedNeighbors.isPaused(Mj(e),t)||this.remotePausedNeighbors.isPaused(Mj(e),t)}stop(){this.neighbors.off("nodeRemoved",this.onNeighborRemoved)}}const M$=e=>new d$((e=>{const t=Mj(e.localPeerDescriptor),r=e.rpcCommunicator??new Kz(C$(e.streamPartId),e.transport),n=e.neighborTargetCount??4,i=e.maxContactCount??20,s=e.acceptProxyConnections??!1,o=e.neighborUpdateInterval??1e4,a=e.minPropagationTargets??2,c=e.maxPropagationBufferSize??150,u=e.neighbors??new p$(t,i),l=e.leftNodeView??new p$(t,i),h=e.rightNodeView??new p$(t,i),d=e.nearbyNodeView??new p$(t,i),f=e.randomNodeView??new p$(t,i),p=new Set,g=new R$({rpcCommunicator:r,localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,connectionLocker:e.connectionLocker}),m=s?new w$({localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,rpcCommunicator:r}):void 0,y=e.plumtreeOptimization?new N$({neighbors:u,localPeerDescriptor:e.localPeerDescriptor,rpcCommunicator:r,maxPausedNeighbors:e.plumtreeMaxPausedNeighbors}):void 0,b=e.propagation??new y$({minPropagationTargets:a,maxMessages:c,ttl:1e4,sendToNeighbor:async(t,r)=>{const n=u.get(t)??g.getNodes().get(t),i=m?.getConnection(t);if(n)await n.sendStreamMessage(r,e.bufferWhileConnecting);else{if(!i)throw new Error("Propagation target not found");await i.remote.sendStreamMessage(r)}}}),w=e.handshaker??new ZH({localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,rpcCommunicator:r,neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,maxNeighborCount:n,rpcRequestTimeout:e.rpcRequestTimeout,ongoingHandshakes:p}),v=e.neighborFinder??new XH({neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,doFindNeighbors:e=>w.attemptHandshakesOnContacts(e),minCount:n}),E=e.neighborUpdateManager??new i$({neighbors:u,nearbyNodeView:d,localPeerDescriptor:e.localPeerDescriptor,neighborFinder:v,streamPartId:e.streamPartId,rpcCommunicator:r,neighborUpdateInterval:o,neighborTargetCount:n,ongoingHandshakes:p}),A=e.inspector??new k$({localPeerDescriptor:e.localPeerDescriptor,rpcCommunicator:r,streamPartId:e.streamPartId,connectionLocker:e.connectionLocker});return{...e,neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,rpcCommunicator:r,handshaker:w,neighborFinder:v,neighborUpdateManager:E,propagation:b,neighborTargetCount:n,nodeViewSize:i,proxyConnectionRpcLocal:m,inspector:A,temporaryConnectionRpcLocal:g,plumtreeManager:y}})(e)),x$=new Bv("ProxyConnectionRpcRemote");class O$ extends wz{async requestConnection(e,t){const r={direction:t,userId:RE(e)},n=this.formDhtRpcOptions({timeout:yz});try{return(await this.getClient().requestConnection(r,n)).accepted}catch(e){return x$.debug("ProxyConnectionRequest failed with error",{err:e}),!1}}}const D$=new Bv("ProxyClient"),B$="system/proxy-client";class L$ extends Sl{rpcCommunicator;contentDeliveryRpcLocal;options;duplicateDetectors=new Map;definition;connections=new Map;propagation;neighbors;abortController;constructor(e){super(),this.options=e,this.rpcCommunicator=new Kz(C$(e.streamPartId),e.transport),this.neighbors=new p$(Mj(this.options.localPeerDescriptor),1e3),this.contentDeliveryRpcLocal=new s$({localPeerDescriptor:this.options.localPeerDescriptor,streamPartId:this.options.streamPartId,markAndCheckDuplicate:(e,t)=>l$(this.duplicateDetectors,e,t),broadcast:(e,t)=>this.broadcast(e,t),onLeaveNotice:e=>{const t=this.neighbors.get(e);t&&setImmediate((()=>this.onNodeDisconnected(t.getPeerDescriptor())))},rpcCommunicator:this.rpcCommunicator,markForInspection:()=>{}}),this.propagation=new y$({minPropagationTargets:e.minPropagationTargets,maxMessages:e.maxPropagationBufferSize,ttl:e.propagationBufferTtl,sendToNeighbor:async(e,t)=>{const r=this.neighbors.get(e);if(!r)throw new Error("Propagation target not found");await r.sendStreamMessage(t)}}),this.abortController=new AbortController}registerDefaultServerMethods(){this.rpcCommunicator.registerRpcNotification(aH,"sendStreamMessage",((e,t)=>this.contentDeliveryRpcLocal.sendStreamMessage(e,t))),this.rpcCommunicator.registerRpcNotification(mH,"leaveStreamPartNotice",((e,t)=>this.contentDeliveryRpcLocal.leaveStreamPartNotice(e,t)))}async setProxies(e,t,r,n){if(D$.trace("Setting proxies",{streamPartId:this.options.streamPartId,peerDescriptors:e,direction:r,userId:t,connectionCount:n}),void 0!==n&&n>e.length)throw new Error("Cannot set connectionCount above the size of the configured array of nodes");const i=new Map;e.forEach((e=>{i.set(Mj(e),e)})),this.definition={nodes:i,userId:t,direction:r,connectionCount:n??e.length},await this.updateConnections()}async updateConnections(){await Promise.all(this.getInvalidConnections().map((async e=>{await this.closeConnection(e)})));const e=this.definition.connectionCount-this.connections.size;e>0?await this.openRandomConnections(e):e<0&&await this.closeRandomConnections(-e)}getInvalidConnections(){return Array.from(this.connections.keys()).filter((e=>!this.definition.nodes.has(e)||this.definition.direction!==this.connections.get(e).direction))}async openRandomConnections(e){const t=$G(Array.from(this.definition.nodes.keys()).filter((e=>!this.connections.has(e))),e);await Promise.all(t.map((e=>this.attemptConnection(e,this.definition.userId,this.definition.direction))))}async attemptConnection(e,t,r){const n=this.definition.nodes.get(e),i=new O$(this.options.localPeerDescriptor,n,this.rpcCommunicator,FH);if(await i.requestConnection(t,r)){this.options.connectionLocker.lockConnection(n,B$),this.connections.set(e,{peerDescriptor:n,direction:r});const t=new VH(this.options.localPeerDescriptor,n,this.rpcCommunicator,LH);this.neighbors.add(t),this.propagation.onNeighborJoined(e),D$.info("Open proxy connection",{nodeId:e,streamPartId:this.options.streamPartId})}else D$.warn("Unable to open proxy connection",{nodeId:e,streamPartId:this.options.streamPartId})}async closeRandomConnections(e){const t=$G(Array.from(this.connections.keys()),e);await Promise.allSettled(t.map((e=>this.closeConnection(e))))}async closeConnection(e){if(this.connections.has(e)){D$.info("Close proxy connection",{nodeId:e});const t=this.neighbors.get(e);t?.leaveStreamPartNotice(this.options.streamPartId,!1),this.removeConnection(this.connections.get(e).peerDescriptor)}}removeConnection(e){const t=Mj(e);this.connections.delete(t),this.neighbors.remove(t),this.options.connectionLocker.unlockConnection(e,B$)}broadcast(e,t){t||l$(this.duplicateDetectors,e.messageId,e.previousMessageRef),this.emit("message",e),this.propagation.feedUnseenMessage(e,this.neighbors.getIds(),t??null)}hasConnection(e,t){return this.connections.has(e)&&this.connections.get(e).direction===t}getDirection(){return this.definition.direction}async onNodeDisconnected(e){const t=Mj(e);this.connections.has(t)&&(this.options.connectionLocker.unlockConnection(e,B$),this.removeConnection(e),await(async(e,t,r,n=1e4)=>{for(;;){try{return await e()}catch{D$.warn(`Failed ${t} (retrying after delay)`,{delayInMs:n})}await Qv(n,r)}})((()=>this.updateConnections()),"updating proxy connections",this.abortController.signal))}async start(){this.registerDefaultServerMethods(),oE(this.options.transport,"disconnected",(e=>this.onNodeDisconnected(e)),this.abortController.signal)}getDiagnosticInfo(){return{neighbors:this.neighbors.getAll().map((e=>e.getPeerDescriptor()))}}stop(){this.neighbors.getAll().forEach((e=>{this.options.connectionLocker.unlockConnection(e.getPeerDescriptor(),B$),e.leaveStreamPartNotice(this.options.streamPartId,!1)})),this.neighbors.stop(),this.rpcCommunicator.destroy(),this.connections.clear(),this.abortController.abort()}}const F$=new Bv("ContentDeliveryManager"),U$=e=>{return _j((t=e,Buffer.from(Zr(pw(t)))));var t};class j$ extends Sl{transport;connectionLocker;controlLayerNode;metricsContext;metrics;options;streamParts;knownStreamPartEntryPoints=new Map;started=!1;destroyed=!1;constructor(e){super(),this.options=e,this.streamParts=new Map,this.metricsContext=e.metricsContext??new $v,this.metrics={broadcastMessagesPerSecond:new Hv,broadcastBytesPerSecond:new Hv},this.metricsContext.addMetrics("node",this.metrics)}async start(e,t,r){this.started||this.destroyed||(this.started=!0,this.controlLayerNode=e,this.transport=t,this.connectionLocker=r)}async destroy(){this.started&&!this.destroyed&&(F$.trace("Destroying ContentDeliveryManager"),this.destroyed=!0,await Promise.all(Array.from(this.streamParts.values()).map((e=>e.stop()))),this.streamParts.clear(),this.removeAllListeners(),this.controlLayerNode=void 0,this.transport=void 0,this.connectionLocker=void 0)}broadcast(e,t){const r=EE(e.messageId.streamId,e.messageId.streamPartition);F$.debug(`Broadcasting to stream part ${r}`),this.joinStreamPart(r,t),this.streamParts.get(r).broadcast(e),"contentMessage"===e.body.oneofKind&&(this.metrics.broadcastMessagesPerSecond.record(1),this.metrics.broadcastBytesPerSecond.record(e.body.contentMessage.content.length))}async leaveStreamPart(e){const t=this.streamParts.get(e);t&&(await t.stop(),this.streamParts.delete(e))}joinStreamPart(e,t){let r=this.streamParts.get(e);if(void 0!==r)return;F$.debug(`Join stream part ${e}`);const n=this.createDiscoveryLayerNode(e,this.knownStreamPartEntryPoints.get(e)??[]),i=new rV({key:U$(e),localPeerDescriptor:this.getPeerDescriptor(),fetchDataFromDht:e=>this.controlLayerNode.fetchDataFromDht(e),storeDataToDht:(e,t)=>this.controlLayerNode.storeDataToDht(e,t),deleteDataFromDht:async(e,t)=>this.controlLayerNode.deleteDataFromDht(e,t)}),s=new iV({discoveryLayerNode:n,discoverEntryPoints:async()=>i.fetchNodes()}),o=this.createContentDeliveryLayerNode(e,n,(()=>i.isLocalNodeStored()),t),a=new sV(n,i);r={proxied:!1,discoveryLayerNode:n,node:o,networkSplitAvoidance:s,broadcast:e=>o.broadcast(e),stop:async()=>{a.destroy(),s.destroy(),await i.destroy(),o.stop(),await n.stop()},getDiagnosticInfo:()=>o.getDiagnosticInfo()},this.streamParts.set(e,r),o.on("message",(e=>{this.emit("newMessage",e)}));const c=async()=>{if(this.destroyed||i.isLocalNodeStored()||this.knownStreamPartEntryPoints.has(e))return;(await i.fetchNodes()).length<8&&await i.storeAndKeepLocalNode()};n.on("manualRejoinRequired",(async()=>{a.isRunning()||s.isRunning()||(F$.debug("Manual rejoin required for stream part",{streamPartId:e}),await a.reconnect())})),o.on("entryPointLeaveDetected",(()=>c())),setImmediate((async()=>{try{await this.startLayersAndJoinDht(e,i)}catch(t){F$.warn(`Failed to join to stream part ${e}`,{err:t})}}))}async startLayersAndJoinDht(e,t){F$.debug(`Start layers and join DHT for stream part ${e}`);const r=this.streamParts.get(e);if(void 0===r||r.proxied)return;this.transport.isPrivateClientMode()&&await this.transport.disablePrivateClientMode(),await r.discoveryLayerNode.start(),await r.node.start();const n=this.knownStreamPartEntryPoints.get(e);if(void 0!==n)await Promise.all([r.discoveryLayerNode.joinDht(n),r.discoveryLayerNode.joinRing()]);else{const e=await t.fetchNodes();await Promise.all([r.discoveryLayerNode.joinDht($G(e,4)),r.discoveryLayerNode.joinRing()]),e.length<8&&(await t.storeAndKeepLocalNode(),r.discoveryLayerNode.getNeighborCount()<4&&setImmediate((()=>r.networkSplitAvoidance.avoidNetworkSplit())))}}createDiscoveryLayerNode(e,t){return new OG({transport:this.controlLayerNode,connectionsView:this.controlLayerNode.getConnectionsView(),serviceId:"layer1::"+e,peerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),entryPoints:t,numberOfNodesPerKBucket:4,rpcRequestTimeout:yz,dhtJoinTimeout:2e4,periodicallyPingNeighbors:!0,periodicallyPingRingContacts:!0,neighborPingLimit:16})}createContentDeliveryLayerNode(e,t,r,n){return M$({streamPartId:e,transport:this.transport,discoveryLayerNode:t,connectionLocker:this.connectionLocker,localPeerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),minPropagationTargets:this.options.streamPartitionMinPropagationTargets,neighborTargetCount:this.options.streamPartitionNeighborTargetCount,maxPropagationBufferSize:this.options.streamPartitionMaxPropagationBufferSize,acceptProxyConnections:this.options.acceptProxyConnections,rpcRequestTimeout:this.options.rpcRequestTimeout,neighborUpdateInterval:this.options.neighborUpdateInterval,isLocalNodeEntryPoint:r,bufferWhileConnecting:this.options.bufferWhileConnecting,plumtreeOptimization:n?.plumtreeOptimization?.enabled,plumtreeMaxPausedNeighbors:!0===n?.plumtreeOptimization?.enabled?n?.plumtreeOptimization?.maxPausedNeighbors:void 0})}async setProxies(e,t,r,n,i){if(this.options.acceptProxyConnections)throw new Error("cannot set proxies when acceptProxyConnections=true");if(t.length>0&&(void 0===i||i>0)){let s;this.isProxiedStreamPart(e)?s=this.streamParts.get(e).client:(s=this.createProxyClient(e),this.streamParts.set(e,{proxied:!0,client:s,broadcast:e=>s.broadcast(e),stop:async()=>s.stop(),getDiagnosticInfo:()=>s.getDiagnosticInfo()}),s.on("message",(e=>{this.emit("newMessage",e)})),Array.from(this.streamParts.values()).every((e=>e.proxied))&&await this.transport.enablePrivateClientMode(),await s.start()),await s.setProxies(t,r,n,i)}else await(this.streamParts.get(e)?.stop()),this.streamParts.delete(e)}createProxyClient(e){return new L$({transport:this.transport,localPeerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),streamPartId:e,connectionLocker:this.connectionLocker,minPropagationTargets:this.options.streamPartitionMinPropagationTargets??2,maxPropagationBufferSize:this.options.streamPartitionMaxPropagationBufferSize??150,propagationBufferTtl:1e4})}async inspect(e,t){const r=this.streamParts.get(t);return void 0!==r&&!r.proxied&&r.node.inspect(e)}getNodeInfo(){const e=Array.from(this.streamParts.entries()).filter((([e,t])=>!1===t.proxied));return e.map((([e])=>{const t=this.streamParts.get(e);return{id:e,controlLayerNeighbors:t.discoveryLayerNode.getNeighbors(),deprecatedContentDeliveryLayerNeighbors:[],contentDeliveryLayerNeighbors:t.node.getInfos()}}))}setStreamPartEntryPoints(e,t){this.knownStreamPartEntryPoints.set(e,t)}isProxiedStreamPart(e,t){const r=this.streamParts.get(e);return void 0!==r&&r.proxied&&(void 0===t||r.client.getDirection()===t)}getStreamPartDelivery(e){return this.streamParts.get(e)}hasStreamPart(e){return this.streamParts.has(e)}getPeerDescriptor(){return this.controlLayerNode.getLocalPeerDescriptor()}getNodeId(){return Mj(this.controlLayerNode.getLocalPeerDescriptor())}getNeighbors(e){const t=this.streamParts.get(e);return!1===t?.proxied?t.node.getNeighbors().map((e=>Mj(e))):[]}getStreamParts(){return Array.from(this.streamParts.keys()).map((e=>AE.parse(e)))}getDiagnosticInfo(){return{streamParts:this.getStreamParts().map((e=>({id:e,info:this.getStreamPartDelivery(e).getDiagnosticInfo()})))}}}class q$ extends wz{async getInfo(){return this.getClient().getInfo({},this.formDhtRpcOptions())}}class z${ownPeerDescriptor;rpcCommunicator;constructor(e,t){this.ownPeerDescriptor=e,this.rpcCommunicator=t}async getInfo(e){return new q$(this.ownPeerDescriptor,e,this.rpcCommunicator,zH).getInfo()}}class K${stack;rpcCommunicator;constructor(e,t){this.stack=e,this.rpcCommunicator=t,this.registerDefaultServerMethods()}registerDefaultServerMethods(){this.rpcCommunicator.registerRpcMethod(CH,IH,"getInfo",(()=>this.getInfo()))}async getInfo(){return this.stack.createNodeInfo()}}const G$=new Bv("NetworkStack"),V$=[],H$=async()=>{const e=[...V$];await Promise.all(e.map((e=>e.stop())))};if("object"==typeof process&&"function"==typeof process?.on){["exit","SIGINT","SIGUSR1","SIGUSR2","uncaughtException","unhandledRejection","SIGTERM"].forEach((e=>{process.on(e,(async t=>{const r="uncaughtException"===e||"unhandledRejection"===e;r&&G$.error(`exit event: ${e}`,t),await H$(),process.exit(r?1:0)}))}))}"object"==typeof window&&window.addEventListener("unload",(async()=>{await H$()}));class $${controlLayerNode;contentDeliveryManager;stopped=!1;metricsContext;options;nodeInfoRpcLocal;nodeInfoClient;constructor(e){this.options=e,this.metricsContext=e.metricsContext??new $v,this.controlLayerNode=new OG({...e.layer0,metricsContext:this.metricsContext,allowIncomingPrivateConnections:e.networkNode?.acceptProxyConnections}),this.contentDeliveryManager=new j$({...e.networkNode,metricsContext:this.metricsContext}),V$.push(this)}async joinStreamPart(e,t,r){if(this.getContentDeliveryManager().isProxiedStreamPart(e))throw new Error(`Cannot join to ${e} as proxy connections have been set`);await this.ensureConnectedToControlLayer(),this.getContentDeliveryManager().joinStreamPart(e,r),void 0!==t&&await iE((()=>this.getContentDeliveryManager().getNeighbors(e).length>=t.minCount),t.timeout)}async broadcast(t,r){const n=EE(t.messageId.streamId,t.messageId.streamPartition);if(this.getContentDeliveryManager().isProxiedStreamPart(n,e.ProxyDirection.SUBSCRIBE)&&"contentMessage"===t.body.oneofKind)throw new Error(`Cannot broadcast to ${n} as proxy subscribe connections have been set`);this.contentDeliveryManager.isProxiedStreamPart(n)||await this.ensureConnectedToControlLayer(),this.getContentDeliveryManager().broadcast(t,r)}async start(e=!0){G$.info("Starting a Streamr Network Node"),await this.controlLayerNode.start(),G$.info(`Node id is ${Mj(this.controlLayerNode.getLocalPeerDescriptor())}`);const t=this.controlLayerNode.getTransport();if(this.options.layer0?.entryPoints?.some((e=>xj(e,this.controlLayerNode.getLocalPeerDescriptor())))?await(this.controlLayerNode?.joinDht(this.options.layer0.entryPoints)):e&&await this.ensureConnectedToControlLayer(),await(this.contentDeliveryManager?.start(this.controlLayerNode,t,t)),this.contentDeliveryManager){const e=new Kz("system/node-info-rpc",this.getConnectionManager());this.nodeInfoRpcLocal=new K$(this,e),this.nodeInfoClient=new z$(this.controlLayerNode.getLocalPeerDescriptor(),e)}}async ensureConnectedToControlLayer(){this.controlLayerNode.hasJoined()||(setImmediate((async()=>{void 0!==this.options.layer0?.entryPoints&&await(this.controlLayerNode?.joinDht(this.options.layer0.entryPoints))})),await this.controlLayerNode.waitForNetworkConnectivity())}getContentDeliveryManager(){return this.contentDeliveryManager}getControlLayerNode(){return this.controlLayerNode}getMetricsContext(){return this.metricsContext}async fetchNodeInfo(e){return xj(e,this.getControlLayerNode().getLocalPeerDescriptor())?this.createNodeInfo():this.nodeInfoClient.getInfo(e)}createNodeInfo(){return{peerDescriptor:this.getControlLayerNode().getLocalPeerDescriptor(),controlLayer:{connections:this.getControlLayerNode().getConnectionsView().getConnections(),neighbors:this.getControlLayerNode().getNeighbors()},streamPartitions:this.getContentDeliveryManager().getNodeInfo(),applicationVersion:"103.3.1"}}getOptions(){return this.options}getConnectionManager(){return this.controlLayerNode.getTransport()}async stop(){this.stopped||(this.stopped=!0,ej(V$,this),await this.contentDeliveryManager.destroy(),await this.controlLayerNode.stop(),this.contentDeliveryManager=void 0,this.controlLayerNode=void 0)}}class W${stack;stopped=!1;externalNetworkRpc;constructor(e){this.stack=e}async start(e){await this.stack.start(e),this.externalNetworkRpc=new XG(this.stack.getControlLayerNode().getTransport())}async inspect(e,t){return this.stack.getContentDeliveryManager().inspect(e,t)}async broadcast(e,t){await this.stack.broadcast(e,t)}async join(e,t,r){await this.stack.joinStreamPart(e,t,r)}async setProxies(e,t,r,n,i){await this.stack.getContentDeliveryManager().setProxies(e,t,r,n,i)}isProxiedStreamPart(e){return this.stack.getContentDeliveryManager().isProxiedStreamPart(e)}addMessageListener(e){this.stack.getContentDeliveryManager().on("newMessage",e)}setStreamPartEntryPoints(e,t){this.stack.getContentDeliveryManager().setStreamPartEntryPoints(e,t)}removeMessageListener(e){this.stack.getContentDeliveryManager().off("newMessage",e)}async leave(e){this.stopped||await this.stack.getContentDeliveryManager().leaveStreamPart(e)}getNeighbors(e){return this.stack.getContentDeliveryManager().getNeighbors(e)}hasStreamPart(e){return this.stack.getContentDeliveryManager().hasStreamPart(e)}async stop(){this.stopped=!0,this.externalNetworkRpc.destroy(),await this.stack.stop()}getPeerDescriptor(){return this.stack.getControlLayerNode().getLocalPeerDescriptor()}getMetricsContext(){return this.stack.getMetricsContext()}getNodeId(){return this.stack.getContentDeliveryManager().getNodeId()}getOptions(){return this.stack.getOptions()}getStreamParts(){return this.stack.getContentDeliveryManager().getStreamParts()}async fetchNodeInfo(e){return this.stack.fetchNodeInfo(e)}getDiagnosticInfo(){return{controlLayer:this.stack.getControlLayerNode().getDiagnosticInfo(),contentLayer:this.stack.getContentDeliveryManager().getDiagnosticInfo()}}registerExternalNetworkRpcMethod(e,t,r,n){this.externalNetworkRpc.registerRpcMethod(e,t,r,n)}createExternalRpcClient(e){return this.externalNetworkRpc.createRpcClient(e)}}class J$ extends Error{code;constructor(e,t){super(e),this.code=t}}function Q$(e,t){if(void 0===t)throw new J$(`Expected ${e} to not be undefined.`)}function Z$(e,t,r=!1){if(!r||void 0!==t){if(Q$(e,t),!Number.isInteger(t))throw new J$(`Expected ${e} to be an integer but was a ${typeof t} (${t}).`);if(t<0)throw new J$(`Expected ${e} to not be negative (${t}).`)}}class Y${timestamp;sequenceNumber;constructor(e,t){Z$("timestamp",e),Z$("sequenceNumber",t,!0),this.timestamp=e,this.sequenceNumber=t}compareTo(e){return this.timestamp<e.timestamp?-1:this.timestamp>e.timestamp?1:this.sequenceNumber<e.sequenceNumber?-1:this.sequenceNumber>e.sequenceNumber?1:0}}class X${streamId;streamPartition;timestamp;sequenceNumber;publisherId;msgChainId;constructor(e,t,r,n,i,s){Z$("streamPartition",t),Z$("timestamp",r),Z$("sequenceNumber",n),this.streamId=e,this.streamPartition=t,this.timestamp=r,this.sequenceNumber=n,this.publisherId=i,this.msgChainId=s}getStreamPartID(){return EE(this.streamId,this.streamPartition)}toMessageRef(){return new Y$(this.timestamp,this.sequenceNumber)}}var eW;e.StreamMessageType=void 0,(eW=e.StreamMessageType||(e.StreamMessageType={}))[eW.MESSAGE=0]="MESSAGE",eW[eW.GROUP_KEY_REQUEST=1]="GROUP_KEY_REQUEST",eW[eW.GROUP_KEY_RESPONSE=2]="GROUP_KEY_RESPONSE";class tW{messageId;prevMsgRef;messageType;content;contentType;signature;signatureType;encryptionType;groupKeyId;newGroupKey;constructor({messageId:t,prevMsgRef:r,messageType:n=e.StreamMessageType.MESSAGE,content:i,contentType:s,signature:o,signatureType:a,encryptionType:c,groupKeyId:u,newGroupKey:l}){!function(e,t){if(void 0===t)return;const r=e.toMessageRef().compareTo(t);if(0===r)throw new J$(`prevMessageRef cannot be identical to current. Current: ${JSON.stringify(e.toMessageRef())} Previous: ${JSON.stringify(t)}`);if(r<0)throw new J$(`prevMessageRef must come before current. Current: ${JSON.stringify(e.toMessageRef())} Previous: ${JSON.stringify(t)}`)}(t,r),c===e.EncryptionType.AES&&Q$("groupKeyId",u),this.messageId=t,this.prevMsgRef=r,this.messageType=n,this.contentType=s,this.encryptionType=c,this.groupKeyId=u,this.newGroupKey=l,this.signature=o,this.signatureType=a,this.content=i}getStreamId(){return this.messageId.streamId}getStreamPartition(){return this.messageId.streamPartition}getStreamPartID(){return this.messageId.getStreamPartID()}getTimestamp(){return this.messageId.timestamp}getSequenceNumber(){return this.messageId.sequenceNumber}getPublisherId(){return this.messageId.publisherId}getMsgChainId(){return this.messageId.msgChainId}getMessageRef(){return new Y$(this.getTimestamp(),this.getSequenceNumber())}getParsedContent(){if(this.encryptionType!==e.EncryptionType.NONE||this.contentType===e.ContentType.BINARY)return this.content;if(this.contentType!==e.ContentType.JSON)throw new uA(`Unknown content type: ${this.contentType}`,"ASSERTION_FAILED",this);try{return JSON.parse(fw(this.content))}catch(e){throw new uA(`Unable to parse JSON: ${e}`,"INVALID_MESSAGE_CONTENT",this)}}static isAESEncrypted(t){return t.encryptionType===e.EncryptionType.AES}}class rW{static toProtobuf(t){const r={timestamp:t.getTimestamp(),sequenceNumber:t.getSequenceNumber(),streamId:t.getStreamId(),streamPartition:t.getStreamPartition(),publisherId:RE(t.getPublisherId()),messageChainId:t.getMsgChainId()};let n,i;if(t.prevMsgRef&&(n={timestamp:t.prevMsgRef.timestamp,sequenceNumber:t.prevMsgRef.sequenceNumber}),t.messageType===e.StreamMessageType.MESSAGE){let e;t.newGroupKey&&(e={id:t.newGroupKey.id,data:t.newGroupKey.data}),i={oneofKind:"contentMessage",contentMessage:{content:t.content,contentType:t.contentType,encryptionType:t.encryptionType,groupKeyId:t.groupKeyId??void 0,newGroupKey:e}}}else if(t.messageType===e.StreamMessageType.GROUP_KEY_REQUEST)i={oneofKind:"groupKeyRequest",groupKeyRequest:uH.fromBinary(t.content)};else{if(t.messageType!==e.StreamMessageType.GROUP_KEY_RESPONSE)throw new Error("invalid message type");i={oneofKind:"groupKeyResponse",groupKeyResponse:lH.fromBinary(t.content)}}return{messageId:r,previousMessageRef:n,signature:t.signature,signatureType:t.signatureType,body:i}}static toClientProtocol(t){let r,n,i,s,o=e.ContentType.BINARY,a=e.EncryptionType.NONE;if("contentMessage"===t.body.oneofKind)r=e.StreamMessageType.MESSAGE,n=t.body.contentMessage.content,o=t.body.contentMessage.contentType,a=t.body.contentMessage.encryptionType,i=t.body.contentMessage.newGroupKey,s=t.body.contentMessage.groupKeyId;else if("groupKeyRequest"===t.body.oneofKind){r=e.StreamMessageType.GROUP_KEY_REQUEST;try{n=uH.toBinary(t.body.groupKeyRequest)}catch(e){throw new Error(`invalid group key request: ${e}`)}}else{if("groupKeyResponse"!==t.body.oneofKind)throw new Error("invalid message type");r=e.StreamMessageType.GROUP_KEY_RESPONSE;try{n=lH.toBinary(t.body.groupKeyResponse)}catch(e){throw new Error(`invalid group key response: ${e}`)}}const c=new X$(t.messageId.streamId,t.messageId.streamPartition,Number(t.messageId.timestamp),t.messageId.sequenceNumber,kE(t.messageId.publisherId),t.messageId.messageChainId);let u;t.previousMessageRef&&(u=new Y$(Number(t.previousMessageRef.timestamp),t.previousMessageRef.sequenceNumber));return new tW({messageId:c,prevMsgRef:u,messageType:r,content:n,contentType:o,signature:t.signature,signatureType:t.signatureType,encryptionType:a,groupKeyId:s,newGroupKey:i})}}function nW(e){return rW.toClientProtocol(aH.fromBinary(e))}async function*iW(e,t,r){let n=0;for await(const r of e){try{await t(r,n,e)}catch(e){throw e}finally{n+=1}yield r}}async function*sW(e,t,r){let n=0;for await(const r of e)try{yield await t(r,n,e)}catch(e){throw e}finally{n+=1}}async function*oW(e,t,r){let n=0;for await(const i of e){let s;try{s=await t(i,n,e)}catch(e){if(r){await r(e,i);continue}throw e}finally{n+=1}s&&(yield i)}}class aW{isLocked=!1;pending;open(){this.isLocked||this.clearPending()}lock(){this.isLocked||(this.isLocked=!0,this.clearPending())}error(e){this.isLocked||this.clearPending(e)}close(){this.isLocked||(this.pending??=new eb)}setOpenState(e){e?this.open():this.close()}isOpen(){return!this.isLocked&&!this.pending}clearPending(e){const{pending:t}=this;t&&(this.pending=void 0,e?t.reject(e):t.resolve(void 0))}async check(){return this.pending&&await this.pending,!this.isLocked}}class cW{buffer=[];bufferSize;writeGate;readGate;error;iterator;isIterating=!1;constructor(e=256){if(!(e>0&&Number.isSafeInteger(e)))throw new uA(`bufferSize must be a safe positive integer, got: ${e}`,"INVALID_ARGUMENT");this.bufferSize=e,this.writeGate=new aW,this.readGate=new aW,this.writeGate.close(),this.readGate.close(),this.iterator=this.iterate()}async push(e){return!!this.isWritable()&&(this.buffer.push(e),this.updateWriteGate(),this.readGate.open(),this.writeGate.check())}updateWriteGate(){this.writeGate.setOpenState(!this.isFull())}end(e){e&&(this.error=e),this.lock()}lock(){this.writeGate.lock(),this.readGate.lock()}endWrite(e){e&&!this.error&&(this.error=e),this.readGate.open(),this.writeGate.lock()}isFull(){return this.buffer.length>=this.bufferSize}isDone(){return this.writeGate.isLocked&&this.readGate.isLocked}isWritable(){return!this.writeGate.isLocked&&!this.readGate.isLocked}async*iterate(){this.isIterating=!0;try{for(;!this.readGate.isLocked;){for(;this.buffer.length&&!this.readGate.isLocked;){const t=this.buffer.shift();if(this.updateWriteGate(),(e=t)&&(e instanceof Error||e?.stack&&e.message&&"string"==typeof e.stack&&"string"==typeof e.message))throw t;yield t}if(0===this.buffer.length&&this.writeGate.isLocked)break;if(this.isDone())break;this.readGate.close();if(!await this.readGate.check())break}const{error:t}=this;if(t)throw this.error=void 0,t}finally{this.buffer=[],this.lock()}var e}get length(){return this.buffer.length}clear(){this.buffer=[]}async throw(e){return this.endWrite(e),this.iterator.throw(e)}async return(e){return this.end(),this.iterator.return(e)}next(){return this.iterator.next()}[Symbol.asyncIterator](){if(this.isIterating)throw new this.constructor.Error(this,"already iterating");return this}async[Symbol.asyncDispose](){this.end()}}var uW,lW,hW=pt();function dW(e,t){if("pipe"in e)return e;const r=new Tr.PassThrough(t);return async function(e,t){const r=e.getReader(),n=new AbortController;try{for(;;){const{value:e,done:i}=await r.read();if(i)break;if(!t.writable)break;if(!t.write(e))try{await hW.once(t,"drain",n)}catch(e){if("AbortError"===e.name)break;throw e}}}catch(e){t.destroy(e),n.abort()}finally{t.end();try{await r.cancel()}catch(e){}r.releaseLock()}}(e,r),r}var fW=function(){if(lW)return uW;lW=1;var e=Ju(),t=0;return uW=function(r){var n=++t;return e(r)+n},uW}(),pW=n(fW);let gW;function mW(e=""){return void 0===gW&&(gW=xF()),pW(`${gW}${e?`-${e}`:""}`)}const yW=new Bv("sdk-utils"),bW=((e,{maxPrefixes:t=256}={})=>{let r={},n=!1;const i=(i="ID",s="-")=>{if(r[i]=(r[i]+1||0)%Number.MAX_SAFE_INTEGER,!n){const e=Object.keys(r).length;e>t&&(n=!0,console.warn(`counterId should not be used for a large number of unique prefixes: ${e} > ${t}`))}return[e,i,r[i]].filter((e=>null!=e)).join(s)};return i.clear=(...e)=>{if(e.length){const[t]=e;delete r[t]}else r={}},i})();function wW(e){return bE("/assignments",nb(e))}class vW{delegate;constructor(e){this.delegate=new hj({maxSize:e,sizeCalculation:()=>1})}add(e){this.delegate.set(e,!0)}has(e){return this.delegate.has(e)}delete(e){this.delegate.delete(e)}}function EW(t){const r=t.type===e.NetworkNodeType.BROWSER?Zj.BROWSER:Zj.NODEJS,n={...t,nodeId:Nj(t.nodeId??t.id),type:r,websocket:t.websocket};return void 0!==n.id&&delete n.id,n}function AW(t){return{nodeId:_j(t.nodeId),type:t.type===Zj.NODEJS?e.NetworkNodeType.NODEJS:e.NetworkNodeType.BROWSER,websocket:t.websocket,region:t.region}}const SW=e=>Array.isArray(e)?e.map((e=>e.toString())).join("|"):e.toString();class kW extends Error{response;constructor(e){super(`Fetch error, url=${e.url}`),this.response=e}}var RW,CW={exports:{}};var IW=function(){if(RW)return CW.exports;RW=1;class e extends Error{constructor(){super("Throttled function aborted"),this.name="AbortError"}}return CW.exports=({limit:t,interval:r,strict:n})=>{if(!Number.isFinite(t))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(r))throw new TypeError("Expected `interval` to be a finite number");const i=new Map;let s=0,o=0;const a=[];const c=n?function(){const e=Date.now();if(a.length<t)return a.push(e),0;const n=a.shift()+r;return e>=n?(a.push(e),0):(a.push(n),n-e)}:function(){const e=Date.now();return e-s>r?(o=1,s=e,0):(o<t?o++:(s+=r,o=1),s-e)};return t=>{const r=function(...e){if(!r.isEnabled)return(async()=>t.apply(this,e))();let n;return new Promise(((r,s)=>{n=setTimeout((()=>{r(t.apply(this,e)),i.delete(n)}),c()),i.set(n,s)}))};return r.abort=()=>{for(const t of i.keys())clearTimeout(t),i.get(t)(new e);i.clear(),a.splice(0,a.length)},r.isEnabled=!0,r}},CW.exports.AbortError=e,CW.exports}(),PW=n(IW);function TW(e,t=1){const r=gD(t);return Object.assign(((...t)=>r((()=>e(...t)))),{clear(){r.clearQueue()}})}function _W(e){let t={status:"init"};return Object.assign((async function(...r){const n=t;if("pending"===n.status)return n.promise;if("fulfilled"===n.status)return n.value;if("rejected"===n.status)throw n.reason;t=n;const i=(async()=>{try{const t=await e(...r);return Object.assign(n,{promise:void 0,status:"fulfilled",value:t}),t}catch(e){throw Object.assign(n,{promise:void 0,status:"rejected",reason:e}),e}})();return i.catch((()=>{})),Object.assign(n,{status:"pending",promise:i}),i}),{isStarted:()=>"init"!==t.status,reset(){t={status:"init"}}})}var NW;!function(e){e.ONCE="ONCE",e.ONE="ONE",e.QUEUE="QUEUE",e.PARALLEL="PARALLEL"}(NW||(NW={}));class MW{static TRIGGER_TYPE=NW;static create(e=NW.PARALLEL){return new this(e)}static once(){return this.create(NW.ONCE)}static one(){return this.create(NW.ONE)}static queue(){return this.create(NW.QUEUE)}static parallel(){return this.create(NW.PARALLEL)}listeners=[];isEnded=!1;triggerCountValue=0;triggerType;constructor(e=NW.PARALLEL){switch(this.triggerType=e,this.trigger=Function.prototype.bind.call(this.trigger,this),e){case NW.ONCE:this.trigger=_W(this.trigger);break;case NW.QUEUE:this.trigger=TW(this.trigger);break;case NW.ONE:this.trigger=function(e){const t=_W(e);return async(...e)=>{try{return await t(...e)}finally{t.reset()}}}(this.trigger);break;case NW.PARALLEL:break;default:throw new Error(`unknown trigger type: ${e}`)}}triggerCount(){return this.triggerCountValue}lastValue;end=(...e)=>{this.lastValue=e,this.isEnded=!0};wait(){return new Promise((e=>{this.once(((...t)=>e(t[0])))}))}async getLastValue(){if(this.currentTask&&await this.currentTask,!this.lastValue)throw new Error("Signal ended with no value");return this.lastValue}listen(e){return e?this.isEnded?(this.getLastValue().then((t=>e(...t))).catch((()=>{})),this):(this.listeners.push(e),this):new Promise((e=>{this.once(((...t)=>{e(t[0])}))}))}once(e){if(!e)return this.listen();const t=Object.assign(((...t)=>(this.unlisten(e),e(...t))),{listener:e});return this.listen(t)}countListeners(){return this.listeners.length}unlisten(e){const t=this.listeners.findIndex((t=>t===e||"listener"in t&&t.listener===e));return this.listeners.splice(t,1),this}async execTrigger(...e){if(this.isEnded)return;this.triggerCountValue+=1;const t=this.listeners.slice();this.triggerType===NW.ONCE&&(this.listeners=[],this.end(...e)),t.length&&await t.reduce((async(t,r)=>{await t,await r(...e)}),Promise.resolve())}currentTask;async trigger(...e){const t=this.execTrigger(...e);this.currentTask=t;try{await this.currentTask}finally{this.currentTask===t&&(this.currentTask=void 0)}}async*[Symbol.asyncIterator](){for(;!this.isEnded;)yield await this.listen()}}class xW extends MW{seenErrors=new WeakSet;ignoredErrors=new WeakSet;minListeners=1;async execTrigger(...e){if(this.isEnded)return;this.triggerCountValue+=1;const t=this.listeners.slice();this.triggerType===NW.ONCE&&(this.listeners=[],this.end(...e)),t.length&&await t.reduce((async(t,r)=>{try{await t}catch(e){return void await r(e)}await r(...e)}),Promise.resolve())}async trigger(...e){const t=e[0];if(this.ignoredErrors.has(t))return;if(this.seenErrors.has(t))throw t;this.seenErrors.add(t);const r=!!(this.countListeners()>=this.minListeners);try{if(await super.trigger(...e),!r)throw t;this.ignoredErrors.add(t)}catch(e){throw this.seenErrors.add(e),e}}}class OW{source;transforms;constructor(e,t=[]){this.source=this.setSource(e),this.transforms=t}pipe(e){return this.transforms.push(e),this}clearTransforms(){this.transforms=[]}setSource(e){const t="id"in e?e.id:function(e,t=""){return bW(e.constructor.name)+t}(e,"Source");return this.source=Object.assign(e,{id:t}),this.source}getTransforms(){return this.transforms}}class DW{source;iterator;isIterating=!1;isCleaningUp=!1;definition;constructor(e,t){this.source=e,this.definition=t??new OW(e),this.cleanup=_W(this.cleanup.bind(this)),this.iterator=function(e,t){if(!t)return async function*(){yield*e}();let r,n,i=!1,s=!1,o=e=>(n??=Promise.resolve(t(e)).finally((()=>{o=()=>{}})),n);function a(e){return async(...t)=>{if(s=!0,i)return e(...t);try{return await e(...t)}catch(e){throw r??=e,e}finally{await o(r)}}}const c=async function*(){i=!0;try{yield*e}catch(e){throw r??=e,e}finally{await o(r)}}(),u=c[Symbol.asyncIterator].bind(c);let l;return l="cancel"in e?Object.assign(c,{cancel:t=>e.cancel(t),isCancelled:()=>e.isCancelled()}):c,Object.assign(l,{return:a(l.return.bind(l)),throw:a(l.throw.bind(l)),[Symbol.asyncIterator]:()=>s&&!i?async function*(){try{"return"in e&&await e.return(void 0)}finally{await o()}}():u()})}(this.iterate(),this.cleanup),this.handleError=this.handleError.bind(this)}pipe(e){if(this.isIterating)throw new uA(`cannot pipe after already iterating: ${this.isIterating}`,"PIPELINE_ERROR");return this.definition.pipe(e),this}onFinally=MW.once();onBeforeFinally=MW.once();onMessage=MW.create();onError=xW.create();filter(e){return this.pipe((t=>oW(t,e,this.onError.trigger)))}flow(){return setImmediate((()=>{this.isIterating||async function(e,t=e=>e){(async e=>{for await(const t of e);})(iW(e,t))}(this)})),this}async cleanup(e){this.isCleaningUp=!0;try{try{e&&await this.onError.trigger(e)}finally{await this.definition.source.return(void 0)}}finally{await this.onBeforeFinally.trigger(),await this.onFinally.trigger(e),this.definition.clearTransforms()}}async handleError(e){await this.onError.trigger(e)}async*iterate(){if(this.isIterating=!0,!this.definition.source)throw new uA("no source","PIPELINE_ERROR");const e=this.definition.getTransforms().reduce(((e,t)=>t(e)),this.definition.source);try{for await(const t of e)await this.onMessage.trigger(t),yield t;this.isCleaningUp=!0}catch(e){this.isCleaningUp=!0,await this.handleError(e)}finally{this.isCleaningUp=!0,this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger()}}async throw(e){if(this.isCleaningUp)throw e;return this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger(),await this.definition.source.throw(e).catch((()=>{})),this.iterator.throw(e)}async return(e){return this.isCleaningUp?Promise.resolve({done:!0,value:e}):(this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger(),await this.definition.source.return(void 0),this.iterator.return(e))}async next(){return this.iterator.next()}[Symbol.asyncIterator](){if(this.isIterating)throw new uA("already iterating","PIPELINE_ERROR");return this}[Symbol.asyncDispose](){return this.cleanup()}}class BW extends DW{source;constructor(e=256){const t=new cW(e);super(t),this.source=t}pipe(e){return super.pipe(e),this}filter(e){return super.filter(e)}async push(e){return this.source.push(e)}async handleError(e){try{await this.onError.trigger(e)}catch(e){if(this.isCleaningUp)throw e;await this.push(e)}}end(e){this.source.end(e)}endWrite(e){this.source.endWrite(e)}isDone(){return this.source.isDone()}get length(){return this.source.length||0}clear(){this.source.clear()}}var LW=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},FW=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let UW=class{onDestroy=MW.once();trigger=this.destroy;abortSignal;constructor(){const e=new AbortController;this.abortSignal=e.signal,this.onDestroy.listen((()=>{e.abort()}))}destroy(){return this.onDestroy.trigger()}assertNotDestroyed(){if(this.isDestroyed())throw new uA("Client is destroyed. Create a new instance","CLIENT_DESTROYED")}isDestroyed(){return this.onDestroy.triggerCount()>0}};var jW,qW,zW,KW,GW,VW;UW=LW([q(d.ContainerScoped),FW("design:paramtypes",[])],UW);var HW=function(){if(VW)return GW;VW=1;var e=Jc(),t=function(){if(qW)return jW;qW=1;var e=Vc(),t=$c(),r=Wc(),n=Jc(),i=Qc(),s=Zc(),o=Math.min;return jW=function(a,c,u){for(var l=u?r:t,h=a[0].length,d=a.length,f=d,p=Array(d),g=1/0,m=[];f--;){var y=a[f];f&&c&&(y=n(y,i(c))),g=o(y.length,g),p[f]=!u&&(c||h>=120&&y.length>=120)?new e(f&&y):void 0}y=a[0];var b=-1,w=p[0];e:for(;++b<h&&m.length<g;){var v=y[b],E=c?c(v):v;if(v=u||0!==v?v:0,!(w?s(w,E):l(m,E,u))){for(f=d;--f;){var A=p[f];if(!(A?s(A,E):l(a[f],E,u)))continue e}w&&w.push(E),m.push(v)}}return m},jW}(),r=nu(),n=function(){if(KW)return zW;KW=1;var e=ou();return zW=function(t){return e(t)?t:[]}}(),i=r((function(r){var i=e(r,n);return i.length&&i[0]===r[0]?t(i):[]}));return GW=i}(),$W=n(HW),WW=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},JW=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},QW=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};function ZW(e){const t=e;if(void 0!==t.id)return t.id;if(void 0!==t.stream)return t.stream;if(void 0!==t.streamId)return t.streamId;throw new Error('streamDefinition: object must have property: "id", "stream", or "streamId"')}let YW=class{identity;constructor(e){this.identity=e}async toStreamID(e){let t;return wE.isPathOnlyFormat(e)&&(t=nb(await this.identity.getUserId())),bE(e,t)}async toStreamPartID(e){const[t,r]=await this.toStreamPartElements(e);return EE(t,r??0)}async toStreamPartElements(e){const[t,r]=function(e){if("string"==typeof e)return AE.parseRawElements(e);if("object"==typeof e)return[ZW(e),e.partition];throw new Error("streamDefinition: must be of type string or object")}(e);return[await this.toStreamID(t),r]}async getMatcher(e){const[t,r]=await this.toStreamPartElements(e);return e=>t===AE.getStreamID(e)&&(void 0===r||r===AE.getStreamPartition(e))}};YW=WW([q(d.ContainerScoped),QW(0,U(kA)),JW("design:paramtypes",[RA])],YW);const XW=e=>{try{return JSON.parse(e)}catch(e){return{}}},eJ=e=>{const t=e.partitions;if(void 0!==t)try{!function(e){if(!Number.isSafeInteger(e)||e<0||e>100)throw new Error(`invalid streamPartition value: ${e}`)}(t)}catch{throw new uA(`Invalid partition count: ${t}`,"INVALID_STREAM_METADATA")}return t??1};var tJ;e.StreamPermission=void 0,(tJ=e.StreamPermission||(e.StreamPermission={})).EDIT="edit",tJ.DELETE="delete",tJ.PUBLISH="publish",tJ.SUBSCRIBE="subscribe",tJ.GRANT="grant";const rJ="0x0000000000000000000000000000000000000000",nJ=e=>!0===e.public,iJ=e=>"userId"in e?{...e,userId:kE(e.userId)}:e,sJ=t=>{switch(t){case e.StreamPermission.EDIT:return 0n;case e.StreamPermission.DELETE:return 1n;case e.StreamPermission.PUBLISH:return 2n;case e.StreamPermission.SUBSCRIBE:return 3n;case e.StreamPermission.GRANT:return 4n}return 0n},oJ=t=>{const r=Math.round(Date.now()/1e3),n=[];return t.canEdit&&n.push(e.StreamPermission.EDIT),t.canDelete&&n.push(e.StreamPermission.DELETE),t.publishExpiration>r&&n.push(e.StreamPermission.PUBLISH),t.subscribeExpiration>r&&n.push(e.StreamPermission.SUBSCRIBE),t.canGrant&&n.push(e.StreamPermission.GRANT),n};class aJ{delegate;pendingPromises=new Map;opts;constructor(e){this.delegate="maxSize"in e?new hj({maxSize:e.maxSize,sizeCalculation:()=>1,ttl:e.maxAge}):new Map,this.opts={isCacheableValue:()=>!0,...e}}async get(e){const t=SW(e),r=this.pendingPromises.get(t);if(void 0!==r)return await r;{let r=this.delegate.get(t);if(void 0===r){const n=this.opts.valueFactory(e);let i;this.pendingPromises.set(t,n);try{i=await n}finally{this.pendingPromises.delete(t)}r={key:e,value:i},this.opts.isCacheableValue(i)&&this.delegate.set(t,r)}return r.value}}set(e,t){this.delegate.set(SW(e),{key:e,value:t})}invalidate(e){for(const[t,r]of this.delegate.entries())e(r.key)&&this.delegate.delete(t)}*values(){for(const e of this.delegate.values())yield e.value}}const cJ=e=>new aJ(e),uJ=e=>new aJ(e);var lJ,hJ,dJ,fJ,pJ,gJ,mJ,yJ;function bJ(){if(fJ)return dJ;fJ=1;var e=Pl(),t=zU(),r=function(){if(hJ)return lJ;hJ=1;var e=sL(),t=Ku();return lJ=function(r,n){return n.length<2?r:e(r,t(n,0,-1))},lJ}(),n=_l();return dJ=function(i,s){return s=e(s,i),null==(i=r(i,s))||delete i[n(t(s))]},dJ}var wJ,vJ,EJ,AJ,SJ,kJ,RJ,CJ,IJ=function(){if(yJ)return mJ;yJ=1;var e=uL(),t=function(){if(gJ)return pJ;gJ=1;var e=bJ(),t=Tl(),r=Array.prototype.splice;return pJ=function(n,i){for(var s=n?i.length:0,o=s-1;s--;){var a=i[s];if(s==o||a!==c){var c=a;t(a)?r.call(n,a,1):e(n,a)}}return n},pJ}();return mJ=function(r,n){var i=[];if(!r||!r.length)return i;var s=-1,o=[],a=r.length;for(n=e(n,3);++s<a;){var c=r[s];n(c,s,r)&&(i.push(c),o.push(s))}return t(r,o),i},mJ}(),PJ=n(IJ);function TJ(){if(AJ)return EJ;AJ=1;var e=YB(),t=vJ?wJ:(vJ=1,wJ=function(){}),r=VB(),n=e&&1/r(new e([,-0]))[1]==1/0?function(t){return new e(t)}:t;return EJ=n}var _J=function(){if(CJ)return RJ;CJ=1;var e=function(){if(kJ)return SJ;kJ=1;var e=Vc(),t=$c(),r=Wc(),n=Zc(),i=TJ(),s=VB();return SJ=function(o,a,c){var u=-1,l=t,h=o.length,d=!0,f=[],p=f;if(c)d=!1,l=r;else if(h>=200){var g=a?null:i(o);if(g)return s(g);d=!1,l=n,p=new e}else p=a?[]:f;e:for(;++u<h;){var m=o[u],y=a?a(m):m;if(m=c||0!==m?m:0,d&&y==y){for(var b=p.length;b--;)if(p[b]===y)continue e;a&&p.push(y),f.push(m)}else l(p,y,c)||(p!==f&&p.push(y),f.push(m))}return f},SJ}();return RJ=function(t){return t&&t.length?e(t):[]},RJ}(),NJ=n(_J),MJ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},xJ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},OJ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let DJ=class{listeners=[];providers;pollInterval;abortController;constructor(e,t){this.providers=e.getSubProviders(),this.pollInterval=t.contracts.pollInterval}on(e){const t=this.listeners.length>0;this.listeners.push(e),t||this.start()}off(e){const t=this.listeners.length>0;PJ(this.listeners,(t=>t.contractAddress===e.contractAddress&&t.contractInterfaceFragment.topicHash===e.contractInterfaceFragment.topicHash&&t.onEvent==e.onEvent)),t&&0===this.listeners.length&&this.abortController.abort()}start(){const e=new AbortController;this.abortController=e,setImmediate((async()=>{const t=new Bv("ChainEventPoller",{sessionId:Wv(6)});let r;t.debug("Start polling",{pollInterval:this.pollInterval});do{try{r=await oA(this.providers).getBlockNumber()}catch(e){t.debug("Failed to query block number",{err:e}),await Qv(1e3)}}while(void 0===r);let n=0;await Jv((async()=>{const i=oA(this.providers),s=this.listeners.map((e=>e.contractInterfaceFragment.name));let o,a=0;try{if(n>=30&&(a=await i.getBlockNumber()+1,t.debug("Fetch next block number explicitly",{newFromBlock:a}),e.signal.aborted))return;t.debug("Polling",{fromBlock:r,eventNames:s});const c={address:NJ(this.listeners.map((e=>e.contractAddress))),topics:[NJ(this.listeners.map((e=>e.contractInterfaceFragment.topicHash)))],fromBlock:r},u=await i.getLogs(c);o=[];for(const e of u){const t=this.listeners.find((t=>t.contractAddress===nb(e.address)&&t.contractInterfaceFragment.topicHash===e.topics[0]));if(void 0!==t){const r=new uN([t.contractInterfaceFragment.format("minimal")]).decodeEventLog(t.contractInterfaceFragment.name,e.data,e.topics);o.push({contractAddress:t.contractAddress,name:t.contractInterfaceFragment.name,args:r,blockNumber:e.blockNumber})}}t.debug("Polled",{fromBlock:r,events:o.length})}catch(e){t.debug("Failed to poll",{reason:e?.reason,eventNames:s,fromBlock:r})}if(!e.signal.aborted){if(void 0!==o&&o.length>0){for(const e of o){const t=this.listeners.filter((t=>t.contractAddress===e.contractAddress&&t.contractInterfaceFragment.name===e.name));for(const r of t)r.onEvent(e.args,e.blockNumber)}a=Math.max(...o.map((e=>e.blockNumber)))+1}void 0!==o&&a>r?(t.debug("Forward fromBlock",{before:r,after:a}),r=a,n=0):n+=1}}),this.pollInterval,!0,e.signal)}))}};DJ=MJ([q(d.ContainerScoped),OJ(1,U(cA)),xJ("design:paramtypes",[e.RpcProviderSource,Object])],DJ);const BJ=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),LJ=e=>`"${e}"`,FJ=e=>`{ ${e} }`,UJ=(t,r,n)=>{const i=[];return t.includes(e.StreamPermission.EDIT)&&i.push("canEdit: true"),t.includes(e.StreamPermission.DELETE)&&i.push("canDelete: true"),t.includes(e.StreamPermission.PUBLISH)&&i.push(`publishExpiration_gt: "${n}"`),t.includes(e.StreamPermission.SUBSCRIBE)&&i.push(`subscribeExpiration_gt: "${n}"`),t.includes(e.StreamPermission.GRANT)&&i.push("canGrant: true"),`${r}: [${i.map(FJ).join(", ")}]`},jJ=(t,r,n,i)=>{const s=[];if(s.push(`id_gt: "${BJ(n)}"`),void 0!==t&&s.push(`idAsString_contains: "${BJ(t)}"`),void 0!==r){const t=[],n=[r.userId];r.allowPublic&&n.push(rJ),t.push(`userId_in: [${n.map(LJ).join(",")}]`);const i=Math.round(Date.now()/1e3);void 0!==r.allOf&&t.push(UJ(r.allOf,"and",i));const o=r.anyOf??(void 0===r.allOf||0===r.allOf.length?Object.values(e.StreamPermission):void 0);void 0!==o&&t.push(UJ(o,"or",i)),s.push(`permissions_: { and: [${t.map(FJ).join(", ")}] }`)}return{query:`\n query {\n streams (\n first: ${i}\n orderBy: "id"\n where: {\n ${s.join(", ")}\n }\n ) {\n id\n metadata\n }\n }`}};var qJ,zJ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},KJ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},GJ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const VJ=t=>{for(const r of t){const t=[e.StreamPermission.EDIT,e.StreamPermission.DELETE,e.StreamPermission.GRANT],n=$W(r.permissions,t);if(n.length>0){const e=e=>new uA(`${e} is not supported for permission types: ${n.map((e=>e.toUpperCase())).join(", ")}`,"UNSUPPORTED_OPERATION");if(nJ(r))throw e("Public permission");if(42!==r.userId.length)throw e("Non-Ethereum user id")}}},HJ=(e,t,r)=>{throw"CALL_EXCEPTION"===e.reason?.code?new uA("Stream not found: id="+t,"STREAM_NOT_FOUND"):new Error(`Could not reach the ${r} Smart Contract: ${e.message}`)},$J=(e,t)=>{e.invalidate((e=>(Array.isArray(e)?e[0]:e)===t))};let WJ=qJ=class{streamRegistryContract;streamRegistryContractReadonly;contractFactory;rpcProviderSource;theGraphClient;streamIdBuilder;config;identity;logger;metadataCache;publisherCache;subscriberCache;publicSubscribePermissionCache;constructor(t,r,n,i,s,o,a,c,u){this.contractFactory=t,this.rpcProviderSource=r,this.theGraphClient=i,this.streamIdBuilder=s,this.config=o,this.identity=a,this.logger=u.createLogger("StreamRegistry"),this.streamRegistryContractReadonly=this.contractFactory.createReadContract(nb(this.config.contracts.streamRegistryChainAddress),SA.StreamRegistryABI,this.rpcProviderSource.getProvider(),"streamRegistry"),wD({sourceDefinition:{contractInterfaceFragment:new uN(SA.StreamRegistryABI).getEvent("StreamCreated"),contractAddress:nb(this.config.contracts.streamRegistryChainAddress)},sourceEmitter:n,targetName:"streamCreated",targetEmitter:c,transformation:([e,t],r)=>({streamId:bE(e),metadata:XW(t),blockNumber:r}),loggerFactory:u}),this.metadataCache=cJ({valueFactory:e=>this.getStreamMetadata_nonCached(e),...o.cache}),this.publisherCache=cJ({valueFactory:([t,r])=>this.isStreamPublisherOrSubscriber_nonCached(t,r,e.StreamPermission.PUBLISH),...o.cache}),this.subscriberCache=cJ({valueFactory:([t,r])=>this.isStreamPublisherOrSubscriber_nonCached(t,r,e.StreamPermission.SUBSCRIBE),...o.cache}),this.publicSubscribePermissionCache=cJ({valueFactory:t=>this.hasPermission({streamId:t,public:!0,permission:e.StreamPermission.SUBSCRIBE}),...o.cache})}async connectToContract(){if(void 0===this.streamRegistryContract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.streamRegistryContract=this.contractFactory.createWriteContract(nb(this.config.contracts.streamRegistryChainAddress),SA.StreamRegistryABI,e,"streamRegistry")}}async createStream(e,t){const r=await nD(this.rpcProviderSource,this.config),n=wE.getDomainAndPath(e);if(void 0===n)throw new Error(`stream id "${e}" not valid`);const[i,s]=n;if(await this.connectToContract(),function(e){return tb(e)}(i)){await mD(this.streamRegistryContract.createStreamWithENS(i,s,JSON.stringify(t),r));try{await iE((async()=>this.streamExistsOnChain(e)),this.config._timeouts.ensStreamCreation.timeout,this.config._timeouts.ensStreamCreation.retryInterval)}catch{throw new Error(`unable to create stream "${e}"`)}}else await this.ensureStreamIdInNamespaceOfAuthenticatedUser(i,e),await mD(this.streamRegistryContract.createStream(s,JSON.stringify(t),r));this.populateMetadataCache(e,t)}async ensureStreamIdInNamespaceOfAuthenticatedUser(e,t){const r=nb(await this.identity.getUserId());if(e!==r)throw new Error(`stream id "${t}" not in namespace of authenticated user "${r}"`)}async setStreamMetadata(e,t){await this.connectToContract();const r=await nD(this.rpcProviderSource,this.config);await mD(this.streamRegistryContract.updateStreamMetadata(e,JSON.stringify(t),r)),this.populateMetadataCache(e,t)}async deleteStream(e){const t=await this.streamIdBuilder.toStreamID(e);await this.connectToContract();const r=await nD(this.rpcProviderSource,this.config);await mD(this.streamRegistryContract.deleteStream(t,r)),$J(this.metadataCache,t),this.invalidatePermissionCaches(t)}async streamExistsOnChain(e){const t=await this.streamIdBuilder.toStreamID(e);return this.logger.debug("Check if stream exists on chain",{streamId:t}),this.streamRegistryContractReadonly.exists(t)}async getStreamMetadata_nonCached(e){let t;try{t=await this.streamRegistryContractReadonly.getStreamMetadata(e)}catch(t){return HJ(t,e,"StreamRegistry")}return XW(t)}async*searchStreams(e,t){const r=async function*(e,t,r){yield*r.queryEntities(((r,n)=>jJ(e,t,r,n)))}(e,t,this.theGraphClient);for await(const e of r){const t=bE(e.id);this.populateMetadataCache(t,XW(e.metadata)),yield t}}getStreamPublishers(e){return this.getStreamPublishersOrSubscribersList(e,"publishExpiration")}getStreamSubscribers(e){return this.getStreamPublishersOrSubscribersList(e,"subscribeExpiration")}async*getStreamPublishersOrSubscribersList(e,t){const r=await this.streamIdBuilder.toStreamID(e),n=oW(this.theGraphClient.queryEntities(((e,n)=>qJ.buildStreamPublishersOrSubscribersQuery(r,t,e,n))),(e=>null!==e.stream));yield*sW(n,(e=>kE(e.userId)))}static buildStreamPublishersOrSubscribersQuery(e,t,r,n){return{query:`\n {\n streamPermissions (\n first: ${n}\n orderBy: "id"\n where: {\n id_gt: "${r}"\n stream: "${e}"\n ${t}_gt: "${Math.round(Date.now()/1e3)}"\n }\n ) {\n id\n userId\n stream {\n id\n }\n }\n }`}}async hasPermission(e){if((e=>!0===e.public)(e)){const t=sJ(e.permission);return this.streamRegistryContractReadonly.hasPublicPermission(e.streamId,t)}{const t=e.allowPublic?await this.streamRegistryContractReadonly.getPermissionsForUserId(e.streamId,e.userId):await this.streamRegistryContractReadonly.getDirectPermissionsForUserId(e.streamId,e.userId);return oJ(t).includes(e.permission)}}async getPermissions(e){const t=await this.streamIdBuilder.toStreamID(e),r=await cE(this.theGraphClient.queryEntities(((e,r)=>({query:`{\n stream (id: "${t}") {\n id\n metadata\n permissions(first: ${r} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n userId\n canEdit\n canDelete\n publishExpiration\n subscribeExpiration\n canGrant\n }\n }\n }`})),(e=>{if(null!==e.stream)return e.stream.permissions;throw new uA("Stream not found: id="+t,"STREAM_NOT_FOUND")}))),n=[];return r.forEach((e=>{const t=oJ(e);t.length>0&&(e.userId===rJ?n.push({public:!0,permissions:t}):n.push({userId:kE(e.userId),permissions:t}))})),n}async grantPermissions(e,...t){VJ(t);const r=await nD(this.rpcProviderSource,this.config);return this.updatePermissions(e,((e,t,n)=>void 0===t?this.streamRegistryContract.grantPublicPermission(e,n,r):this.streamRegistryContract.grantPermissionForUserId(e,t,n,r)),...t)}async revokePermissions(e,...t){VJ(t);const r=await nD(this.rpcProviderSource,this.config);return this.updatePermissions(e,((e,t,n)=>void 0===t?this.streamRegistryContract.revokePublicPermission(e,n,r):this.streamRegistryContract.revokePermissionForUserId(e,t,n,r)),...t)}async updatePermissions(e,t,...r){const n=await this.streamIdBuilder.toStreamID(e);this.invalidatePermissionCaches(n),await this.connectToContract();for(const e of r)for(const r of e.permissions){const i=sJ(r),s=t(n,nJ(e)?void 0:e.userId,i);await mD(s)}}async setPermissions(...t){const r=[],n=[],i=[];for(const s of t){VJ(s.assignments);const t=await this.streamIdBuilder.toStreamID(s.streamId);this.invalidatePermissionCaches(t),r.push(t),n.push(s.assignments.map((e=>nJ(e)?rJ:e.userId))),i.push(s.assignments.map((t=>{return{canEdit:(r=t.permissions).includes(e.StreamPermission.EDIT),canDelete:r.includes(e.StreamPermission.DELETE),publishExpiration:r.includes(e.StreamPermission.PUBLISH)?PI:0n,subscribeExpiration:r.includes(e.StreamPermission.SUBSCRIBE)?PI:0n,canGrant:r.includes(e.StreamPermission.GRANT)};var r})))}await this.connectToContract();const s=await nD(this.rpcProviderSource,this.config),o=this.streamRegistryContract.setMultipleStreamPermissionsForUserIds(r,n,i,s);await mD(o)}async isStreamPublisherOrSubscriber_nonCached(e,t,r){try{return await this.hasPermission({streamId:e,userId:t,permission:r,allowPublic:!0})}catch(t){return HJ(t,e,"StreamPermission")}}getStreamMetadata(e){return this.metadataCache.get(e)}isStreamPublisher(e,t){return this.publisherCache.get([e,t])}isStreamSubscriber(e,t){return this.subscriberCache.get([e,t])}hasPublicSubscribePermission(e){return this.publicSubscribePermissionCache.get(e)}populateMetadataCache(e,t){this.metadataCache.set(e,t)}invalidatePermissionCaches(e){this.logger.trace("Clear permission caches for stream",{streamId:e}),$J(this.publisherCache,e),$J(this.subscriberCache,e)}};var JJ,QJ,ZJ,YJ,XJ,eQ;WJ=qJ=zJ([q(d.ContainerScoped),GJ(5,U(cA)),GJ(6,U(kA)),KJ("design:paramtypes",[SD,e.RpcProviderSource,DJ,lE,YW,Object,RA,sD,uD])],WJ);var tQ=function(){if(eQ)return XJ;eQ=1;var e=function(){if(QJ)return JJ;QJ=1;var e=Le();return JJ=function(t,r,n){for(var i=-1,s=t.length;++i<s;){var o=t[i],a=r(o);if(null!=a&&(void 0===c?a==a&&!e(a):n(a,c)))var c=a,u=o}return u},JJ}(),t=YJ?ZJ:(YJ=1,ZJ=function(e,t){return e<t}),r=Yc();return XJ=function(n){return n&&n.length?e(n,r,t):void 0},XJ}(),rQ=n(tQ),nQ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},iQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},sQ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const oQ=Symbol("GET_ALL_STORAGE_NODES");let aQ=class{streamStorageRegistryContract;streamStorageRegistryContractReadonly;streamIdBuilder;contractFactory;rpcProviderSource;theGraphClient;config;identity;logger;storageNodesCache;constructor(e,t,r,n,i,s,o,a,c){this.streamIdBuilder=e,this.contractFactory=t,this.rpcProviderSource=r,this.theGraphClient=i,this.config=s,this.identity=o,this.logger=c.createLogger("StreamStorageRegistry"),this.streamStorageRegistryContractReadonly=this.contractFactory.createReadContract(nb(this.config.contracts.streamStorageRegistryChainAddress),SA.StreamStorageRegistryABI,r.getProvider(),"streamStorageRegistry"),this.initStreamAssignmentEventListeners(a,n,c),this.storageNodesCache=cJ({valueFactory:e=>this.getStorageNodes_nonCached(e),...s.cache})}initStreamAssignmentEventListeners(e,t,r){const n=([e,t],r)=>({streamId:bE(e),nodeAddress:nb(t),blockNumber:r}),i=nb(this.config.contracts.streamStorageRegistryChainAddress),s=new uN(SA.StreamStorageRegistryABI);wD({sourceDefinition:{contractInterfaceFragment:s.getEvent("Added"),contractAddress:i},sourceEmitter:t,targetName:"streamAddedToStorageNode",targetEmitter:e,transformation:n,loggerFactory:r}),wD({sourceDefinition:{contractInterfaceFragment:s.getEvent("Removed"),contractAddress:i},sourceEmitter:t,targetName:"streamRemovedFromStorageNode",targetEmitter:e,transformation:n,loggerFactory:r})}async connectToContract(){if(!this.streamStorageRegistryContract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.streamStorageRegistryContract=this.contractFactory.createWriteContract(nb(this.config.contracts.streamStorageRegistryChainAddress),SA.StreamStorageRegistryABI,e,"streamStorageRegistry")}}async addStreamToStorageNode(e,t){const r=await this.streamIdBuilder.toStreamID(e);this.logger.debug("Add stream to storage node",{streamId:r,nodeAddress:t}),await this.connectToContract();const n=await nD(this.rpcProviderSource,this.config);await mD(this.streamStorageRegistryContract.addStorageNode(r,t,n)),this.storageNodesCache.invalidate((e=>e===r))}async removeStreamFromStorageNode(e,t){const r=await this.streamIdBuilder.toStreamID(e);this.logger.debug("Remove stream from storage node",{streamId:r,nodeAddress:t}),await this.connectToContract();const n=await nD(this.rpcProviderSource,this.config);await mD(this.streamStorageRegistryContract.removeStorageNode(r,t,n)),this.storageNodesCache.invalidate((e=>e===r))}async isStoredStream(e,t){const r=await this.streamIdBuilder.toStreamID(e);return this.logger.debug("Check if stream is stored in storage node",{streamId:r,nodeAddress:t}),await this.streamStorageRegistryContractReadonly.isStorageNodeOf(r,t)}async getStoredStreams(e){this.logger.debug("Get stored streams of storage node",{nodeAddress:e});const t=[],r=(await cE(this.theGraphClient.queryEntities(((t,r)=>({query:`{\n node (id: "${e}") {\n id\n metadata\n lastSeen\n storedStreams (first: ${r} orderBy: "id" where: { id_gt: "${t}"}) {\n id,\n metadata\n }\n }\n _meta {\n block {\n number\n }\n }\n }`})),(e=>(t.push(e._meta.block.number),null!==e.node?e.node.storedStreams:[]))))).map((e=>({id:bE(e.id),metadata:XW(e.metadata)})));return{streams:r,blockNumber:rQ(t)}}async getStorageNodes(e){const t=void 0!==e?await this.streamIdBuilder.toStreamID(e):oQ;return this.storageNodesCache.get(t)}async getStorageNodes_nonCached(e){let t;if(e!==oQ){const r=e;this.logger.debug("Get storage nodes of stream",{streamId:r}),t=await cE(this.theGraphClient.queryEntities(((e,t)=>({query:`{\n stream (id: "${r}") {\n id\n metadata\n storageNodes (first: ${t} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n metadata\n lastSeen\n }\n }\n }`})),(e=>null!==e.stream?e.stream.storageNodes:[])))}else this.logger.debug("Get all storage nodes"),t=await cE(this.theGraphClient.queryEntities(((e,t)=>({query:`{\n nodes (first: ${t} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n metadata\n lastSeen\n }\n }`}))));return t.map((e=>nb(e.id)))}};aQ=nQ([q(d.ContainerScoped),sQ(5,U(cA)),sQ(6,U(kA)),iQ("design:paramtypes",[YW,SD,e.RpcProviderSource,DJ,lE,Object,RA,sD,uD])],aQ);
62
+ /*! MIT License. Copyright 2015-2022 Richard Moore <me@ricmoo.com>. See LICENSE.txt. */var Bx,Lx,Fx,Ux=window&&window.__classPrivateFieldGet||function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)},jx=window&&window.__classPrivateFieldSet||function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r};const qx={16:10,24:12,32:14},zx=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],Kx=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],Gx=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],Vx=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],Hx=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],$x=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],Wx=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],Jx=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],Qx=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],Zx=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],Yx=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],Xx=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],eO=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],tO=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],rO=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function nO(e){const t=[];for(let r=0;r<e.length;r+=4)t.push(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]);return t}class iO{get key(){return Ux(this,Bx,"f").slice()}constructor(e){if(Bx.set(this,void 0),Lx.set(this,void 0),Fx.set(this,void 0),!(this instanceof iO))throw Error("AES must be instanitated with `new`");jx(this,Bx,new Uint8Array(e),"f");const t=qx[this.key.length];if(null==t)throw new TypeError("invalid key size (must be 16, 24 or 32 bytes)");jx(this,Fx,[],"f"),jx(this,Lx,[],"f");for(let e=0;e<=t;e++)Ux(this,Fx,"f").push([0,0,0,0]),Ux(this,Lx,"f").push([0,0,0,0]);const r=4*(t+1),n=this.key.length/4,i=nO(this.key);let s;for(let e=0;e<n;e++)s=e>>2,Ux(this,Fx,"f")[s][e%4]=i[e],Ux(this,Lx,"f")[t-s][e%4]=i[e];let o,a=0,c=n;for(;c<r;){if(o=i[n-1],i[0]^=Kx[o>>16&255]<<24^Kx[o>>8&255]<<16^Kx[255&o]<<8^Kx[o>>24&255]^zx[a]<<24,a+=1,8!=n)for(let e=1;e<n;e++)i[e]^=i[e-1];else{for(let e=1;e<n/2;e++)i[e]^=i[e-1];o=i[n/2-1],i[n/2]^=Kx[255&o]^Kx[o>>8&255]<<8^Kx[o>>16&255]<<16^Kx[o>>24&255]<<24;for(let e=n/2+1;e<n;e++)i[e]^=i[e-1]}let e,s,u=0;for(;u<n&&c<r;)e=c>>2,s=c%4,Ux(this,Fx,"f")[e][s]=i[u],Ux(this,Lx,"f")[t-e][s]=i[u++],c++}for(let e=1;e<t;e++)for(let t=0;t<4;t++)o=Ux(this,Lx,"f")[e][t],Ux(this,Lx,"f")[e][t]=Xx[o>>24&255]^eO[o>>16&255]^tO[o>>8&255]^rO[255&o]}encrypt(e){if(16!=e.length)throw new TypeError("invalid plaintext size (must be 16 bytes)");const t=Ux(this,Fx,"f").length-1,r=[0,0,0,0];let n=nO(e);for(let e=0;e<4;e++)n[e]^=Ux(this,Fx,"f")[0][e];for(let e=1;e<t;e++){for(let t=0;t<4;t++)r[t]=Vx[n[t]>>24&255]^Hx[n[(t+1)%4]>>16&255]^$x[n[(t+2)%4]>>8&255]^Wx[255&n[(t+3)%4]]^Ux(this,Fx,"f")[e][t];n=r.slice()}const i=new Uint8Array(16);let s=0;for(let e=0;e<4;e++)s=Ux(this,Fx,"f")[t][e],i[4*e]=255&(Kx[n[e]>>24&255]^s>>24),i[4*e+1]=255&(Kx[n[(e+1)%4]>>16&255]^s>>16),i[4*e+2]=255&(Kx[n[(e+2)%4]>>8&255]^s>>8),i[4*e+3]=255&(Kx[255&n[(e+3)%4]]^s);return i}decrypt(e){if(16!=e.length)throw new TypeError("invalid ciphertext size (must be 16 bytes)");const t=Ux(this,Lx,"f").length-1,r=[0,0,0,0];let n=nO(e);for(let e=0;e<4;e++)n[e]^=Ux(this,Lx,"f")[0][e];for(let e=1;e<t;e++){for(let t=0;t<4;t++)r[t]=Jx[n[t]>>24&255]^Qx[n[(t+3)%4]>>16&255]^Zx[n[(t+2)%4]>>8&255]^Yx[255&n[(t+1)%4]]^Ux(this,Lx,"f")[e][t];n=r.slice()}const i=new Uint8Array(16);let s=0;for(let e=0;e<4;e++)s=Ux(this,Lx,"f")[t][e],i[4*e]=255&(Gx[n[e]>>24&255]^s>>24),i[4*e+1]=255&(Gx[n[(e+3)%4]>>16&255]^s>>16),i[4*e+2]=255&(Gx[n[(e+2)%4]>>8&255]^s>>8),i[4*e+3]=255&(Gx[255&n[(e+1)%4]]^s);return i}}Bx=new WeakMap,Lx=new WeakMap,Fx=new WeakMap;class sO{constructor(e,t,r){if(r&&!(this instanceof r))throw new Error(`${e} must be instantiated with "new"`);Object.defineProperties(this,{aes:{enumerable:!0,value:new iO(t)},name:{enumerable:!0,value:e}})}}var oO,aO,cO=window&&window.__classPrivateFieldSet||function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r},uO=window&&window.__classPrivateFieldGet||function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class lO extends sO{constructor(e,t){if(super("ECC",e,lO),oO.set(this,void 0),aO.set(this,void 0),t){if(t.length%16)throw new TypeError("invalid iv size (must be 16 bytes)");cO(this,oO,new Uint8Array(t),"f")}else cO(this,oO,new Uint8Array(16),"f");cO(this,aO,this.iv,"f")}get iv(){return new Uint8Array(uO(this,oO,"f"))}encrypt(e){if(e.length%16)throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)");const t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=16){for(let t=0;t<16;t++)uO(this,aO,"f")[t]^=e[r+t];cO(this,aO,this.aes.encrypt(uO(this,aO,"f")),"f"),t.set(uO(this,aO,"f"),r)}return t}decrypt(e){if(e.length%16)throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)");const t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=16){const n=this.aes.decrypt(e.subarray(r,r+16));for(let i=0;i<16;i++)t[r+i]=n[i]^uO(this,aO,"f")[i],uO(this,aO,"f")[i]=e[r+i]}return t}}oO=new WeakMap,aO=new WeakMap;var hO,dO,fO,pO=window&&window.__classPrivateFieldSet||function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r},gO=window&&window.__classPrivateFieldGet||function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class mO extends sO{constructor(e,t){super("CTR",e,mO),hO.set(this,void 0),dO.set(this,void 0),fO.set(this,void 0),pO(this,fO,new Uint8Array(16),"f"),gO(this,fO,"f").fill(0),pO(this,hO,gO(this,fO,"f"),"f"),pO(this,dO,16,"f"),null==t&&(t=1),"number"==typeof t?this.setCounterValue(t):this.setCounterBytes(t)}get counter(){return new Uint8Array(gO(this,fO,"f"))}setCounterValue(e){if(!Number.isInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new TypeError("invalid counter initial integer value");for(let t=15;t>=0;--t)gO(this,fO,"f")[t]=e%256,e=Math.floor(e/256)}setCounterBytes(e){if(16!==e.length)throw new TypeError("invalid counter initial Uint8Array value length");gO(this,fO,"f").set(e)}increment(){for(let e=15;e>=0;e--){if(255!==gO(this,fO,"f")[e]){gO(this,fO,"f")[e]++;break}gO(this,fO,"f")[e]=0}}encrypt(e){var t,r;const n=new Uint8Array(e);for(let e=0;e<n.length;e++)16===gO(this,dO,"f")&&(pO(this,hO,this.aes.encrypt(gO(this,fO,"f")),"f"),pO(this,dO,0,"f"),this.increment()),n[e]^=gO(this,hO,"f")[(pO(this,dO,(r=gO(this,dO,"f"),t=r++,r),"f"),t)];return n}decrypt(e){return this.encrypt(e)}}function yO(e){return"string"!=typeof e||e.startsWith("0x")||(e="0x"+e),zA(e)}function bO(e,t){for(e=String(e);e.length<t;)e="0"+e;return e}function wO(e){return"string"==typeof e?ES(e,"NFKC"):zA(e)}function vO(e,t){const r=t.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);DA(null!=r,"invalid path","path",t);const n=r[1],i=r[3],s="!"===r[4];let o=e;for(const e of n.toLowerCase().split(".")){if(Array.isArray(o)){if(!e.match(/^[0-9]+$/))break;o=o[parseInt(e)]}else if("object"==typeof o){let t=null;for(const r in o)if(r.toLowerCase()===e){t=o[r];break}o=t}else o=null;if(null==o)break}if(DA(!s||null!=o,"missing required value","path",n),i&&null!=o){if("int"===i){if("string"==typeof o&&o.match(/^-?[0-9]+$/))return parseInt(o);if(Number.isSafeInteger(o))return o}if("number"===i&&"string"==typeof o&&o.match(/^-?[0-9.]*$/))return parseFloat(o);if("data"===i&&"string"==typeof o)return yO(o);if("array"===i&&Array.isArray(o))return o;if(i===typeof o)return o;DA(!1,`wrong type found for ${i} `,"path",n)}return o}hO=new WeakMap,dO=new WeakMap,fO=new WeakMap;const EO="m/44'/60'/0'/0/0";function AO(e){try{const t=JSON.parse(e);if(3===(null!=t.version?parseInt(t.version):0))return!0}catch(e){}return!1}function SO(e,t){const r=qA(t),n=vO(e,"crypto.ciphertext:data!");DA(HA(xR($A([r.slice(16,32),n]))).substring(2)===vO(e,"crypto.mac:string!").toLowerCase(),"incorrect password","password","[ REDACTED ]");const i=function(e,t,r){if("aes-128-ctr"===vO(e,"crypto.cipher:string")){const n=vO(e,"crypto.cipherparams.iv:data!");return HA(new mO(t,n).decrypt(r))}OA(!1,"unsupported cipher","UNSUPPORTED_OPERATION",{operation:"decrypt"})}(e,r.slice(0,16),n),s=IT(i);if(e.address){let t=e.address.toLowerCase();t.startsWith("0x")||(t="0x"+t),DA(GI(t)===s,"keystore address/privateKey mismatch","address",e.address)}const o={address:s,privateKey:i};if("0.1"===vO(e,"x-ethers.version:string")){const t=r.slice(32,64),n=vO(e,"x-ethers.mnemonicCiphertext:data!"),i=vO(e,"x-ethers.mnemonicCounter:data!"),s=new mO(t,i);o.mnemonic={path:vO(e,"x-ethers.path:string")||EO,locale:vO(e,"x-ethers.locale:string")||"en",entropy:HA(qA(s.decrypt(n)))}}return o}function kO(e){const t=vO(e,"crypto.kdf:string");if(t&&"string"==typeof t){if("scrypt"===t.toLowerCase()){const r=vO(e,"crypto.kdfparams.salt:data!"),n=vO(e,"crypto.kdfparams.n:int!"),i=vO(e,"crypto.kdfparams.r:int!"),s=vO(e,"crypto.kdfparams.p:int!");DA(n>0&&!(n&n-1),"invalid kdf.N","kdf.N",n),DA(i>0&&s>0,"invalid kdf","kdf",t);const o=vO(e,"crypto.kdfparams.dklen:int!");return DA(32===o,"invalid kdf.dklen","kdf.dflen",o),{name:"scrypt",salt:r,N:n,r:i,p:s,dkLen:64}}if("pbkdf2"===t.toLowerCase()){const t=vO(e,"crypto.kdfparams.salt:data!"),r=vO(e,"crypto.kdfparams.prf:string!"),n=r.split("-").pop();DA("sha256"===n||"sha512"===n,"invalid kdf.pdf","kdf.pdf",r);const i=vO(e,"crypto.kdfparams.c:int!"),s=vO(e,"crypto.kdfparams.dklen:int!");return DA(32===s,"invalid kdf.dklen","kdf.dklen",s),{name:"pbkdf2",salt:t,count:i,dkLen:s,algorithm:n}}}DA(!1,"unsupported key-derivation function","kdf",t)}function RO(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}function CO(e){const t=null!=e.salt?qA(e.salt,"options.salt"):sC(32);let r=1<<17,n=8,i=1;return e.scrypt&&(e.scrypt.N&&(r=e.scrypt.N),e.scrypt.r&&(n=e.scrypt.r),e.scrypt.p&&(i=e.scrypt.p)),DA("number"==typeof r&&r>0&&Number.isSafeInteger(r)&&(BigInt(r)&BigInt(r-1))===BigInt(0),"invalid scrypt N parameter","options.N",r),DA("number"==typeof n&&n>0&&Number.isSafeInteger(n),"invalid scrypt r parameter","options.r",n),DA("number"==typeof i&&i>0&&Number.isSafeInteger(i),"invalid scrypt p parameter","options.p",i),{name:"scrypt",dkLen:32,salt:t,N:r,r:n,p:i}}function IO(e,t,r,n){const i=qA(r.privateKey,"privateKey"),s=null!=n.iv?qA(n.iv,"options.iv"):sC(16);DA(16===s.length,"invalid options.iv length","options.iv",n.iv);const o=null!=n.uuid?qA(n.uuid,"options.uuid"):sC(16);DA(16===o.length,"invalid options.uuid length","options.uuid",n.iv);const a=e.slice(0,16),c=e.slice(16,32),u=qA(new mO(a,s).encrypt(i)),l=xR($A([c,u])),h={address:r.address.substring(2).toLowerCase(),id:nk(o),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:HA(s).substring(2)},ciphertext:HA(u).substring(2),kdf:"scrypt",kdfparams:{salt:HA(t.salt).substring(2),n:t.N,dklen:32,p:t.p,r:t.r},mac:l.substring(2)}};if(r.mnemonic){const t=null!=n.client?n.client:`ethers/${CA}`,i=r.mnemonic.path||EO,s=r.mnemonic.locale||"en",o=e.slice(32,64),a=qA(r.mnemonic.entropy,"account.mnemonic.entropy"),c=sC(16),u=qA(new mO(o,c).encrypt(a)),l=new Date,d="UTC--"+(l.getUTCFullYear()+"-"+bO(l.getUTCMonth()+1,2)+"-"+bO(l.getUTCDate(),2)+"T"+bO(l.getUTCHours(),2)+"-"+bO(l.getUTCMinutes(),2)+"-"+bO(l.getUTCSeconds(),2)+".0Z")+"--"+h.address;h["x-ethers"]={client:t,gethFilename:d,path:i,locale:s,mnemonicCounter:HA(c).substring(2),mnemonicCiphertext:HA(u).substring(2),version:"0.1"}}return JSON.stringify(h)}function PO(e,t,r){null==r&&(r={});const n=wO(t),i=CO(r);return IO(qA(bC(n,i.salt,i.N,i.r,i.p,64)),i,e,r)}async function TO(e,t,r){null==r&&(r={});const n=wO(t),i=CO(r);return IO(qA(await yC(n,i.salt,i.N,i.r,i.p,64,r.progressCallback)),i,e,r)}const _O="m/44'/60'/0'/0/0",NO=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]),MO=2147483648,xO=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");function OO(e,t){let r="";for(;e;)r="0123456789abcdef"[e%16]+r,e=Math.trunc(e/16);for(;r.length<2*t;)r="0"+r;return"0x"+r}function DO(e){const t=qA(e);return yS($A([t,JA(AC(AC(t)),0,4)]))}const BO={};function LO(e,t,r,n){const i=new Uint8Array(37);e&MO?(OA(null!=n,"cannot derive child of neutered node","UNSUPPORTED_OPERATION",{operation:"deriveChild"}),i.set(qA(n),1)):i.set(qA(r));for(let t=24;t>=0;t-=8)i[33+(t>>3)]=e>>24-t&255;const s=qA(pR("sha512",t,i));return{IL:s.slice(0,32),IR:s.slice(32)}}function FO(e,t){const r=t.split("/");DA(r.length>0,"invalid path","path",t),"m"===r[0]&&(DA(0===e.depth,`cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${e.depth}`,"path",t),r.shift());let n=e;for(let e=0;e<r.length;e++){const t=r[e];if(t.match(/^[0-9]+'$/)){const r=parseInt(t.substring(0,t.length-1));DA(r<MO,"invalid path index",`path[${e}]`,t),n=n.deriveChild(MO+r)}else if(t.match(/^[0-9]+$/)){const r=parseInt(t);DA(r<MO,"invalid path index",`path[${e}]`,t),n=n.deriveChild(r)}else DA(!1,"invalid path component",`path[${e}]`,t)}return n}class UO extends Ax{publicKey;fingerprint;parentFingerprint;mnemonic;chainCode;path;index;depth;constructor(e,t,r,n,i,s,o,a,c){super(t,c),UA(e,BO,"HDNodeWallet"),TA(this,{publicKey:t.compressedPublicKey});TA(this,{parentFingerprint:r,fingerprint:JA(ZR(AC(this.publicKey)),0,4),chainCode:n,path:i,index:s,depth:o}),TA(this,{mnemonic:a})}connect(e){return new UO(BO,this.signingKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.mnemonic,e)}#Ot(){const e={address:this.address,privateKey:this.privateKey},t=this.mnemonic;return this.path&&t&&"en"===t.wordlist.locale&&""===t.password&&(e.mnemonic={path:this.path,locale:"en",entropy:t.entropy}),e}async encrypt(e,t){return await TO(this.#Ot(),e,{progressCallback:t})}encryptSync(e){return PO(this.#Ot(),e)}get extendedKey(){return OA(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),DO($A(["0x0488ADE4",OO(this.depth,1),this.parentFingerprint,OO(this.index,4),this.chainCode,$A(["0x00",this.privateKey])]))}hasPath(){return null!=this.path}neuter(){return new jO(BO,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,this.provider)}deriveChild(e){const t=cS(e,"index");DA(t<=4294967295,"invalid index","index",t);let r=this.path;r&&(r+="/"+(2147483647&t),t&MO&&(r+="'"));const{IR:n,IL:i}=LO(t,this.chainCode,this.publicKey,this.privateKey),s=new FI(uS((aS(i)+BigInt(this.privateKey))%xO,32));return new UO(BO,s,this.fingerprint,HA(n),r,t,this.depth+1,this.mnemonic,this.provider)}derivePath(e){return FO(this,e)}static#Dt(e,t){DA(GA(e),"invalid seed","seed","[REDACTED]");const r=qA(e,"seed");DA(r.length>=16&&r.length<=64,"invalid seed","seed","[REDACTED]");const n=qA(pR("sha512",NO,r)),i=new FI(HA(n.slice(0,32)));return new UO(BO,i,"0x00000000",HA(n.slice(32)),"m",0,0,t,null)}static fromExtendedKey(e){const t=lS(function(e){let t=gS;for(let r=0;r<e.length;r++)t*=mS,t+=pS(e[r]);return t}(e));DA(82===t.length||DO(t.slice(0,78))===e,"invalid extended key","extendedKey","[ REDACTED ]");const r=t[4],n=HA(t.slice(5,9)),i=parseInt(HA(t.slice(9,13)).substring(2),16),s=HA(t.slice(13,45)),o=t.slice(45,78);switch(HA(t.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const e=HA(o);return new jO(BO,IT(e),e,n,s,null,i,r,null)}case"0x0488ade4":case"0x04358394 ":if(0!==o[0])break;return new UO(BO,new FI(o.slice(1)),n,s,null,i,r,null,null)}DA(!1,"invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(e,t,r){null==e&&(e=""),null==t&&(t=_O),null==r&&(r=_x.wordlist());const n=Dx.fromEntropy(sC(16),e,r);return UO.#Dt(n.computeSeed(),n).derivePath(t)}static fromMnemonic(e,t){return t||(t=_O),UO.#Dt(e.computeSeed(),e).derivePath(t)}static fromPhrase(e,t,r,n){null==t&&(t=""),null==r&&(r=_O),null==n&&(n=_x.wordlist());const i=Dx.fromPhrase(e,t,n);return UO.#Dt(i.computeSeed(),i).derivePath(r)}static fromSeed(e){return UO.#Dt(e,null)}}class jO extends $M{publicKey;fingerprint;parentFingerprint;chainCode;path;index;depth;constructor(e,t,r,n,i,s,o,a,c){super(t,c),UA(e,BO,"HDNodeVoidWallet"),TA(this,{publicKey:r});TA(this,{publicKey:r,fingerprint:JA(ZR(AC(r)),0,4),parentFingerprint:n,chainCode:i,path:s,index:o,depth:a})}connect(e){return new jO(BO,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,e)}get extendedKey(){return OA(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"}),DO($A(["0x0488B21E",OO(this.depth,1),this.parentFingerprint,OO(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return null!=this.path}deriveChild(e){const t=cS(e,"index");DA(t<=4294967295,"invalid index","index",t);let r=this.path;r&&(r+="/"+(2147483647&t),t&MO&&(r+="'"));const{IR:n,IL:i}=LO(t,this.chainCode,this.publicKey,null),s=FI.addPoints(i,this.publicKey,!0),o=IT(s);return new jO(BO,o,s,this.fingerprint,HA(n),r,t,this.depth+1,this.provider)}derivePath(e){return FO(this,e)}}function qO(e){try{if(JSON.parse(e).encseed)return!0}catch(e){}return!1}function zO(e,t){const r=JSON.parse(e),n=wO(t),i=GI(vO(r,"ethaddr:string!")),s=yO(vO(r,"encseed:string!"));DA(s&&s.length%16==0,"invalid encseed","json",e);const o=qA(tC(n,n,2e3,32,"sha256")).slice(0,16),a=s.slice(0,16),c=s.slice(16),u=function(e){if(e.length<16)throw new TypeError("PKCS#7 invalid length");const t=e[e.length-1];if(t>16)throw new TypeError("PKCS#7 padding byte out of range");const r=e.length-t;for(let n=0;n<t;n++)if(e[r+n]!==t)throw new TypeError("PKCS#7 invalid padding byte");return new Uint8Array(e.subarray(0,r))}(qA(new lO(o,a).decrypt(c)));let l="";for(let e=0;e<u.length;e++)l+=String.fromCharCode(u[e]);return{address:i,privateKey:mP(l)}}function KO(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}class GO extends Ax{constructor(e,t){"string"!=typeof e||e.startsWith("0x")||(e="0x"+e),super("string"==typeof e?new FI(e):e,t)}connect(e){return new GO(this.signingKey,e)}async encrypt(e,t){const r={address:this.address,privateKey:this.privateKey};return await TO(r,e,{progressCallback:t})}encryptSync(e){return PO({address:this.address,privateKey:this.privateKey},e)}static#Bt(e){if(DA(e,"invalid JSON wallet","json","[ REDACTED ]"),"mnemonic"in e&&e.mnemonic&&"en"===e.mnemonic.locale){const t=Dx.fromEntropy(e.mnemonic.entropy),r=UO.fromMnemonic(t,e.mnemonic.path);if(r.address===e.address&&r.privateKey===e.privateKey)return r;console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key")}const t=new GO(e.privateKey);return DA(t.address===e.address,"address/privateKey mismatch","json","[ REDACTED ]"),t}static async fromEncryptedJson(e,t,r){let n=null;return AO(e)?n=await async function(e,t,r){const n=JSON.parse(e),i=wO(t),s=kO(n);if("pbkdf2"===s.name){r&&(r(0),await RO(0));const{salt:e,count:t,dkLen:o,algorithm:a}=s,c=tC(i,e,t,o,a);return r&&(r(1),await RO(0)),SO(n,c)}OA("scrypt"===s.name,"cannot be reached","UNKNOWN_ERROR",{params:s});const{salt:o,N:a,r:c,p:u,dkLen:l}=s;return SO(n,await yC(i,o,a,c,u,l,r))}(e,t,r):qO(e)&&(r&&(r(0),await KO(0)),n=zO(e,t),r&&(r(1),await KO(0))),GO.#Bt(n)}static fromEncryptedJsonSync(e,t){let r=null;return AO(e)?r=function(e,t){const r=JSON.parse(e),n=wO(t),i=kO(r);if("pbkdf2"===i.name){const{salt:e,count:t,dkLen:s,algorithm:o}=i;return SO(r,tC(n,e,t,s,o))}OA("scrypt"===i.name,"cannot be reached","UNKNOWN_ERROR",{params:i});const{salt:s,N:o,r:a,p:c,dkLen:u}=i;return SO(r,bC(n,s,o,a,c,u))}(e,t):qO(e)?r=zO(e,t):DA(!1,"invalid JSON wallet","json","[ REDACTED ]"),GO.#Bt(r)}static createRandom(e){const t=UO.createRandom();return e?t.connect(e):t}static fromPhrase(e,t){const r=UO.fromPhrase(e);return t?r.connect(t):r}}const VO=new Bv("LoggingJsonRpcProvider");class HO extends ox{urlConfig;constructor(e,t,r){super(e,t,r),this.urlConfig=e}async send(e,t){const r=Wv(5),n=Date.now(),i={traceId:r,method:e,params:t,connection:{url:this.urlConfig.url,timeout:this.urlConfig.timeout}};let s;VO.debug("Send request",i);try{s=await super.send(e,t)}catch(e){throw VO.debug("Encountered error while requesting",{...i,err:e,elapsedTime:Date.now()-n}),e}return VO.debug("Received response",{...i,elapsedTime:Date.now()-n}),s}}var $O,WO,JO={},QO={};var ZO=(WO||(WO=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.config=void 0;const t=($O||($O=1,Object.defineProperty(QO,"__esModule",{value:!0}),QO.config=void 0,QO.config={dev0:{id:8995,name:"dev0",nativeCurrency:{symbol:"DEV",name:"Developer Ethereum",decimals:18},rpcEndpoints:[{url:"http://10.200.10.1:8545"},{url:"ws://10.200.10.1:8545"}],contracts:{AMB:"0xaFA0dc5Ad21796C9106a36D68f69aAD69994BB64",DATA:"0xbAA81A0179015bE47Ad439566374F2Bae098686F",DataUnionFactory:"0x90a0480c6fA6b2dC967d8F03660c81C8a5A7c465",DataUnionTemplate:"0x07a4CaF6064ACFe4c279e32e5ed2F376B36DcB3F",DefaultFeeOracle:"0x454E0fEcCf4611eA9E41C986E4A2949CFD4b53d4",ENS:"0x92E8435EB56fD01BF4C79B66d47AC1A94338BB03",FIFSRegistrar:"0x57B81a9442805f88c4617B506206531e72d96290",Marketplace:"0xF1371c0f40528406dc4f4cAf89924eA9Da49E866",MarketplaceV3:"0x56e57Bf7422eDe1ED75520D4387829feEe8a8319",MigrationManager:"0xc7aaf6c62e86a36395d8108fe95d5f758794c16c",PublicResolver:"0xBc0c81a318D57ae54dA28DE69184A9c3aE9a1e1c",TokenMediator:"0xedD2aa644a6843F2e5133Fe3d6BD3F4080d97D9F",TrackerRegistry:"0xBFCF120a8fD17670536f1B27D9737B775b2FD4CF",Uniswap2Router:"0xeE1bC9a7BFF1fFD913f4c97B6177D47E804E1920",UniswapAdapter:"0xE4eA76e830a659282368cA2e7E4d18C4AE52D8B3",Uniswap2AdapterForMarketplaceV3:"0xDbcdfB708A006A9AebC592C4520289cD87a95938",XDATA:"0x6d0F3bF9aD2455b4F62f22fFD21317e1E3eEFE5C","core-api":"0xFCAd0B19bB29D4674531d6f115237E16AfCE377c"}},dev1:{id:8997,name:"dev1",nativeCurrency:{symbol:"DEV",name:"Developer Ethereum",decimals:18},rpcEndpoints:[{url:"http://10.200.10.1:8546"},{url:"ws://10.200.10.1:8546"}],contracts:{AMB:"0xaFA0dc5Ad21796C9106a36D68f69aAD69994BB64",DATA:"0x73Be21733CC5D08e1a14Ea9a399fb27DB3BEf8fF",DataUnionFactory:"0x50aAa135AeBAC61E8394F80fF2Df091fcb66b072",DefaultFeeOracle:"0xd1FA6C06E1D838Bb989640A2C4b8a499FD0ab187",DataUnionTemplate:"0xC2F87E37019e227F2Be5030aabBCc7eAF136e05c",LINK:"0x3387F44140ea19100232873a5aAf9E46608c791E",Marketplace:"0xa072C42CB167d68D4c1cA15d0e4d0bd93E74A80f",MarketplaceV3:"0xA90CeCcA042312b8f2e8B924C04Ce62516CBF7b2",MarketplaceV4:"0xB9372284e0D61607aF3B7EF5f022e7D599Ed2a37",ProjectRegistryV1:"0x3C841B9Aa08166e9B864972930703e878d25804B",ProjectStakingV1:"0xBFCF120a8fD17670536f1B27D9737B775b2FD4CF",Mediator:"0xedD2aa644a6843F2e5133Fe3d6BD3F4080d97D9F",StorageNodeRegistry:"0x231b810D98702782963472e1D60a25496999E75D",StreamRegistry:"0x6cCdd5d866ea766f6DF5965aA98DeCCD629ff222",ENSCacheV2:"0x611900fD07BB133016Ed85553aF9586771da5ff9",StreamStorageRegistry:"0xd04af489677001444280366Dd0885B03dAaDe71D",Uniswap2Router:"0xdc5F6368cd31330adC259386e78604a5E29E9415",StreamrConfig:"0xa86863053cECFD9f6f861e0Fd39a042238411b75",SponsorshipFactory:"0x58C8e321d561123649bE41445cB0690Ec3d27Fe9",SponsorshipDefaultLeavePolicy:"0xa2338F8be0941B361baBebb01ab8da5725CF0a33",SponsorshipMaxOperatorsJoinPolicy:"0x2521E0480004056c35e199a1BBE2FdA9119032A0",SponsorshipOperatorContractOnlyJoinPolicy:"0xd8F0a63e5EB661695620c92af5d981D18d5a484E",SponsorshipStakeWeightedAllocationPolicy:"0xef927F18D2ac3862c6ABCAa953203A4DbF7f519e",SponsorshipVoteKickPolicy:"0x0617466e5bC15027c604A56E35b172E06d689E4f",OperatorFactory:"0xcb5bCb343218044C547AFdcBa2e50Ac728D0DcA3",OperatorDefaultDelegationPolicy:"0x03CF38C75BFb9F4466fBA0aEd95f2613B0D1bCA0",OperatorDefaultUndelegationPolicy:"0x67A0E9C9c21d11dB4eBAe420aBf705626a3a2561",OperatorDefaultExchangeRatePolicy:"0x252743660fACD52e7CEF851CEB1c133B58Fb526d"},theGraphUrl:"http://10.200.10.1:8000/subgraphs/name/streamr-dev/network-subgraphs"},dev2:{id:31337,name:"dev2",nativeCurrency:{symbol:"DEV",name:"Developer Ethereum",decimals:18},rpcEndpoints:[{url:"http://10.200.10.1:8547"}],adminPrivateKey:"0x5e98cce00cff5dea6b454889f359a4ec06b9fa6b88e9d69b86de8e1c81887da0",contracts:{DATA:"0xbAA81A0179015bE47Ad439566374F2Bae098686F",ENS:"0xEAA002f7Dc60178B6103f8617Be45a9D3df659B6",FIFSRegistrar:"0xF1371c0f40528406dc4f4cAf89924eA9Da49E866",PublicResolver:"0xdc5F6368cd31330adC259386e78604a5E29E9415",TrackerRegistry:"0xE4eA76e830a659282368cA2e7E4d18C4AE52D8B3",StorageNodeRegistry:"0x338090C5492C5c5E41a4458f5FC4b205cbc54A24",StreamRegistry:"0x18E0937099660B82464475Ea2B7e6Af4f2BFE5F0",ENSCacheV2:"0x7739b57beC285539A62434DF9808f66ebB405ba3",StreamStorageRegistry:"0xB73189CeBCc870bE6f9aa16764bbB3665e4B49B6",StreamrConfig:"0x00E680d549FE53a627a3db86a6F88fA2471CFfAa",SponsorshipOperatorContractOnlyJoinPolicy:"0xB9372284e0D61607aF3B7EF5f022e7D599Ed2a37",SponsorshipMaxOperatorsJoinPolicy:"0x36368Be8Cde49558Ab6ceEf2632984b282Db8775",SponsorshipStakeWeightedAllocationPolicy:"0xc24BA8c05E5206F1bE57bfA0aD14E9882126eD38",SponsorshipDefaultLeavePolicy:"0xBFCF120a8fD17670536f1B27D9737B775b2FD4CF",SponsorshipVoteKickPolicy:"0x92E8435EB56fD01BF4C79B66d47AC1A94338BB03",SponsorshipFactory:"0x699B4bE95614f017Bb622e427d3232837Cc814E6",OperatorDefaultDelegationPolicy:"0x5159FBF2e0Ff63e35b17293416fdf7a0909a0cDA",OperatorDefaultExchangeRatePolicy:"0xfC31c70FafCbFe399195C789602ae2455B247fD2",OperatorDefaultUndelegationPolicy:"0xBacF06448F4f14361AD80d425686021b041F3B2C",OperatorFactory:"0xD13D34d37e2c94cb35EA8D5DE7498Cb7830d26e0",ProjectRegistryV1:"0xA9166376706611110f814D1333b8E80FEc5d8f10",MarketplaceV4:"0xb8678223183d560280a7BEF68daAbB0E3daBd97D",ProjectStakingV1:"0x73a9310C43621B853C508902bb8c1DA8f1240EaE"},theGraphUrl:"http://10.200.10.1:8800/subgraphs/name/streamr-dev/network-subgraphs",entryPoints:[{nodeId:"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",websocket:{host:"10.200.10.1",port:40500,tls:!1}}]},alfajores:{id:44787,name:"Celo Alfajores",nativeCurrency:{symbol:"CELO",name:"Celo Alfajores",decimals:18},rpcEndpoints:[{url:"https://alfajores-forno.celo-testnet.org"}],contracts:{ProjectRegistryV1:"0x32A142A27A595DC75aD1443728fecCbD5650446A",MarketplaceV4:"0x14577e0D5BD77536E073712d98E471edDaFAE8b4",cUSD:"0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1"},blockExplorerUrl:"https://alfajores.celoscan.io"},optGoerli:{id:420,name:"Optimism Goerli Testnet",nativeCurrency:{symbol:"ETH",name:"Optimism Goerli Testnet Ethereum",decimals:18},rpcEndpoints:[{url:"https://goerli.optimism.io"}],contracts:{RemoteMarketplaceV1:"0xBef916b1EC6EAA3F522368f75094DAed5c228aF6",DAI:"0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1"},blockExplorerUrl:"https://goerli-optimism.etherscan.io"},ethereum:{id:1,name:"Ethereum",nativeCurrency:{symbol:"ETH",name:"Ethereum",decimals:18},rpcEndpoints:[],contracts:{AMB:"0x4C36d2919e407f0Cc2Ee3c993ccF8ac26d9CE64e",DATA:"0x8f693ca8D21b157107184d29D398A8D082b38b76",ENS:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",Marketplace:"0xdc8d23092b93f9bb7416f45dea36f55996f34867",MediatorDATA:"0x29e572d45cC33D5a68DCc8f92bfc7ded0017Bc59",MediatorXDATA:"0x2eeeDdeECe91c9F4c5bA4C8E1d784A0234C6d015",MigrationManager:"0xf32219E61c840300D1B35c939ed9E54a86163334",TrackerRegistry:"0xab9BEb0e8B106078c953CcAB4D6bF9142BeF854d",UniswapAdapter:"0xbe99db4ea1964ea9a9e80de41517901da6ef9307",XDATA:"0x0cf0ee63788a0849fe5297f3407f701e122cc023","core-api":"0xf3E5A65851C3779f468c9EcB32E6f25D9D68601a"},blockExplorerUrl:"https://etherscan.io"},gnosis:{id:100,name:"Gnosis Chain",nativeCurrency:{symbol:"xDAI",name:"xDai",decimals:18},rpcEndpoints:[{url:"https://rpc.gnosischain.com"},{url:"wss://rpc.gnosischain.com/wss"}],contracts:{AMB:"0x75Df5AF045d91108662D8080fD1FEFAd6aA0bb59",BinanceAdapterDATA:"0x193888692673b5dD46e6BC90bA8cBFeDa515c8C1",BinanceAdapterXDATA:"0x0c1aF6edA561fbDA48E9A7B1Dd46D216F31A97cC",DATA:"0x256eb8a51f382650B2A1e946b8811953640ee47D",DataUnionFactory:"0xe4515702878931b45Dfe4D89d3Fb3208910C913C",DataUnionTemplate:"0x1d425525c7A5df3736875fe76Bc3B9E776E89AcA",DataUnionFeeOracle:"0x86686266E7cA80b247151104f26d308079997637",Marketplace:"0x246dd6D96282c1ED9Ca69eF9f3e1f975fC1B8Bd5",MarketplaceV3:"0x2022E1F7749D355726Fb65285E29605A098bcb52",MediatorDATA:"0x53f3F44c434494da73EC44a6E8a8D091332bC2ce",MediatorXDATA:"0x7d55f9981d4E10A193314E001b96f72FCc901e40",MigrationManager:"0x29e572d45cC33D5a68DCc8f92bfc7ded0017Bc59",RemoteMarketplaceV1:"0x023eaE17d3dd65F1e7b4daa355e6478719Bd2BEf",StorageNodeRegistry:"0xC746847d7916623fb75849696f04827bbc34854f",UniswapAdapter:"0xc5Cd4900841a849d798725441b54fB0fec0d0f5b",Uniswap2AdapterForMarketplaceV3:"0xec92c5f94d45D1a4D917f2E07dD959b33e1AFe38",XDATA:"0xE4a2620edE1058D61BEe5F45F6414314fdf10548"},blockExplorerUrl:"https://gnosisscan.io"},binance:{id:56,name:"BNB Chain",nativeCurrency:{symbol:"BNB",name:"BNB",decimals:18},rpcEndpoints:[{url:"https://bsc-dataseed.binance.org"},{url:"wss://bsc-dataseed.binance.org"}],contracts:{DATA:"0x0864c156b3c5f69824564dec60c629ae6401bf2a",xdaiBridge:"0xa93ee7b4a7215f7e725437a6b6d7a4e7fe1dd8f0"},blockExplorerUrl:"https://bscscan.com"},polygon:{id:137,name:"Polygon",nativeCurrency:{symbol:"MATIC",name:"MATIC",decimals:18},rpcEndpoints:[{url:"https://polygon-rpc.com"},{url:"https://polygon.drpc.org"},{url:"https://rpc-mainnet.matic.quiknode.pro"},{url:"https://polygon-bor-rpc.publicnode.com"}],contracts:{ChainlinkOracle:"0x36BF71D0ba2e449fc14f9C4cF51468948E4ED27D",DATA:"0x3a9A81d576d83FF21f26f325066054540720fC34",DataUnionFactory:"0xd0B3a09A6bCee8446d10e6E7e12c78F8725C9B18",DataUnionTemplate:"0xaFe97F5a1cD3edE2c11d990e0EB0270054AA0589",DataUnionFeeOracle:"0x369Be397b3Cfe914728Bbd2329c0e5D1FE2E4202",GSNPayMaster:"0x43E69adABC664617EB9C5E19413a335e9cd4A243",GSNForwarder:"0xdA78a11FD57aF7be2eDD804840eA7f4c2A38801d",ENSCache:"0xEd9d3D29c25e197677DD84E3f7D81cCCD613B2bF",ENSCacheV2:"0xEd9d3D29c25e197677DD84E3f7D81cCCD613B2bF",Marketplace:"0x058FbB3Cf628EE51CE8864C9Ee8350f81E495A7D",MarketplaceV3:"0x1e9c22B4C92ce78Fe489C72f9D070C583D8359C3",MarketplaceV4:"0xdF8b74D735197dCD5C94bE933db080E69A958de6",ProjectRegistryV1:"0x496a6154da5aA6a021a3bd0DCd337DA80F48a6e1",ProjectStakingV1:"0xAA7a4BdBE91F143F3103206e48A8AfF21101B6DE",StorageNodeRegistry:"0x080F34fec2bc33928999Ea9e39ADc798bEF3E0d6",StreamRegistry:"0x0D483E10612F327FC11965Fc82E90dC19b141641",StreamStorageRegistry:"0xe8e2660CeDf2a59C917a5ED05B72df4146b58399",StreamrConfig:"0x869e88dB146ECAF20dDf199a12684cD80c263c8f",SponsorshipOperatorContractOnlyJoinPolicy:"0xa1F3c94A682Cb43d26AcC40dA1Dc31f49e4dA466",SponsorshipMaxOperatorsJoinPolicy:"0x27448061420bAccAE8c84DDC3E7e2e8B2aE4977E",SponsorshipStakeWeightedAllocationPolicy:"0x1Dd16E748308E9f259f3D6097d00e1793BfBdcDB",SponsorshipDefaultLeavePolicy:"0xa953D590098A3d56304a12A8e929D63748D90AAC",SponsorshipVoteKickPolicy:"0xeF3F567D7328849c1130CBCBF8Cd9feB42eA5dB5",SponsorshipFactory:"0x820b2f9a15ed45F9802c59d0CC77C22C81755e45",OperatorDefaultDelegationPolicy:"0x8e449F0B1AFAD807135B5Ea829F41851d5DE1426",OperatorDefaultExchangeRatePolicy:"0xE8F511bB4888D16D81acab7ab1c05A356E37237f",OperatorDefaultUndelegationPolicy:"0x5c81fA1e79318386Dd82Ef059bCB194DbA87De45",OperatorFactory:"0x935734e66729b69260543Cf6e5EfeB42AC962183",Uniswap2Router:"0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff",UniswapAdapter:"0xAd54A57383EcA2D4f0D22337A96A7c4f6Bd51A13",Uniswap2AdapterForMarketplaceV3:"0x83C42F77c6dD09A1A93A7834be65b3bB891106bE"},blockExplorerUrl:"https://polygonscan.com",theGraphUrl:"https://gateway-arbitrum.network.thegraph.com/api/a971cec07440a9ec63cd806c06ccc990/subgraphs/id/EGWFdhhiWypDuz22Uy7b3F69E9MEkyfU9iAQMttkH5Rj",entryPoints:[{nodeId:"e5f87a7ee99b3c91e7b795b70f87ef8ba5497596",websocket:{host:"polygon-entrypoint-3.streamr.network",port:443,tls:!0}},{nodeId:"6f5b53812fd9cc07f225a0b3a6aa5b96672e852e",websocket:{host:"polygon-entrypoint-4.streamr.network",port:443,tls:!0}}]},polygonAmoy:{id:80002,name:"Polygon Amoy testnet",nativeCurrency:{symbol:"MATIC",name:"Amoy MATIC",decimals:18},rpcEndpoints:[{url:"https://polygon-amoy-bor-rpc.publicnode.com"},{url:"https://rpc-amoy.polygon.technology"}],contracts:{DATA:"0xf5e28a2E7BbedbE97c3782b17b102410E10d90f1",StreamRegistry:"0xE9C98bdE63248e58E9137Db8270D9675B9E34b93",ENSCacheV2:"0x6a81414936868fdcF4f077e2a0B24879e2871016",StorageNodeRegistry:"0x02fdF917f4e6Ae8F7F1bBDd28179d819E2b76820",StreamStorageRegistry:"0x0f3671A9A92416E1aD32750faCf2AD4FA1b66f78",StreamrConfig:"0x835bC97D2a61bbF5d05932C5105Ca34e1b815F94",SponsorshipOperatorContractOnlyJoinPolicy:"0x930Dcc2ca313ACf7177185C0D68462fDc699C7e0",SponsorshipMaxOperatorsJoinPolicy:"0xd640C2C5102953d122759826daa6Aec25eC98ca5",SponsorshipStakeWeightedAllocationPolicy:"0xaC80c738FCF8d259F07C82eAD68B75aF4DF82223",SponsorshipDefaultLeavePolicy:"0x16Ba0F2793Da54b67717c6bAD471624C6628F2aa",SponsorshipVoteKickPolicy:"0xA73aDbEC14be2D3628CeAD022243f080CB162955",SponsorshipFactory:"0xb194a68b166f2e3074B551393fA61490D19c69f8",OperatorDefaultDelegationPolicy:"0x78f29fF290148e83795393f1858DC540D8cB046b",OperatorDefaultExchangeRatePolicy:"0x48d25dd5731AD644613b67E4281C505Ef392Dd70",OperatorDefaultUndelegationPolicy:"0x7962155D5ea2fF949FCF300F221964d5ef9d1bad",OperatorFactory:"0xE02E8E9fF5ea6a58F34D00C0e4B091e066B9fA81",ProjectRegistryV1:"0xc5e1434d35c0c7291c7032Fd9C4096b4876C6823",ProjectStakingV1:"0x3A27A16770477EbcFb4B81cE462F4f12591767A0",MarketplaceV4:"0x6C8eaA8e0bF605469c15b6F9106387B4cEC99976",DataUnionFactory:"0x62d48EBcf518AF1eb4c647721a19B046810623c4",DataUnionTemplate:"0xACe6B50B1d1Fb06b4650eF4Adb094747C65Ab674",DataUnionFeeOracle:"0x1A20217419156E09D36fd380d3F429d03AD2Dc97"},theGraphUrl:"https://gateway.thegraph.com/api/dd2dd773d33a3b2f5028ddaa8e1874c1/subgraphs/id/3nVH84bDz3wFJ82UZxMD2WfpGyU2KzDnZdEdDQFsHAqp",blockExplorerUrl:"https://amoy.polygonscan.com",entryPoints:[{nodeId:"d48787fc36eaed43770ec84947ef81557b19ec98",websocket:{host:"amoy-entrypoint-1.streamr.network",port:443,tls:!0}},{nodeId:"24395826687b099fd735a730219ba750169c4f40",websocket:{host:"amoy-entrypoint-2.streamr.network",port:443,tls:!0}}]},peaq:{id:3338,name:"Peaq EVM chain",nativeCurrency:{symbol:"PEAQ",name:"PEAQ",decimals:18},rpcEndpoints:[{url:"https://peaq.api.onfinality.io/public"}],contracts:{DATA:"0xdCB1EcdD509c61De5C3B672fDD2335AC750142c9",StreamRegistry:"0xD0C720e99Bd39311614f292d8B0B4e351Bde157c",ENSCacheV2:"0x4A71d0FA9e3326E830048B1423d7010fB9343071",StorageNodeRegistry:"0xaCF9e8134047eDc671162D9404BF63a587435bAa",StreamStorageRegistry:"0xB36CF8ee4219a3Ac9FBC3865C35E9a99353c26db",StreamrConfig:"0xc81Fa3Cc3E81dF24D21bfc608f8FB06262Da4F8c",SponsorshipOperatorContractOnlyJoinPolicy:"0xF655955dc561356851e95a6D0febeB0BAc955Ab5",SponsorshipMaxOperatorsJoinPolicy:"0xE41439BF434F9CfBF0153f5231C205d4ae0C22e3",SponsorshipStakeWeightedAllocationPolicy:"0xC8E8efAF4CE7bCcFc87878631BC64A1FAe63dc5D",SponsorshipDefaultLeavePolicy:"0xDa579a9a55158Bc57389f1b05F553DEf38a121c1",SponsorshipVoteKickPolicy:"0xdc8d23092b93F9BB7416F45dEa36f55996f34867",SponsorshipFactory:"0xdaF0905e19C45b9Fea7E60D232061edF78E9F570",OperatorDefaultDelegationPolicy:"0xD3329a2FC8194f0F96749275FF5162f7f2F031F7",OperatorDefaultExchangeRatePolicy:"0xA3D82B569ab0dEF86935fCf4e7714626a608CF81",OperatorDefaultUndelegationPolicy:"0x3EF89eF888721446Cf373C5070399B8225C9E936",OperatorFactory:"0x6d201374D7c28EF1c3cc1b6FA300f06110B597A3",ProjectRegistryV1:"0xB14205AE3D7672B937B972EBdf2b986fB0B8CfaA",ProjectStakingV1:"0xd1cBD6b1Be710C41c01A9613802209843407b8b9",MarketplaceV4:"0x959684926448296ea72BD4B05593426A3cD3F0dF"},blockExplorerUrl:"https://peaq.subscan.io",theGraphUrl:"https://gateway.thegraph.com/api/5bcf7b0d11045c944600d4007737d457/subgraphs/id/CV3grB3fYpUzET1s75kXG2BaNyREK5uRA8SkjLTyXXh7",entryPoints:[{nodeId:"e5f87a7ee99b3c91e7b795b70f87ef8ba5497596",websocket:{host:"polygon-entrypoint-3.streamr.network",port:443,tls:!0}},{nodeId:"6f5b53812fd9cc07f225a0b3a6aa5b96672e852e",websocket:{host:"polygon-entrypoint-4.streamr.network",port:443,tls:!0}}]},iotex:{id:4689,name:"IoTeX",nativeCurrency:{symbol:"IOTX",name:"IOTX",decimals:18},rpcEndpoints:[{url:"https://babel-api.mainnet.iotex.one"}],contracts:{DATA:"0xD94be6fd546d4cE502CB1E870A58330Cc8869e9B",StreamRegistry:"0x080F34fec2bc33928999Ea9e39ADc798bEF3E0d6",ENSCacheV2:"0xAB072849dd3Cd648cb85c73d525a70A36523337d",StorageNodeRegistry:"0xb9e70Bd9833dd091f06edc8073aa86a76EdeF46D",StreamStorageRegistry:"0xF79c40Fbc432f1f8B8B017441B644e0ac7bccea2",StreamrConfig:"0x176B108E72ee49A01Bea1eDb32f7f296d2bb3db8",SponsorshipOperatorContractOnlyJoinPolicy:"0xace5b2A71A44efD9259983b5671d8ba802703dF7",SponsorshipMaxOperatorsJoinPolicy:"0x6956abe11F99e3983282f8B4fFb30015cC45Ae1D",SponsorshipStakeWeightedAllocationPolicy:"0x0Eb81BF75e585B227c01BBd1Ba5Ee0Ab6b1b55d5",SponsorshipDefaultLeavePolicy:"0xb9fe5430aC3eE3B1D26734C513f41Bf96B10C830",SponsorshipVoteKickPolicy:"0xc4a1ba0655FC6C34F9283e33682e57031fC060af",SponsorshipFactory:"0x7ac03730374E995E366F2a466be6aCC14E1DB1C4",OperatorDefaultDelegationPolicy:"0x5E0F361EC38cBE990baCB0D3008B5582DA4eAa2a",OperatorDefaultExchangeRatePolicy:"0x75e26741538825263954AC2a1Ad9d6eAb695FD47",OperatorDefaultUndelegationPolicy:"0x6D48ee54898e9B1f5FBe468ab85eA542dd82Ae6c",OperatorFactory:"0xD1Bc2A37405F88d4904844B7BF1BEadA7c0851c1",ProjectRegistryV1:"0xbb2a2CF40Ca86378983cfcACB7Aac1568237a692",MarketplaceV4:"0xe3F6750a5f9a6315cB11adc5CE980F7356C927C4",ProjectStakingV1:"0x0F91Edc1760e64e434Fb9CaF93a76b262E7015b3"},blockExplorerUrl:"https://iotexscan.io",theGraphUrl:"https://gateway.thegraph.com/api/4bddc6e1e1fe65a49bf8091785478835/subgraphs/id/CvGQcfBwWH1SvyxJDGjRRMa4YXQpxmpt369orMirZ3RH",entryPoints:[{nodeId:"e5f87a7ee99b3c91e7b795b70f87ef8ba5497596",websocket:{host:"polygon-entrypoint-3.streamr.network",port:443,tls:!0}},{nodeId:"6f5b53812fd9cc07f225a0b3a6aa5b96672e852e",websocket:{host:"polygon-entrypoint-4.streamr.network",port:443,tls:!0}}]},iotexTestnet:{id:4690,name:"IoTeX Testnet",nativeCurrency:{symbol:"IOTEX",name:"IOTEX",decimals:18},rpcEndpoints:[{url:"https://babel-api.testnet.iotex.io"}],contracts:{DATA:"0x5ABD469031d2B5f939808565EAB8562d7Cbaa939",StreamRegistry:"0xDC695780959aa5aEe9B28dfED7332032e3045210",ENSCacheV2:"0xDDf8FB60f8c3ffb1C20375A30f6D8CFB0C48Bd38",StorageNodeRegistry:"0xc0F9666fbF16B2ac5726697237BcdF79096e3FA7",StreamStorageRegistry:"0xd0C3A69762Bd920C1cAfBE91612a4600429f02f1",StreamrConfig:"0x6d201374D7c28EF1c3cc1b6FA300f06110B597A3",SponsorshipOperatorContractOnlyJoinPolicy:"0xAd24077505d3584F1AC8d78719F9d31F7Da0E264",SponsorshipMaxOperatorsJoinPolicy:"0x78d13aaBA657F448933Bb469E4E549Dee88cB78B",SponsorshipStakeWeightedAllocationPolicy:"0xB14205AE3D7672B937B972EBdf2b986fB0B8CfaA",SponsorshipDefaultLeavePolicy:"0xfC9C1886EAd9a757039Edbee16Bea0183344D2BA",SponsorshipVoteKickPolicy:"0xd1cBD6b1Be710C41c01A9613802209843407b8b9",SponsorshipFactory:"0x84c8d8f9760639e159350e5d2Bfaada99b670114",OperatorDefaultDelegationPolicy:"0x67352e3F7dBA907aF877020aE7E9450C0029C70c",OperatorDefaultExchangeRatePolicy:"0xE41439BF434F9CfBF0153f5231C205d4ae0C22e3",OperatorDefaultUndelegationPolicy:"0xF655955dc561356851e95a6D0febeB0BAc955Ab5",OperatorFactory:"0xdaF0905e19C45b9Fea7E60D232061edF78E9F570"},blockExplorerUrl:"https://testnet.iotexscan.io",entryPoints:[]}}),QO);Object.defineProperty(e,"config",{enumerable:!0,get:function(){return t.config}}),t.config}(JO)),JO),YO=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},XO=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},eD=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};function tD(e){return e.contracts.ethereumNetwork.chainId===ZO.config.dev2.id}const rD=e=>({staticNetwork:!0,batchStallTime:tD(e)?0:void 0,cacheTimeout:tD(e)?-1:void 0});e.RpcProviderSource=class{config;provider;subProviders;constructor(e){this.config=e}getProvider(){if(void 0===this.provider){const e=this.getSubProviders();this.provider=new vx(e,this.config.contracts.ethereumNetwork.chainId,{quorum:Math.min(this.config.contracts.rpcQuorum,this.config.contracts.rpcs.length),cacheTimeout:rD(this.config).cacheTimeout})}return this.provider}getSubProviders(){return this.subProviders??=this.config.contracts.rpcs.map((e=>{const t=new OS(e.url);t.retryFunc=async()=>!1,t.timeout=this.config._timeouts.jsonRpcTimeout;const r=rD(this.config);return new HO(t,this.config.contracts.ethereumNetwork.chainId,r)})),this.subProviders}},e.RpcProviderSource=YO([q(d.ContainerScoped),eD(0,U(cA)),XO("design:paramtypes",[Object])],e.RpcProviderSource);const nD=async(e,t)=>{const r=t.contracts.ethereumNetwork,n=r.overrides??{};if(r.highGasPriceStrategy&&void 0===r.overrides?.gasPrice){const t=await e.getProvider().getFeeData(),r=e=>null===e.gasPrice?void 0:e.gasPrice*BigInt(130)/100n;return{...n,gasPrice:r(t)}}return n};var iD=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o};let sD=class extends sE{};sD=iD([q(d.ContainerScoped)],sD);var oD=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},aD=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},cD=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let uD=class{config;constructor(e){this.config=e}createLogger(e){return new Bv(e,{id:this.config.id},this.config.logLevel)}};var lD,hD,dD,fD;uD=oD([q(d.ContainerScoped),cD(0,U(cA)),aD("design:paramtypes",[Object])],uD);var pD=function(){if(fD)return dD;fD=1;const e=function(){if(hD)return lD;hD=1;class e{constructor(e){this.value=e,this.next=void 0}}class t{constructor(){this.clear()}enqueue(t){const r=new e(t);this._head?(this._tail.next=r,this._tail=r):(this._head=r,this._tail=r),this._size++}dequeue(){const e=this._head;if(e)return this._head=this._head.next,this._size--,e.value}clear(){this._head=void 0,this._tail=void 0,this._size=0}get size(){return this._size}*[Symbol.iterator](){let e=this._head;for(;e;)yield e.value,e=e.next}}return lD=t}();return dD=t=>{if(!Number.isInteger(t)&&t!==1/0||!(t>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");const r=new e;let n=0;const i=async(e,t,...i)=>{n++;const s=(async()=>e(...i))();t(s);try{await s}catch{}n--,r.size>0&&r.dequeue()()},s=(e,...s)=>new Promise((o=>{((e,s,...o)=>{r.enqueue(i.bind(null,e,s,...o)),(async()=>{await Promise.resolve(),n<t&&r.size>0&&r.dequeue()()})()})(e,o,...s)}));return Object.defineProperties(s,{activeCount:{get:()=>n},pendingCount:{get:()=>r.size},clearQueue:{value:()=>{r.clear()}}}),s}}(),gD=n(pD);async function mD(e){return(await e).wait()}const yD=async(e,t,r)=>{try{return await e()}catch(e){const n=ju(["reason","code"].map((t=>void 0!==e[t]?`${t}=${e[t]}`:void 0)),void 0),i=new Error(`Error while ${r} contract call "${t}"${n.length>0?", "+n.join(", "):""}`);throw i.reason=e,i}},bD=(e,t,r,n)=>{const i=new Sl,s=gD(n),o={eventEmitter:i,getAddress:()=>e.getAddress(),on:(t,r)=>{e.on(t,r)},off:(t,r)=>{e.off(t,r)}},a=e.interface.fragments.filter((e=>J_.isFunction(e))).map((e=>e.name));return a.forEach((r=>{o[r]=((e,t,r,n,i)=>{const s=e[r],o=`${t}.${r}`,a=async(...e)=>{const t=await yD((()=>i((()=>(n.emit("onMethodExecute",o),s(...e))))),o,"executing");if((e=>void 0!==e.wait&&"function"==typeof e.wait)(t)){n.emit("onTransactionSubmit",o,t);const e=t.wait.bind(t);t.wait=async(t,i)=>{const s=await yD((()=>e(t,i)),r,"waiting transaction for");return n.emit("onTransactionConfirm",o,s),s}}return t};return a.estimateGas=(...e)=>s.estimateGas(...e),a})(e,t,r,i,s)})),((e,t)=>{const r=t.createLogger("contract");e.on("onMethodExecute",(e=>{r.debug("Execute method",{methodName:e})})),e.on("onTransactionSubmit",((e,t)=>{r.debug("Submit transaction",{method:e,tx:t.hash,to:t.to,nonce:t.nonce,gasLimit:t.gasLimit,gasPrice:t.gasPrice})})),e.on("onTransactionConfirm",((e,t)=>{r.debug("Received transaction confirmation",{method:e,tx:t?.hash,block:t?.blockNumber,confirmations:t?.confirmations,gasUsed:t?.gasUsed,events:t?.logs??[]})}))})(i,r),o},wD=e=>{const t=e.loggerFactory.createLogger("contract");((e,t,r,n)=>{const i=n.getObserver(),s=t=>n.emit(e,t);let o;i.on("addEventListener",(r=>{r===e&&void 0===o&&(o=t(s))})),i.on("removeEventListener",(t=>{t===e&&void 0!==o&&0===n.getListenerCount(e)&&(r(o),o=void 0)})),n.getListenerCount(e)>0&&(o=t(s))})(e.targetName,(r=>{const n=(n,i)=>{let s;try{s=e.transformation(n,i)}catch(r){return void t.error("Skip emit event",{eventName:e.targetName,reason:r?.message})}r(s)};return e.sourceEmitter.on({onEvent:n,...e.sourceDefinition}),n}),(t=>{e.sourceEmitter.off({onEvent:t,...e.sourceDefinition})}),e.targetEmitter)};var vD=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},ED=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},AD=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let SD=class{config;eventEmitter;loggerFactory;constructor(e,t,r){this.config=e,this.eventEmitter=t,this.loggerFactory=r}createReadContract(e,t,r,n){return bD(new JN(e,t,r),n,this.loggerFactory,this.config.contracts.maxConcurrentCalls)}createWriteContract(e,t,r,n){const i=bD(new JN(e,t,r),n,this.loggerFactory,999999);return i.eventEmitter.on("onTransactionConfirm",((e,t)=>{this.eventEmitter.emit("contractTransactionConfirmed",{methodName:e,receipt:t})})),i}createEventContract(e,t,r){return new JN(e,t,r)}};SD=vD([q(d.ContainerScoped),AD(0,U(cA)),ED("design:paramtypes",[Object,sD,uD])],SD);var kD=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},RD=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},CD=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let ID=class{nodeRegistryContract;nodeRegistryContractReadonly;contractFactory;rpcProviderSource;config;identity;constructor(e,t,r,n){this.contractFactory=e,this.rpcProviderSource=t,this.config=r,this.identity=n,this.nodeRegistryContractReadonly=this.contractFactory.createReadContract(nb(this.config.contracts.storageNodeRegistryChainAddress),SA.NodeRegistryABI,t.getProvider(),"storageNodeRegistry")}async connectToContract(){if(void 0===this.nodeRegistryContract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.nodeRegistryContract=this.contractFactory.createWriteContract(nb(this.config.contracts.storageNodeRegistryChainAddress),SA.NodeRegistryABI,e,"storageNodeRegistry")}}async setStorageNodeMetadata(e){await this.connectToContract();const t=await nD(this.rpcProviderSource,this.config);void 0!==e?await mD(this.nodeRegistryContract.createOrUpdateNodeSelf(JSON.stringify(e),t)):await mD(this.nodeRegistryContract.removeNodeSelf(t))}async getStorageNodeMetadata(e){const[t,r]=await this.nodeRegistryContractReadonly.getNode(e);if("0x0000000000000000000000000000000000000000"!==t)return JSON.parse(r);throw new uA("Node not found, id: "+e,"NODE_NOT_FOUND")}};var PD,TD,_D,ND,MD,xD,OD,DD,BD,LD,FD,UD,jD,qD,zD,KD,GD,VD,HD,$D,WD,JD,QD,ZD,YD,XD,eB,tB,rB,nB,iB,sB,oB,aB,cB,uB,lB,hB,dB,fB,pB,gB,mB,yB,bB,wB,vB,EB,AB,SB,kB,RB,CB,IB,PB,TB,_B,NB,MB,xB,OB,DB,BB,LB,FB,UB,jB,qB,zB,KB;function GB(){if(ND)return _D;ND=1;var e=Vc(),t=(TD||(TD=1,PD=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}),PD),r=Zc();return _D=function(n,i,s,o,a,c){var u=1&s,l=n.length,h=i.length;if(l!=h&&!(u&&h>l))return!1;var d=c.get(n),f=c.get(i);if(d&&f)return d==i&&f==n;var p=-1,g=!0,m=2&s?new e:void 0;for(c.set(n,i),c.set(i,n);++p<l;){var y=n[p],b=i[p];if(o)var w=u?o(b,y,p,i,n,c):o(y,b,p,n,i,c);if(void 0!==w){if(w)continue;g=!1;break}if(m){if(!t(i,(function(e,t){if(!r(m,t)&&(y===e||a(y,e,s,o,c)))return m.push(t)}))){g=!1;break}}else if(y!==b&&!a(y,b,s,o,c)){g=!1;break}}return c.delete(n),c.delete(i),g},_D}function VB(){if(DD)return OD;return DD=1,OD=function(e){var t=-1,r=Array(e.size);return e.forEach((function(e){r[++t]=e})),r},OD}function HB(){if(LD)return BD;LD=1;var e=Oe(),t=Ch(),r=Uc(),n=GB(),i=(xD||(xD=1,MD=function(e){var t=-1,r=Array(e.size);return e.forEach((function(e,n){r[++t]=[n,e]})),r}),MD),s=VB(),o=e?e.prototype:void 0,a=o?o.valueOf:void 0;return BD=function(e,o,c,u,l,h,d){switch(c){case"[object DataView]":if(e.byteLength!=o.byteLength||e.byteOffset!=o.byteOffset)return!1;e=e.buffer,o=o.buffer;case"[object ArrayBuffer]":return!(e.byteLength!=o.byteLength||!h(new t(e),new t(o)));case"[object Boolean]":case"[object Date]":case"[object Number]":return r(+e,+o);case"[object Error]":return e.name==o.name&&e.message==o.message;case"[object RegExp]":case"[object String]":return e==o+"";case"[object Map]":var f=i;case"[object Set]":var p=1&u;if(f||(f=s),e.size!=o.size&&!p)return!1;var g=d.get(e);if(g)return g==o;u|=2,d.set(e,o);var m=n(f(e),f(o),u,l,h,d);return d.delete(e),m;case"[object Symbol]":if(a)return a.call(e)==a.call(o)}return!1},BD}function $B(){if(UD)return FD;return UD=1,FD=function(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e},FD}function WB(){if(qD)return jD;qD=1;var e=$B(),t=qu();return jD=function(r,n,i){var s=n(r);return t(r)?s:e(s,i(r))},jD}function JB(){if(VD)return GD;return VD=1,GD=function(){return[]}}function QB(){if($D)return HD;$D=1;var e=(KD||(KD=1,zD=function(e,t){for(var r=-1,n=null==e?0:e.length,i=0,s=[];++r<n;){var o=e[r];t(o,r,e)&&(s[i++]=o)}return s}),zD),t=JB(),r=Object.prototype.propertyIsEnumerable,n=Object.getOwnPropertySymbols,i=n?function(t){return null==t?[]:(t=Object(t),e(n(t),(function(e){return r.call(t,e)})))}:t;return HD=i}function ZB(){if(JD)return WD;JD=1;var e=WB(),t=QB(),r=rA();return WD=function(n){return e(n,r,t)},WD}function YB(){if(nB)return rB;nB=1;var e=Bc()(xe(),"Set");return rB=e}function XB(){if(aB)return oB;aB=1;var e=function(){if(XD)return YD;XD=1;var e=Bc()(xe(),"DataView");return YD=e}(),t=zc(),r=function(){if(tB)return eB;tB=1;var e=Bc()(xe(),"Promise");return eB=e}(),n=YB(),i=function(){if(sB)return iB;sB=1;var e=Bc()(xe(),"WeakMap");return iB=e}(),s=De(),o=Dc(),a="[object Map]",c="[object Promise]",u="[object Set]",l="[object WeakMap]",h="[object DataView]",d=o(e),f=o(t),p=o(r),g=o(n),m=o(i),y=s;return(e&&y(new e(new ArrayBuffer(1)))!=h||t&&y(new t)!=a||r&&y(r.resolve())!=c||n&&y(new n)!=u||i&&y(new i)!=l)&&(y=function(e){var t=s(e),r="[object Object]"==t?e.constructor:void 0,n=r?o(r):"";if(n)switch(n){case d:return h;case f:return a;case p:return c;case g:return u;case m:return l}return t}),oB=y}function eL(){if(uB)return cB;uB=1;var e=Yl(),t=GB(),r=HB(),n=function(){if(ZD)return QD;ZD=1;var e=ZB(),t=Object.prototype.hasOwnProperty;return QD=function(r,n,i,s,o,a){var c=1&i,u=e(r),l=u.length;if(l!=e(n).length&&!c)return!1;for(var h=l;h--;){var d=u[h];if(!(c?d in n:t.call(n,d)))return!1}var f=a.get(r),p=a.get(n);if(f&&p)return f==n&&p==r;var g=!0;a.set(r,n),a.set(n,r);for(var m=c;++h<l;){var y=r[d=u[h]],b=n[d];if(s)var w=c?s(b,y,d,n,r,a):s(y,b,d,r,n,a);if(!(void 0===w?y===b||o(y,b,i,s,a):w)){g=!1;break}m||(m="constructor"==d)}if(g&&!m){var v=r.constructor,E=n.constructor;v==E||!("constructor"in r)||!("constructor"in n)||"function"==typeof v&&v instanceof v&&"function"==typeof E&&E instanceof E||(g=!1)}return a.delete(r),a.delete(n),g},QD}(),i=XB(),s=qu(),o=Kh(),a=Ad(),c="[object Arguments]",u="[object Array]",l="[object Object]",h=Object.prototype.hasOwnProperty;return cB=function(d,f,p,g,m,y){var b=s(d),w=s(f),v=b?u:i(d),E=w?u:i(f),A=(v=v==c?l:v)==l,S=(E=E==c?l:E)==l,k=v==E;if(k&&o(d)){if(!o(f))return!1;b=!0,A=!1}if(k&&!A)return y||(y=new e),b||a(d)?t(d,f,p,g,m,y):r(d,f,v,p,g,m,y);if(!(1&p)){var R=A&&h.call(d,"__wrapped__"),C=S&&h.call(f,"__wrapped__");if(R||C){var I=R?d.value():d,P=C?f.value():f;return y||(y=new e),m(I,P,p,g,y)}}return!!k&&(y||(y=new e),n(d,f,p,g,m,y))},cB}function tL(){if(hB)return lB;hB=1;var e=eL(),t=Be();return lB=function r(n,i,s,o,a){return n===i||(null==n||null==i||!t(n)&&!t(i)?n!=n&&i!=i:e(n,i,s,o,r,a))},lB}function rL(){if(gB)return pB;gB=1;var e=Ne();return pB=function(t){return t==t&&!e(t)}}function nL(){if(wB)return bB;return wB=1,bB=function(e,t){return function(r){return null!=r&&(r[e]===t&&(void 0!==t||e in Object(r)))}},bB}function iL(){if(EB)return vB;EB=1;var e=function(){if(fB)return dB;fB=1;var e=Yl(),t=tL();return dB=function(r,n,i,s){var o=i.length,a=o,c=!s;if(null==r)return!a;for(r=Object(r);o--;){var u=i[o];if(c&&u[2]?u[1]!==r[u[0]]:!(u[0]in r))return!1}for(;++o<a;){var l=(u=i[o])[0],h=r[l],d=u[1];if(c&&u[2]){if(void 0===h&&!(l in r))return!1}else{var f=new e;if(s)var p=s(h,d,l,r,n,f);if(!(void 0===p?t(d,h,3,s,f):p))return!1}}return!0},dB}(),t=function(){if(yB)return mB;yB=1;var e=rL(),t=rA();return mB=function(r){for(var n=t(r),i=n.length;i--;){var s=n[i],o=r[s];n[i]=[s,o,e(o)]}return n},mB}(),r=nL();return vB=function(n){var i=t(n);return 1==i.length&&i[0][2]?r(i[0][0],i[0][1]):function(t){return t===n||e(t,n,i)}},vB}function sL(){if(SB)return AB;SB=1;var e=Pl(),t=_l();return AB=function(r,n){for(var i=0,s=(n=e(n,r)).length;null!=r&&i<s;)r=r[t(n[i++])];return i&&i==s?r:void 0},AB}function oL(){if(NB)return _B;NB=1;var e=(IB||(IB=1,CB=function(e,t){return null!=e&&t in Object(e)}),CB),t=function(){if(TB)return PB;TB=1;var e=Pl(),t=Oh(),r=qu(),n=Tl(),i=iu(),s=_l();return PB=function(o,a,c){for(var u=-1,l=(a=e(a,o)).length,h=!1;++u<l;){var d=s(a[u]);if(!(h=null!=o&&c(o,d)))break;o=o[d]}return h||++u!=l?h:!!(l=null==o?0:o.length)&&i(l)&&n(d,l)&&(r(o)||t(o))},PB}();return _B=function(r,n){return null!=r&&t(r,n,e)},_B}function aL(){if(xB)return MB;xB=1;var e=tL(),t=function(){if(RB)return kB;RB=1;var e=sL();return kB=function(t,r,n){var i=null==t?void 0:e(t,r);return void 0===i?n:i},kB}(),r=oL(),n=Cl(),i=rL(),s=nL(),o=_l();return MB=function(a,c){return n(a)&&i(c)?s(o(a),c):function(n){var i=t(n,a);return void 0===i&&i===c?r(n,a):e(c,i,3)}},MB}function cL(){if(LB)return BB;LB=1;var e=Vu(),t=function(){if(DB)return OB;DB=1;var e=sL();return OB=function(t){return function(r){return e(r,t)}},OB}(),r=Cl(),n=_l();return BB=function(i){return r(i)?e(n(i)):t(i)},BB}function uL(){if(UB)return FB;UB=1;var e=iL(),t=aL(),r=Yc(),n=qu(),i=cL();return FB=function(s){return"function"==typeof s?s:null==s?r:"object"==typeof s?n(s)?t(s[0],s[1]):e(s):i(s)}}ID=kD([q(d.ContainerScoped),CD(2,U(cA)),CD(3,U(kA)),RD("design:paramtypes",[SD,e.RpcProviderSource,Object,RA])],ID);var lL,hL,dL,fL=function(){if(KB)return zB;KB=1;var e=uL(),t=function(){if(qB)return jB;qB=1;var e=Le(),t=Math.floor,r=Math.min;return jB=function(n,i,s,o){var a=0,c=null==n?0:n.length;if(0===c)return 0;for(var u=(i=s(i))!=i,l=null===i,h=e(i),d=void 0===i;a<c;){var f=t((a+c)/2),p=s(n[f]),g=void 0!==p,m=null===p,y=p==p,b=e(p);if(u)var w=o||y;else w=d?y&&(o||g):l?y&&g&&(o||!m):h?y&&g&&!m&&(o||!b):!m&&!b&&(o?p<=i:p<i);w?a=f+1:c=f}return r(c,4294967294)},jB}();return zB=function(r,n,i){return t(r,n,e(i,2))},zB}(),pL=n(fL),gL={exports:{}};var mL=function(){if(dL)return hL;dL=1;const e=function(){if(lL)return gL.exports;lL=1;var e=65536,t=4294967295,n=We().Buffer,i=r.crypto||r.msCrypto;return i&&i.getRandomValues?gL.exports=function(r,s){if(r>t)throw new RangeError("requested too many random bytes");var o=n.allocUnsafe(r);if(r>0)if(r>e)for(var a=0;a<r;a+=e)i.getRandomValues(o.slice(a,a+e));else i.getRandomValues(o);return"function"==typeof s?process.nextTick((function(){s(null,o)})):o}:gL.exports=function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")},gL.exports}(),{EventEmitter:t}=pt();function n(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0,n=e.length;r<n;++r)if(e[r]!==t[r])return!1;return!0}function i(e,t){if(!(t instanceof Uint8Array))throw new TypeError(e+" is not a Uint8Array")}class s extends t{constructor(t={}){super(),this.localNodeId=t.localNodeId||e(20),this.numberOfNodesPerKBucket=t.numberOfNodesPerKBucket||20,this.numberOfNodesToPing=t.numberOfNodesToPing||3,this.distance=t.distance||s.distance,this.arbiter=t.arbiter||s.arbiter,this.metadata=Object.assign({},t.metadata),i("option.localNodeId as parameter 1",this.localNodeId),this.root={contacts:[],dontSplit:!1,left:null,right:null}}static arbiter(e,t){return e.vectorClock>t.vectorClock?e:t}static distance(e,t){let r=0,n=0;const i=Math.min(e.length,t.length),s=Math.max(e.length,t.length);for(;n<i;++n)r=256*r+(e[n]^t[n]);for(;n<s;++n)r=256*r+255;return r}add(e){i("contact.id",(e||{}).id);let t=0,r=this.root;for(;null===r.contacts;)r=this._determineNode(r,e.id,t++);const n=this._indexOf(r,e.id);return n>=0?(this._update(r,n,e),this):r.contacts.length<this.numberOfNodesPerKBucket?(r.contacts.push(e),this.emit("added",e),this):r.dontSplit?(this.emit("ping",r.contacts.slice(0,this.numberOfNodesToPing),e),this):(this._split(r,t),this.add(e))}closest(e,t=1/0){if(i("id",e),!Number.isInteger(t)&&t!==1/0||t<=0)throw new TypeError("n is not positive number");let r=[];for(let n=[this.root],i=0;n.length>0&&r.length<t;){const t=n.pop();if(null===t.contacts){const r=this._determineNode(t,e,i++);n.push(t.left===r?t.right:t.left),n.push(r)}else r=r.concat(t.contacts)}return r.map((t=>[this.distance(t.id,e),t])).sort(((e,t)=>e[0]-t[0])).slice(0,t).map((e=>e[1]))}count(){let e=0;for(const t=[this.root];t.length>0;){const r=t.pop();null===r.contacts?t.push(r.right,r.left):e+=r.contacts.length}return e}_determineNode(e,t,r){const n=r>>3,i=r%8;if(t.length<=n&&0!==i)return e.left;return t[n]&1<<7-i?e.right:e.left}get(e){i("id",e);let t=0,r=this.root;for(;null===r.contacts;)r=this._determineNode(r,e,t++);const n=this._indexOf(r,e);return n>=0?r.contacts[n]:null}_indexOf(e,t){for(let r=0;r<e.contacts.length;++r)if(n(e.contacts[r].id,t))return r;return-1}remove(e){i("the id as parameter 1",e);let t=0,r=this.root;for(;null===r.contacts;)r=this._determineNode(r,e,t++);const n=this._indexOf(r,e);if(n>=0){const e=r.contacts.splice(n,1)[0];this.emit("removed",e)}return this}_split(e,t){e.left={contacts:[],dontSplit:!1,left:null,right:null},e.right={contacts:[],dontSplit:!1,left:null,right:null};for(const r of e.contacts)this._determineNode(e,r.id,t).contacts.push(r);e.contacts=null;const r=this._determineNode(e,this.localNodeId,t);(e.left===r?e.right:e.left).dontSplit=!0}toArray(){let e=[];for(const t=[this.root];t.length>0;){const r=t.pop();null===r.contacts?t.push(r.right,r.left):e=e.concat(r.contacts)}return e}*toIterable(){for(const e=[this.root];e.length>0;){const t=e.pop();null===t.contacts?e.push(t.right,t.left):yield*t.contacts}}_update(e,t,r){if(!n(e.contacts[t].id,r.id))throw new Error("wrong index for _update");const i=e.contacts[t],s=this.arbiter(i,r);s===i&&i!==r||(e.contacts.splice(t,1),e.contacts.push(s),this.emit("updated",i,s))}}return hL=s}(),yL=n(mL);function bL(e){let t=typeof e;if("object"==t){if(Array.isArray(e))return"array";if(null===e)return"null"}return t}function wL(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let vL="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),EL=[];for(let e=0;e<vL.length;e++)EL[vL[e].charCodeAt(0)]=e;var AL,SL;function kL(e,t){return Object.assign(Object.assign({},e),t)}function RL(){let e=0,t=0;for(let r=0;r<28;r+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<r,!(128&n))return this.assertBounds(),[e,t]}let r=this.buf[this.pos++];if(e|=(15&r)<<28,t=(112&r)>>4,!(128&r))return this.assertBounds(),[e,t];for(let r=3;r<=31;r+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<r,!(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function CL(e,t,r){for(let n=0;n<28;n+=7){const i=e>>>n,s=!(i>>>7==0&&0==t),o=255&(s?128|i:i);if(r.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,i=!!(t>>3);if(r.push(255&(i?128|n:n)),i){for(let e=3;e<31;e+=7){const n=t>>>e,i=!(n>>>7==0),s=255&(i?128|n:n);if(r.push(s),!i)return}r.push(t>>>31&1)}}EL["-".charCodeAt(0)]=vL.indexOf("+"),EL["_".charCodeAt(0)]=vL.indexOf("/"),function(e){e.symbol=Symbol.for("protobuf-ts/unknown"),e.onRead=(r,n,i,s,o)=>{(t(n)?n[e.symbol]:n[e.symbol]=[]).push({no:i,wireType:s,data:o})},e.onWrite=(t,r,n)=>{for(let{no:t,wireType:i,data:s}of e.list(r))n.tag(t,i).raw(s)},e.list=(r,n)=>{if(t(r)){let t=r[e.symbol];return n?t.filter((e=>e.no==n)):t}return[]},e.last=(t,r)=>e.list(t,r).slice(-1)[0];const t=t=>t&&Array.isArray(t[e.symbol])}(AL||(AL={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(SL||(SL={}));const IL=4294967296;function PL(e){let t="-"==e[0];t&&(e=e.slice(1));const r=1e6;let n=0,i=0;function s(t,s){const o=Number(e.slice(t,s));i*=r,n=n*r+o,n>=IL&&(i+=n/IL|0,n%=IL)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[t,n,i]}function TL(e,t){if(t>>>0<=2097151)return""+(IL*t+(e>>>0));let r=(e>>>24|t<<8)>>>0&16777215,n=t>>16&65535,i=(16777215&e)+6777216*r+6710656*n,s=r+8147497*n,o=2*n,a=1e7;function c(e,t){let r=e?String(e):"";return t?"0000000".slice(r.length)+r:r}return i>=a&&(s+=Math.floor(i/a),i%=a),s>=a&&(o+=Math.floor(s/a),s%=a),c(o,0)+c(s,o)+c(i,1)}function _L(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let r=0;r<9;r++)t.push(127&e|128),e>>=7;t.push(1)}}function NL(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let ML;function xL(e){if(!e)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}!function(){const e=new DataView(new ArrayBuffer(8)),t=void 0!==globalThis.BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64;ML=t?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:e}:void 0}();const OL=/^-?[0-9]+$/,DL=4294967296,BL=2147483648;class LL{constructor(e,t){this.lo=0|e,this.hi=0|t}isZero(){return 0==this.lo&&0==this.hi}toNumber(){let e=this.hi*DL+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class FL extends LL{static from(e){if(ML)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=ML.C(e);case"number":if(0===e)return this.ZERO;e=ML.C(e);case"bigint":if(!e)return this.ZERO;if(e<ML.UMIN)throw new Error("signed value for ulong");if(e>ML.UMAX)throw new Error("ulong too large");return ML.V.setBigUint64(0,e,!0),new FL(ML.V.getInt32(0,!0),ML.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!OL.test(e))throw new Error("string is no integer");let[t,r,n]=PL(e);if(t)throw new Error("signed value for ulong");return new FL(r,n);case"number":if(0==e)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new FL(e,e/DL)}throw new Error("unknown value "+typeof e)}toString(){return ML?this.toBigInt().toString():TL(this.lo,this.hi)}toBigInt(){return xL(ML),ML.V.setInt32(0,this.lo,!0),ML.V.setInt32(4,this.hi,!0),ML.V.getBigUint64(0,!0)}}FL.ZERO=new FL(0,0);class UL extends LL{static from(e){if(ML)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=ML.C(e);case"number":if(0===e)return this.ZERO;e=ML.C(e);case"bigint":if(!e)return this.ZERO;if(e<ML.MIN)throw new Error("signed long too small");if(e>ML.MAX)throw new Error("signed long too large");return ML.V.setBigInt64(0,e,!0),new UL(ML.V.getInt32(0,!0),ML.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!OL.test(e))throw new Error("string is no integer");let[t,r,n]=PL(e);if(t){if(n>BL||n==BL&&0!=r)throw new Error("signed long too small")}else if(n>=BL)throw new Error("signed long too large");let i=new UL(r,n);return t?i.negate():i;case"number":if(0==e)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new UL(e,e/DL):new UL(-e,-e/DL).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return!!(this.hi&BL)}negate(){let e=~this.hi,t=this.lo;return t?t=1+~t:e+=1,new UL(t,e)}toString(){if(ML)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+TL(e.lo,e.hi)}return TL(this.lo,this.hi)}toBigInt(){return xL(ML),ML.V.setInt32(0,this.lo,!0),ML.V.setInt32(4,this.hi,!0),ML.V.getBigInt64(0,!0)}}UL.ZERO=new UL(0,0);const jL={readUnknownField:!0,readerFactory:e=>new qL(e)};class qL{constructor(e,t){this.varint64=RL,this.uint32=NL,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),t=e>>>3,r=7&e;if(t<=0||r<0||r>5)throw new Error("illegal tag: field no "+t+" wire type "+r);return[t,r]}skip(e){let t=this.pos;switch(e){case SL.Varint:for(;128&this.buf[this.pos++];);break;case SL.Bit64:this.pos+=4;case SL.Bit32:this.pos+=4;break;case SL.LengthDelimited:let t=this.uint32();this.pos+=t;break;case SL.StartGroup:let r;for(;(r=this.tag()[1])!==SL.EndGroup;)this.skip(r);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return new UL(...this.varint64())}uint64(){return new FL(...this.varint64())}sint64(){let[e,t]=this.varint64(),r=-(1&e);return e=(e>>>1|(1&t)<<31)^r,t=t>>>1^r,new UL(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new FL(this.sfixed32(),this.sfixed32())}sfixed64(){return new UL(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function zL(e,t){if(!e)throw new Error(t)}function KL(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function GL(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function VL(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const HL={writeUnknownFields:!0,writerFactory:()=>new $L};class $L{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),r=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],r),r+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(GL(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return KL(e),_L(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){VL(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){GL(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){KL(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return KL(e),_L(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=UL.from(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),r=new DataView(t.buffer),n=FL.from(e);return r.setInt32(0,n.lo,!0),r.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=UL.from(e);return CL(t.lo,t.hi,this.buf),this}sint64(e){let t=UL.from(e),r=t.hi>>31;return CL(t.lo<<1^r,(t.hi<<1|t.lo>>>31)^r,this.buf),this}uint64(e){let t=FL.from(e);return CL(t.lo,t.hi,this.buf),this}}const WL={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},JL={ignoreUnknownFields:!1};function QL(e){return e?Object.assign(Object.assign({},WL),e):WL}function ZL(e,t){var r,n;let i=Object.assign(Object.assign({},e),t);return i.typeRegistry=[...null!==(r=null==e?void 0:e.typeRegistry)&&void 0!==r?r:[],...null!==(n=null==t?void 0:t.typeRegistry)&&void 0!==n?n:[]],i}const YL=Symbol.for("protobuf-ts/message-type");function XL(e){let t=!1;const r=[];for(let n=0;n<e.length;n++){let i=e.charAt(n);"_"==i?t=!0:/\d/.test(i)?(r.push(i),t=!0):t?(r.push(i.toUpperCase()),t=!1):0==n?r.push(i.toLowerCase()):r.push(i)}return r.join("")}var eF,tF,rF;function nF(e){var t,r,n,i;return e.localName=null!==(t=e.localName)&&void 0!==t?t:XL(e.name),e.jsonName=null!==(r=e.jsonName)&&void 0!==r?r:XL(e.name),e.repeat=null!==(n=e.repeat)&&void 0!==n?n:rF.NO,e.opt=null!==(i=e.opt)&&void 0!==i?i:!e.repeat&&(!e.oneof&&"message"==e.kind),e}function iF(e){if("object"!=typeof e||null===e||!e.hasOwnProperty("oneofKind"))return!1;switch(typeof e.oneofKind){case"string":return void 0!==e[e.oneofKind]&&2==Object.keys(e).length;case"undefined":return 1==Object.keys(e).length;default:return!1}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(eF||(eF={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING",e[e.NUMBER=2]="NUMBER"}(tF||(tF={})),function(e){e[e.NO=0]="NO",e[e.PACKED=1]="PACKED",e[e.UNPACKED=2]="UNPACKED"}(rF||(rF={}));class sF{constructor(e){var t;this.fields=null!==(t=e.fields)&&void 0!==t?t:[]}prepare(){if(this.data)return;const e=[],t=[],r=[];for(let n of this.fields)if(n.oneof)r.includes(n.oneof)||(r.push(n.oneof),e.push(n.oneof),t.push(n.oneof));else switch(t.push(n.localName),n.kind){case"scalar":case"enum":n.opt&&!n.repeat||e.push(n.localName);break;case"message":n.repeat&&e.push(n.localName);break;case"map":e.push(n.localName)}this.data={req:e,known:t,oneofs:Object.values(r)}}is(e,t,r=!1){if(t<0)return!0;if(null==e||"object"!=typeof e)return!1;this.prepare();let n=Object.keys(e),i=this.data;if(n.length<i.req.length||i.req.some((e=>!n.includes(e))))return!1;if(!r&&n.some((e=>!i.known.includes(e))))return!1;if(t<1)return!0;for(const n of i.oneofs){const i=e[n];if(!iF(i))return!1;if(void 0===i.oneofKind)continue;const s=this.fields.find((e=>e.localName===i.oneofKind));if(!s)return!1;if(!this.field(i[i.oneofKind],s,r,t))return!1}for(const n of this.fields)if(void 0===n.oneof&&!this.field(e[n.localName],n,r,t))return!1;return!0}field(e,t,r,n){let i=t.repeat;switch(t.kind){case"scalar":return void 0===e?t.opt:i?this.scalars(e,t.T,n,t.L):this.scalar(e,t.T,t.L);case"enum":return void 0===e?t.opt:i?this.scalars(e,eF.INT32,n):this.scalar(e,eF.INT32);case"message":return void 0===e||(i?this.messages(e,t.T(),r,n):this.message(e,t.T(),r,n));case"map":if("object"!=typeof e||null===e)return!1;if(n<2)return!0;if(!this.mapKeys(e,t.K,n))return!1;switch(t.V.kind){case"scalar":return this.scalars(Object.values(e),t.V.T,n,t.V.L);case"enum":return this.scalars(Object.values(e),eF.INT32,n);case"message":return this.messages(Object.values(e),t.V.T(),r,n)}}return!0}message(e,t,r,n){return r?t.isAssignable(e,n):t.is(e,n)}messages(e,t,r,n){if(!Array.isArray(e))return!1;if(n<2)return!0;if(r){for(let r=0;r<e.length&&r<n;r++)if(!t.isAssignable(e[r],n-1))return!1}else for(let r=0;r<e.length&&r<n;r++)if(!t.is(e[r],n-1))return!1;return!0}scalar(e,t,r){let n=typeof e;switch(t){case eF.UINT64:case eF.FIXED64:case eF.INT64:case eF.SFIXED64:case eF.SINT64:switch(r){case tF.BIGINT:return"bigint"==n;case tF.NUMBER:return"number"==n&&!isNaN(e);default:return"string"==n}case eF.BOOL:return"boolean"==n;case eF.STRING:return"string"==n;case eF.BYTES:return e instanceof Uint8Array;case eF.DOUBLE:case eF.FLOAT:return"number"==n&&!isNaN(e);default:return"number"==n&&Number.isInteger(e)}}scalars(e,t,r,n){if(!Array.isArray(e))return!1;if(r<2)return!0;if(Array.isArray(e))for(let i=0;i<e.length&&i<r;i++)if(!this.scalar(e[i],t,n))return!1;return!0}mapKeys(e,t,r){let n=Object.keys(e);switch(t){case eF.INT32:case eF.FIXED32:case eF.SFIXED32:case eF.SINT32:case eF.UINT32:return this.scalars(n.slice(0,r).map((e=>parseInt(e))),t,r);case eF.BOOL:return this.scalars(n.slice(0,r).map((e=>"true"==e||"false"!=e&&e)),t,r);default:return this.scalars(n,t,r,tF.STRING)}}}function oF(e,t){switch(t){case tF.BIGINT:return e.toBigInt();case tF.NUMBER:return e.toNumber();default:return e.toString()}}class aF{constructor(e){this.info=e}prepare(){var e;if(void 0===this.fMap){this.fMap={};const t=null!==(e=this.info.fields)&&void 0!==e?e:[];for(const e of t)this.fMap[e.name]=e,this.fMap[e.jsonName]=e,this.fMap[e.localName]=e}}assert(e,t,r){if(!e){let e=bL(r);throw"number"!=e&&"boolean"!=e||(e=r.toString()),new Error(`Cannot parse JSON ${e} for ${this.info.typeName}#${t}`)}}read(e,t,r){this.prepare();const n=[];for(const[i,s]of Object.entries(e)){const e=this.fMap[i];if(!e){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${i}`);continue}const o=e.localName;let a;if(e.oneof){if(null===s&&("enum"!==e.kind||"google.protobuf.NullValue"!==e.T()[0]))continue;if(n.includes(e.oneof))throw new Error(`Multiple members of the oneof group "${e.oneof}" of ${this.info.typeName} are present in JSON.`);n.push(e.oneof),a=t[e.oneof]={oneofKind:o}}else a=t;if("map"==e.kind){if(null===s)continue;this.assert(wL(s),e.name,s);const t=a[o];for(const[n,i]of Object.entries(s)){let s;switch(this.assert(null!==i,e.name+" map value",null),e.V.kind){case"message":s=e.V.T().internalJsonRead(i,r);break;case"enum":if(s=this.enum(e.V.T(),i,e.name,r.ignoreUnknownFields),!1===s)continue;break;case"scalar":s=this.scalar(i,e.V.T,e.V.L,e.name)}this.assert(void 0!==s,e.name+" map value",i);let o=n;e.K==eF.BOOL&&(o="true"==o||"false"!=o&&o),o=this.scalar(o,e.K,tF.STRING,e.name).toString(),t[o]=s}}else if(e.repeat){if(null===s)continue;this.assert(Array.isArray(s),e.name,s);const t=a[o];for(const n of s){let i;switch(this.assert(null!==n,e.name,null),e.kind){case"message":i=e.T().internalJsonRead(n,r);break;case"enum":if(i=this.enum(e.T(),n,e.name,r.ignoreUnknownFields),!1===i)continue;break;case"scalar":i=this.scalar(n,e.T,e.L,e.name)}this.assert(void 0!==i,e.name,s),t.push(i)}}else switch(e.kind){case"message":if(null===s&&"google.protobuf.Value"!=e.T().typeName){this.assert(void 0===e.oneof,e.name+" (oneof member)",null);continue}a[o]=e.T().internalJsonRead(s,r,a[o]);break;case"enum":if(null===s)continue;let t=this.enum(e.T(),s,e.name,r.ignoreUnknownFields);if(!1===t)continue;a[o]=t;break;case"scalar":if(null===s)continue;a[o]=this.scalar(s,e.T,e.L,e.name)}}}enum(e,t,r,n){if("google.protobuf.NullValue"==e[0]&&zL(null===t||"NULL_VALUE"===t,`Unable to parse field ${this.info.typeName}#${r}, enum ${e[0]} only accepts null.`),null===t)return 0;switch(typeof t){case"number":return zL(Number.isInteger(t),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${t}.`),t;case"string":let i=t;e[2]&&t.substring(0,e[2].length)===e[2]&&(i=t.substring(e[2].length));let s=e[1][i];return(void 0!==s||!n)&&(zL("number"==typeof s,`Unable to parse field ${this.info.typeName}#${r}, enum ${e[0]} has no value for "${t}".`),s)}zL(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof t}".`)}scalar(e,t,r,n){let i;try{switch(t){case eF.DOUBLE:case eF.FLOAT:if(null===e)return 0;if("NaN"===e)return Number.NaN;if("Infinity"===e)return Number.POSITIVE_INFINITY;if("-Infinity"===e)return Number.NEGATIVE_INFINITY;if(""===e){i="empty string";break}if("string"==typeof e&&e.trim().length!==e.length){i="extra whitespace";break}if("string"!=typeof e&&"number"!=typeof e)break;let n=Number(e);if(Number.isNaN(n)){i="not a number";break}if(!Number.isFinite(n)){i="too large or small";break}return t==eF.FLOAT&&VL(n),n;case eF.INT32:case eF.FIXED32:case eF.SFIXED32:case eF.SINT32:case eF.UINT32:if(null===e)return 0;let s;if("number"==typeof e?s=e:""===e?i="empty string":"string"==typeof e&&(e.trim().length!==e.length?i="extra whitespace":s=Number(e)),void 0===s)break;return t==eF.UINT32?GL(s):KL(s),s;case eF.INT64:case eF.SFIXED64:case eF.SINT64:if(null===e)return oF(UL.ZERO,r);if("number"!=typeof e&&"string"!=typeof e)break;return oF(UL.from(e),r);case eF.FIXED64:case eF.UINT64:if(null===e)return oF(FL.ZERO,r);if("number"!=typeof e&&"string"!=typeof e)break;return oF(FL.from(e),r);case eF.BOOL:if(null===e)return!1;if("boolean"!=typeof e)break;return e;case eF.STRING:if(null===e)return"";if("string"!=typeof e){i="extra whitespace";break}try{encodeURIComponent(e)}catch(i){i="invalid UTF8";break}return e;case eF.BYTES:if(null===e||""===e)return new Uint8Array(0);if("string"!=typeof e)break;return function(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let r,n=new Uint8Array(t),i=0,s=0,o=0;for(let t=0;t<e.length;t++){if(r=EL[e.charCodeAt(t)],void 0===r)switch(e[t]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=r,s=1;break;case 1:n[i++]=o<<2|(48&r)>>4,o=r,s=2;break;case 2:n[i++]=(15&o)<<4|(60&r)>>2,o=r,s=3;break;case 3:n[i++]=(3&o)<<6|r,s=0}}if(1==s)throw Error("invalid base64 string.");return n.subarray(0,i)}(e)}}catch(e){i=e.message}this.assert(!1,n+(i?" - "+i:""),e)}}class cF{constructor(e){var t;this.fields=null!==(t=e.fields)&&void 0!==t?t:[]}write(e,t){const r={},n=e;for(const e of this.fields){if(!e.oneof){let i=this.field(e,n[e.localName],t);void 0!==i&&(r[t.useProtoFieldName?e.name:e.jsonName]=i);continue}const i=n[e.oneof];if(i.oneofKind!==e.localName)continue;const s="scalar"==e.kind||"enum"==e.kind?Object.assign(Object.assign({},t),{emitDefaultValues:!0}):t;let o=this.field(e,i[e.localName],s);zL(void 0!==o),r[t.useProtoFieldName?e.name:e.jsonName]=o}return r}field(e,t,r){let n;if("map"==e.kind){zL("object"==typeof t&&null!==t);const i={};switch(e.V.kind){case"scalar":for(const[r,n]of Object.entries(t)){const t=this.scalar(e.V.T,n,e.name,!1,!0);zL(void 0!==t),i[r.toString()]=t}break;case"message":const n=e.V.T();for(const[s,o]of Object.entries(t)){const t=this.message(n,o,e.name,r);zL(void 0!==t),i[s.toString()]=t}break;case"enum":const s=e.V.T();for(const[n,o]of Object.entries(t)){zL(void 0===o||"number"==typeof o);const t=this.enum(s,o,e.name,!1,!0,r.enumAsInteger);zL(void 0!==t),i[n.toString()]=t}}(r.emitDefaultValues||Object.keys(i).length>0)&&(n=i)}else if(e.repeat){zL(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let r=0;r<t.length;r++){const n=this.scalar(e.T,t[r],e.name,e.opt,!0);zL(void 0!==n),i.push(n)}break;case"enum":const n=e.T();for(let s=0;s<t.length;s++){zL(void 0===t[s]||"number"==typeof t[s]);const o=this.enum(n,t[s],e.name,e.opt,!0,r.enumAsInteger);zL(void 0!==o),i.push(o)}break;case"message":const s=e.T();for(let n=0;n<t.length;n++){const o=this.message(s,t[n],e.name,r);zL(void 0!==o),i.push(o)}}(r.emitDefaultValues||i.length>0||r.emitDefaultValues)&&(n=i)}else switch(e.kind){case"scalar":n=this.scalar(e.T,t,e.name,e.opt,r.emitDefaultValues);break;case"enum":n=this.enum(e.T(),t,e.name,e.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":n=this.message(e.T(),t,e.name,r)}return n}enum(e,t,r,n,i,s){if("google.protobuf.NullValue"==e[0])return i||n?null:void 0;if(void 0!==t){if(0!==t||i||n)return zL("number"==typeof t),zL(Number.isInteger(t)),s||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}else zL(n)}message(e,t,r,n){return void 0===t?n.emitDefaultValues?null:void 0:e.internalJsonWrite(t,n)}scalar(e,t,r,n,i){if(void 0===t)return void zL(n);const s=i||n;switch(e){case eF.INT32:case eF.SFIXED32:case eF.SINT32:return 0===t?s?0:void 0:(KL(t),t);case eF.FIXED32:case eF.UINT32:return 0===t?s?0:void 0:(GL(t),t);case eF.FLOAT:VL(t);case eF.DOUBLE:return 0===t?s?0:void 0:(zL("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case eF.STRING:return""===t?s?"":void 0:(zL("string"==typeof t),t);case eF.BOOL:return!1===t?!s&&void 0:(zL("boolean"==typeof t),t);case eF.UINT64:case eF.FIXED64:zL("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let e=FL.from(t);if(e.isZero()&&!s)return;return e.toString();case eF.INT64:case eF.SFIXED64:case eF.SINT64:zL("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let r=UL.from(t);if(r.isZero()&&!s)return;return r.toString();case eF.BYTES:return zL(t instanceof Uint8Array),t.byteLength?function(e){let t,r="",n=0,i=0;for(let s=0;s<e.length;s++)switch(t=e[s],n){case 0:r+=vL[t>>2],i=(3&t)<<4,n=1;break;case 1:r+=vL[i|t>>4],i=(15&t)<<2,n=2;break;case 2:r+=vL[i|t>>6],r+=vL[63&t],n=0}return n&&(r+=vL[i],r+="=",1==n&&(r+="=")),r}(t):s?"":void 0}}}function uF(e,t=tF.STRING){switch(e){case eF.BOOL:return!1;case eF.UINT64:case eF.FIXED64:return oF(FL.ZERO,t);case eF.INT64:case eF.SFIXED64:case eF.SINT64:return oF(UL.ZERO,t);case eF.DOUBLE:case eF.FLOAT:return 0;case eF.BYTES:return new Uint8Array(0);case eF.STRING:return"";default:return 0}}class lF{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const t=null!==(e=this.info.fields)&&void 0!==e?e:[];this.fieldNoToField=new Map(t.map((e=>[e.no,e])))}}read(e,t,r,n){this.prepare();const i=void 0===n?e.len:e.pos+n;for(;e.pos<i;){const[n,i]=e.tag(),s=this.fieldNoToField.get(n);if(!s){let s=r.readUnknownField;if("throw"==s)throw new Error(`Unknown field ${n} (wire type ${i}) for ${this.info.typeName}`);let o=e.skip(i);!1!==s&&(!0===s?AL.onRead:s)(this.info.typeName,t,n,i,o);continue}let o=t,a=s.repeat,c=s.localName;switch(s.oneof&&(o=o[s.oneof],o.oneofKind!==c&&(o=t[s.oneof]={oneofKind:c})),s.kind){case"scalar":case"enum":let t="enum"==s.kind?eF.INT32:s.T,n="scalar"==s.kind?s.L:void 0;if(a){let r=o[c];if(i==SL.LengthDelimited&&t!=eF.STRING&&t!=eF.BYTES){let i=e.uint32()+e.pos;for(;e.pos<i;)r.push(this.scalar(e,t,n))}else r.push(this.scalar(e,t,n))}else o[c]=this.scalar(e,t,n);break;case"message":if(a){let t=o[c],n=s.T().internalBinaryRead(e,e.uint32(),r);t.push(n)}else o[c]=s.T().internalBinaryRead(e,e.uint32(),r,o[c]);break;case"map":let[u,l]=this.mapEntry(s,e,r);o[c][u]=l}}}mapEntry(e,t,r){let n,i,s=t.uint32(),o=t.pos+s;for(;t.pos<o;){let[s,o]=t.tag();switch(s){case 1:n=e.K==eF.BOOL?t.bool().toString():this.scalar(t,e.K,tF.STRING);break;case 2:switch(e.V.kind){case"scalar":i=this.scalar(t,e.V.T,e.V.L);break;case"enum":i=t.int32();break;case"message":i=e.V.T().internalBinaryRead(t,t.uint32(),r)}break;default:throw new Error(`Unknown field ${s} (wire type ${o}) in map entry for ${this.info.typeName}#${e.name}`)}}if(void 0===n){let t=uF(e.K);n=e.K==eF.BOOL?t.toString():t}if(void 0===i)switch(e.V.kind){case"scalar":i=uF(e.V.T,e.V.L);break;case"enum":i=0;break;case"message":i=e.V.T().create()}return[n,i]}scalar(e,t,r){switch(t){case eF.INT32:return e.int32();case eF.STRING:return e.string();case eF.BOOL:return e.bool();case eF.DOUBLE:return e.double();case eF.FLOAT:return e.float();case eF.INT64:return oF(e.int64(),r);case eF.UINT64:return oF(e.uint64(),r);case eF.FIXED64:return oF(e.fixed64(),r);case eF.FIXED32:return e.fixed32();case eF.BYTES:return e.bytes();case eF.UINT32:return e.uint32();case eF.SFIXED32:return e.sfixed32();case eF.SFIXED64:return oF(e.sfixed64(),r);case eF.SINT32:return e.sint32();case eF.SINT64:return oF(e.sint64(),r)}}}class hF{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort(((e,t)=>e.no-t.no))}}write(e,t,r){this.prepare();for(const n of this.fields){let i,s,o=n.repeat,a=n.localName;if(n.oneof){const t=e[n.oneof];if(t.oneofKind!==a)continue;i=t[a],s=!0}else i=e[a],s=!1;switch(n.kind){case"scalar":case"enum":let e="enum"==n.kind?eF.INT32:n.T;if(o)if(zL(Array.isArray(i)),o==rF.PACKED)this.packed(t,e,n.no,i);else for(const r of i)this.scalar(t,e,n.no,r,!0);else void 0===i?zL(n.opt):this.scalar(t,e,n.no,i,s||n.opt);break;case"message":if(o){zL(Array.isArray(i));for(const e of i)this.message(t,r,n.T(),n.no,e)}else this.message(t,r,n.T(),n.no,i);break;case"map":zL("object"==typeof i&&null!==i);for(const[e,s]of Object.entries(i))this.mapEntry(t,r,n,e,s)}}let n=r.writeUnknownFields;!1!==n&&(!0===n?AL.onWrite:n)(this.info.typeName,e,t)}mapEntry(e,t,r,n,i){e.tag(r.no,SL.LengthDelimited),e.fork();let s=n;switch(r.K){case eF.INT32:case eF.FIXED32:case eF.UINT32:case eF.SFIXED32:case eF.SINT32:s=Number.parseInt(n);break;case eF.BOOL:zL("true"==n||"false"==n),s="true"==n}switch(this.scalar(e,r.K,1,s,!0),r.V.kind){case"scalar":this.scalar(e,r.V.T,2,i,!0);break;case"enum":this.scalar(e,eF.INT32,2,i,!0);break;case"message":this.message(e,t,r.V.T(),2,i)}e.join()}message(e,t,r,n,i){void 0!==i&&(r.internalBinaryWrite(i,e.tag(n,SL.LengthDelimited).fork(),t),e.join())}scalar(e,t,r,n,i){let[s,o,a]=this.scalarInfo(t,n);a&&!i||(e.tag(r,s),e[o](n))}packed(e,t,r,n){if(!n.length)return;zL(t!==eF.BYTES&&t!==eF.STRING),e.tag(r,SL.LengthDelimited),e.fork();let[,i]=this.scalarInfo(t);for(let t=0;t<n.length;t++)e[i](n[t]);e.join()}scalarInfo(e,t){let r,n=SL.Varint,i=void 0===t,s=0===t;switch(e){case eF.INT32:r="int32";break;case eF.STRING:s=i||!t.length,n=SL.LengthDelimited,r="string";break;case eF.BOOL:s=!1===t,r="bool";break;case eF.UINT32:r="uint32";break;case eF.DOUBLE:n=SL.Bit64,r="double";break;case eF.FLOAT:n=SL.Bit32,r="float";break;case eF.INT64:s=i||UL.from(t).isZero(),r="int64";break;case eF.UINT64:s=i||FL.from(t).isZero(),r="uint64";break;case eF.FIXED64:s=i||FL.from(t).isZero(),n=SL.Bit64,r="fixed64";break;case eF.BYTES:s=i||!t.byteLength,n=SL.LengthDelimited,r="bytes";break;case eF.FIXED32:n=SL.Bit32,r="fixed32";break;case eF.SFIXED32:n=SL.Bit32,r="sfixed32";break;case eF.SFIXED64:s=i||UL.from(t).isZero(),n=SL.Bit64,r="sfixed64";break;case eF.SINT32:r="sint32";break;case eF.SINT64:s=i||UL.from(t).isZero(),r="sint64"}return[n,r,i||s]}}function dF(e,t,r){let n,i,s=r;for(let r of e.fields){let e=r.localName;if(r.oneof){const o=s[r.oneof];if(null==(null==o?void 0:o.oneofKind))continue;if(n=o[e],i=t[r.oneof],i.oneofKind=o.oneofKind,null==n){delete i[e];continue}}else if(n=s[e],i=t,null==n)continue;switch(r.repeat&&(i[e].length=n.length),r.kind){case"scalar":case"enum":if(r.repeat)for(let t=0;t<n.length;t++)i[e][t]=n[t];else i[e]=n;break;case"message":let t=r.T();if(r.repeat)for(let r=0;r<n.length;r++)i[e][r]=t.create(n[r]);else void 0===i[e]?i[e]=t.create(n):t.mergePartial(i[e],n);break;case"map":switch(r.V.kind){case"scalar":case"enum":Object.assign(i[e],n);break;case"message":let t=r.V.T();for(let r of Object.keys(n))i[e][r]=t.create(n[r])}}}}const fF=Object.values;function pF(e,t,r){if(t===r)return!0;if(e!==eF.BYTES)return!1;let n=t,i=r;if(n.length!==i.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!=i[e])return!1;return!0}function gF(e,t,r){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!pF(e,t[n],r[n]))return!1;return!0}function mF(e,t,r){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!e.equals(t[n],r[n]))return!1;return!0}const yF=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),bF=yF[YL]={};class wF{constructor(e,t,r){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(nF),this.options=null!=r?r:{},bF.value=this,this.messagePrototype=Object.create(null,yF),this.refTypeCheck=new sF(this),this.refJsonReader=new aF(this),this.refJsonWriter=new cF(this),this.refBinReader=new lF(this),this.refBinWriter=new hF(this)}create(e){let t=function(e){const t=e.messagePrototype?Object.create(e.messagePrototype):Object.defineProperty({},YL,{value:e});for(let r of e.fields){let e=r.localName;if(!r.opt)if(r.oneof)t[r.oneof]={oneofKind:void 0};else if(r.repeat)t[e]=[];else switch(r.kind){case"scalar":t[e]=uF(r.T,r.L);break;case"enum":t[e]=0;break;case"map":t[e]={}}}return t}(this);return void 0!==e&&dF(this,t,e),t}clone(e){let t=this.create();return dF(this,t,e),t}equals(e,t){return function(e,t,r){if(t===r)return!0;if(!t||!r)return!1;for(let n of e.fields){let e=n.localName,i=n.oneof?t[n.oneof][e]:t[e],s=n.oneof?r[n.oneof][e]:r[e];switch(n.kind){case"enum":case"scalar":let e="enum"==n.kind?eF.INT32:n.T;if(!(n.repeat?gF(e,i,s):pF(e,i,s)))return!1;break;case"map":if(!("message"==n.V.kind?mF(n.V.T(),fF(i),fF(s)):gF("enum"==n.V.kind?eF.INT32:n.V.T,fF(i),fF(s))))return!1;break;case"message":let t=n.T();if(!(n.repeat?mF(t,i,s):t.equals(i,s)))return!1}}return!0}(this,e,t)}is(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!1)}isAssignable(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!0)}mergePartial(e,t){dF(this,e,t)}fromBinary(e,t){let r=function(e){return e?Object.assign(Object.assign({},jL),e):jL}(t);return this.internalBinaryRead(r.readerFactory(e),e.byteLength,r)}fromJson(e,t){return this.internalJsonRead(e,function(e){return e?Object.assign(Object.assign({},JL),e):JL}(t))}fromJsonString(e,t){let r=JSON.parse(e);return this.fromJson(r,t)}toJson(e,t){return this.internalJsonWrite(e,QL(t))}toJsonString(e,t){var r;let n=this.toJson(e,t);return JSON.stringify(n,null,null!==(r=null==t?void 0:t.prettySpaces)&&void 0!==r?r:0)}toBinary(e,t){let r=function(e){return e?Object.assign(Object.assign({},HL),e):HL}(t);return this.internalBinaryWrite(e,r.writerFactory(),r).finish()}internalJsonRead(e,t,r){if(null!==e&&"object"==typeof e&&!Array.isArray(e)){let n=null!=r?r:this.create();return this.refJsonReader.read(e,n,t),n}throw new Error(`Unable to parse message ${this.typeName} from JSON ${bL(e)}.`)}internalJsonWrite(e,t){return this.refJsonWriter.write(e,t)}internalBinaryWrite(e,t,r){return this.refBinWriter.write(e,t,r),t}internalBinaryRead(e,t,r,n){let i=null!=n?n:this.create();return this.refBinReader.read(e,i,r,t),i}}class vF{constructor(e,t,r){this.typeName=e,this.methods=t.map((e=>function(e,t){var r,n,i;let s=e;return s.service=t,s.localName=null!==(r=s.localName)&&void 0!==r?r:XL(s.name),s.serverStreaming=!!s.serverStreaming,s.clientStreaming=!!s.clientStreaming,s.options=null!==(n=s.options)&&void 0!==n?n:{},s.idempotency=null!==(i=s.idempotency)&&void 0!==i?i:void 0,s}(e,this))),this.options=null!=r?r:{}}}class EF extends Error{constructor(e,t="UNKNOWN",r){super(e),this.name="RpcError",Object.setPrototypeOf(this,new.target.prototype),this.code=t,this.meta=null!=r?r:{}}toString(){const e=[this.name+": "+this.message];this.code&&(e.push(""),e.push("Code: "+this.code)),this.serviceName&&this.methodName&&e.push("Method: "+this.serviceName+"/"+this.methodName);let t=Object.entries(this.meta);if(t.length){e.push(""),e.push("Meta:");for(let[r,n]of t)e.push(` ${r}: ${n}`)}return e.join("\n")}}function AF(e,t){if(!e)return;let r=t;for(let[t,n]of Object.entries(e))n instanceof Date?r[t]=new Date(n.getTime()):Array.isArray(n)?r[t]=n.concat():r[t]=n}var SF;!function(e){e[e.PENDING=0]="PENDING",e[e.REJECTED=1]="REJECTED",e[e.RESOLVED=2]="RESOLVED"}(SF||(SF={}));class kF{constructor(e=!0){this._state=SF.PENDING,this._promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t})),e&&this._promise.catch((e=>{}))}get state(){return this._state}get promise(){return this._promise}resolve(e){if(this.state!==SF.PENDING)throw new Error(`cannot resolve ${SF[this.state].toLowerCase()}`);this._resolve(e),this._state=SF.RESOLVED}reject(e){if(this.state!==SF.PENDING)throw new Error(`cannot reject ${SF[this.state].toLowerCase()}`);this._reject(e),this._state=SF.REJECTED}resolvePending(e){this._state===SF.PENDING&&this.resolve(e)}rejectPending(e){this._state===SF.PENDING&&this.reject(e)}}var RF=window&&window.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))};class CF{constructor(e,t,r,n,i,s,o){this.method=e,this.requestHeaders=t,this.request=r,this.headers=n,this.response=i,this.status=s,this.trailers=o}then(e,t){return this.promiseFinished().then((t=>e?Promise.resolve(e(t)):t),(e=>t?Promise.resolve(t(e)):Promise.reject(e)))}promiseFinished(){return RF(this,void 0,void 0,(function*(){let[e,t,r,n]=yield Promise.all([this.headers,this.response,this.status,this.trailers]);return{method:this.method,requestHeaders:this.requestHeaders,request:this.request,headers:e,response:t,status:r,trailers:n}}))}}function IF(e,t,r,n,i){var s;{let e=(e,r,n)=>t.unary(e,r,n);for(const t of(null!==(s=n.interceptors)&&void 0!==s?s:[]).filter((e=>e.interceptUnary)).reverse()){const r=e;e=(e,n,i)=>t.interceptUnary(r,e,n,i)}return e(r,i,n)}}const PF=[];for(let e=0;e<256;++e)PF.push((e+256).toString(16).slice(1));let TF;const _F=new Uint8Array(16);var NF,MF={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function xF(e,t,r){if(MF.randomUUID&&!e)return MF.randomUUID();const n=(e=e||{}).random??e.rng?.()??function(){if(!TF){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");TF=crypto.getRandomValues.bind(crypto)}return TF(_F)}();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=15&n[6]|64,n[8]=63&n[8]|128,function(e,t=0){return(PF[e[t+0]]+PF[e[t+1]]+PF[e[t+2]]+PF[e[t+3]]+"-"+PF[e[t+4]]+PF[e[t+5]]+"-"+PF[e[t+6]]+PF[e[t+7]]+"-"+PF[e[t+8]]+PF[e[t+9]]+"-"+PF[e[t+10]]+PF[e[t+11]]+PF[e[t+12]]+PF[e[t+13]]+PF[e[t+14]]+PF[e[t+15]]).toLowerCase()}(n)}!function(e){e.RPC_TIMEOUT="RPC_TIMEOUT",e.RPC_REQUEST="RPC_REQUEST",e.RPC_SERVER_ERROR="RPC_SERVER_ERROR",e.RPC_CLIENT_ERROR="RPC_CLIENT_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNKNOWN_RPC_METHOD="UNKNOWN_RPC_METHOD",e.FAILED_TO_PARSE="FAILED_TO_PARSE",e.FAILED_TO_SERIALIZE="FAILED_TO_SERIALIZE",e.DISCONNECTED="DISCONNECTED"}(NF||(NF={}));let OF=class extends Error{code;originalError;constructor(e,t,r){super(t),this.code=e,this.originalError=r}};class DF extends OF{constructor(e,t){super(NF.RPC_TIMEOUT,e,t)}}class BF extends OF{constructor(e,t){super(NF.RPC_REQUEST,e,t)}}class LF extends OF{errorClassName;errorCode;constructor(e,t,r){super(NF.RPC_SERVER_ERROR,e),this.errorClassName=t,this.errorCode=r}}class FF extends OF{constructor(e,t){super(NF.NOT_IMPLEMENTED,e,t)}}let UF=class extends OF{constructor(e,t){super(NF.UNKNOWN_RPC_METHOD,e,t)}};class jF extends OF{constructor(e,t){super(NF.FAILED_TO_PARSE,e,t)}}var qF=Object.freeze({__proto__:null,Disconnected:class extends OF{constructor(e,t){super(NF.DISCONNECTED,e,t)}},get ErrorCode(){return NF},FailedToParse:jF,FailedToSerialize:class extends OF{constructor(e,t){super(NF.FAILED_TO_SERIALIZE,e,t)}},NotImplemented:FF,RpcClientError:class extends OF{constructor(e,t){super(NF.RPC_CLIENT_ERROR,e,t)}},RpcRequest:BF,RpcServerError:LF,RpcTimeout:DF,UnknownRpcMethod:UF});const zF=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}},KF=new Bv("ClientTransport");class GF extends Sl{static objectCount=0;objectId;defaultOptions;constructor(e=5e3){super(),this.objectId=GF.objectCount++,this.defaultOptions={timeout:e,clientId:this.objectId}}mergeOptions(e){return function(e,t){if(!t)return e;let r={};AF(e,r),AF(t,r);for(let n of Object.keys(t)){let i=t[n];switch(n){case"jsonOptions":r.jsonOptions=ZL(e.jsonOptions,r.jsonOptions);break;case"binaryOptions":r.binaryOptions=kL(e.binaryOptions,r.binaryOptions);break;case"meta":r.meta={},AF(e.meta,r.meta),AF(t.meta,r.meta);break;case"interceptors":r.interceptors=e.interceptors?e.interceptors.concat(i):i.concat()}}return r}(this.defaultOptions,e)}static createRequestHeaders(e,t){return{method:e.localName,request:"request",notification:t?"notification":void 0}}unary(e,t,r){if(!r?.isProtoRpc)throw new Error("ProtoRpc ClientTransport can only be used with ProtoRpcClients. Please convert your protobuf-ts generated client to a ProtoRpcClient by calling toProtoRpcclient(yourClient).");const n=zF.pack(t,e.I),i={header:GF.createRequestHeaders(e,r.notification),body:n,requestId:xF()},s=new kF,o=new kF,a=new kF,c=new kF,u=new CF(e,{},t,s.promise,o.promise,a.promise,c.promise),l={message:o,header:s,trailer:c,status:a,messageParser:t=>e.O.fromBinary(t)};return KF.trace(`New rpc ${r.notification?"notification":"request"}, ${i.requestId}`),this.emit("rpcRequest",i,r,l),u}clientStreaming(e){const t=new EF("Client streaming is not supported by DhtTransport");throw t.methodName=e.name,t.serviceName=e.service.typeName,t}duplex(e){const t=new EF("Duplex streaming is not supported by DhtTransport");throw t.methodName=e.name,t.serviceName=e.service.typeName,t}serverStreaming(e){const t=new EF("Server streaming is not supported by DhtTransport");throw t.methodName=e.name,t.serviceName=e.service.typeName,t}stop(){this.removeAllListeners()}}const VF=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var HF;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(HF||(HF={}));new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>zF},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",HF]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};function $F(e,t){const r=new Promise(((r,n)=>{const i=setTimeout((()=>{n(new DF("Timed out in "+e+"ms."))}),e);t.finally((()=>clearTimeout(i))).catch((()=>null))}));return Promise.race([t,r])}new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>VF}])}};class WF{method=void 0;headers=void 0;deadline=void 0;trailers=void 0;status=void 0;sendResponseHeaders(e){throw new FF("Method not implemented.")}cancelled=void 0;onCancel(e){throw new FF("Method not implemented.")}notification}var JF=UF;const QF=e=>({timeout:e.timeout??1e3}),ZF=new Bv("ServerRegistry");function YF(e){try{return e()}catch(e){throw new jF("Could not parse binary to JSON-object",e)}}class XF{methods=new Map;notifications=new Map;getImplementation(e,t){if(!e?.header?.method)throw new JF('Header "method" missing from RPC message');if(!t.has(e.header.method))throw new JF(`RPC Method ${e.header.method} is not provided`);return t.get(e.header.method)}async handleRequest(e,t){ZF.trace(`Server processing RPC call ${e.requestId}`);const r=this.getImplementation(e,this.methods),n=r.options.timeout;return await $F(n,r.fn(e.body,t??new WF))}async handleNotification(e,t){ZF.trace(`Server processing RPC notification ${e.requestId}`);const r=this.getImplementation(e,this.notifications),n=r.options.timeout;await $F(n,r.fn(e.body,t??new WF))}registerRpcMethod(e,t,r,n,i={}){const s={fn:async(r,i)=>{const s=YF((()=>zF.unpack(r,e))),o=await n(s,i);return zF.pack(o,t)},options:QF(i)};this.methods.set(r,s)}registerRpcNotification(e,t,r,n={}){const i={fn:async(t,n)=>{const i=YF((()=>zF.unpack(t,e)));await r(i,n)},options:QF(n)};this.notifications.set(t,i)}}var eU;!function(e){e.OK="OK",e.STOPPED="STOPPED",e.DEADLINE_EXCEEDED="DEADLINE_EXCEEDED",e.SERVER_ERROR="SERVER_ERROR"}(eU||(eU={}));class tU{deferredPromises;callContext;timeoutRef;constructor(e,t,r){this.deferredPromises=e,this.callContext=t,r&&(this.timeoutRef=setTimeout((()=>{const e=new DF("Rpc request timed out",new Error);this.rejectDeferredPromises(e,eU.DEADLINE_EXCEEDED),r.onTimeout()}),r.timeout))}resolveRequest(e){this.timeoutRef&&clearTimeout(this.timeoutRef),this.resolveDeferredPromises(e)}resolveNotification(){this.timeoutRef&&clearTimeout(this.timeoutRef),this.deferredPromises.message.state===SF.PENDING&&(this.deferredPromises.message.resolve({}),this.deferredPromises.header.resolve({}),this.deferredPromises.status.resolve({code:eU.OK,detail:""}),this.deferredPromises.trailer.resolve({}))}rejectRequest(e,t){this.timeoutRef&&clearTimeout(this.timeoutRef),this.rejectDeferredPromises(e,t)}resolveDeferredPromises(e){if(this.deferredPromises.message.state===SF.PENDING)try{const t=this.deferredPromises.messageParser(e.body.value);this.deferredPromises.message.resolve(t),this.deferredPromises.header.resolve({}),this.deferredPromises.status.resolve({code:eU.OK,detail:""}),this.deferredPromises.trailer.resolve({})}catch(e){rU.debug("Could not parse response, received message is likely ");const t=new jF("Failed to parse received response, network protocol version likely is likely incompatible",e);this.rejectDeferredPromises(t,eU.SERVER_ERROR)}}rejectDeferredPromises(e,t){this.deferredPromises.message.state===SF.PENDING&&(this.deferredPromises.message.reject(e),this.deferredPromises.header.reject(e),this.deferredPromises.status.reject({code:t,detail:e.message}),this.deferredPromises.trailer.reject(e))}fulfillsPredicate(e){return e(this)}getCallContext(){return this.callContext}}const rU=new Bv("RpcCommunicator");class nU{stopped=!1;rpcClientTransport;rpcServerRegistry;ongoingRequests;rpcRequestTimeout;outgoingMessageListener;constructor(e){this.rpcRequestTimeout=e?.rpcRequestTimeout??5e3,this.rpcClientTransport=new GF(this.rpcRequestTimeout),this.rpcServerRegistry=new XF,this.ongoingRequests=new Map,this.rpcClientTransport.on("rpcRequest",((e,t,r)=>{this.onOutgoingMessage(e,t,r)}))}async handleIncomingMessage(e,t){if(!this.stopped)return this.onIncomingMessage(e,t)}registerRpcMethod(e,t,r,n,i={}){this.rpcServerRegistry.registerRpcMethod(e,t,r,n,i)}registerRpcNotification(e,t,r,n={}){this.rpcServerRegistry.registerRpcNotification(e,t,r,n)}getRpcClientTransport(){return this.rpcClientTransport}stop(){this.stopped=!0,this.ongoingRequests.forEach((e=>{e.rejectRequest(new Error("stopped"),eU.STOPPED)})),this.ongoingRequests.clear(),this.rpcClientTransport.stop()}onOutgoingMessage(e,t,r){if(this.stopped){if(r){new tU(r,t).rejectRequest(new Error("stopped"),eU.STOPPED)}return}const n=this.rpcClientTransport.mergeOptions(t);if(!r||t&&t.notification||this.registerRequest(e.requestId,r,t,n.timeout),rU.trace(`onOutGoingMessage, messageId: ${e.requestId}`),this.outgoingMessageListener)this.outgoingMessageListener(e,e.requestId,t).catch((n=>{if(r)if(this.ongoingRequests.has(e.requestId))this.handleClientError(e.requestId,n);else{new tU(r,t).rejectRequest(n,eU.SERVER_ERROR)}})).then((()=>{if(r&&!this.ongoingRequests.has(e.requestId)){new tU(r,t).resolveNotification()}}));else if(r&&!this.ongoingRequests.has(e.requestId)){new tU(r,t).resolveNotification()}}async onIncomingMessage(e,t){rU.trace(`onIncomingMessage, requestId: ${e.requestId}`),e.header.response&&this.ongoingRequests.has(e.requestId)?void 0!==e.errorType?this.rejectOngoingRequest(e):this.resolveOngoingRequest(e):e.header.request&&e.header.method&&(e.header.notification?await this.handleNotification(e,t):await this.handleRequest(e,t))}async handleRequest(e,t){if(this.stopped)return;let r;try{const n=await this.rpcServerRegistry.handleRequest(e,t);r=this.createResponseRpcMessage({request:e,body:n})}catch(t){const n={request:e};t.code===NF.UNKNOWN_RPC_METHOD?n.errorType=HF.UNKNOWN_RPC_METHOD:t.code===NF.RPC_TIMEOUT?n.errorType=HF.SERVER_TIMEOUT:(n.errorType=HF.SERVER_ERROR,t.className&&(n.errorClassName=t.className),t.code&&(n.errorCode=t.code),t.message&&(n.errorMessage=t.message)),r=this.createResponseRpcMessage(n)}this.onOutgoingMessage(r,t,void 0)}async handleNotification(e,t){if(!this.stopped)try{await this.rpcServerRegistry.handleNotification(e,t)}catch(e){rU.debug("error",{err:e})}}registerRequest(e,t,r,n=this.rpcRequestTimeout){if(this.stopped)return;const i=new tU(t,r,{timeout:n,onTimeout:()=>this.ongoingRequests.delete(e)});this.ongoingRequests.set(e,i)}resolveOngoingRequest(e){if(this.stopped)return;this.ongoingRequests.get(e.requestId).resolveRequest(e),this.ongoingRequests.delete(e.requestId)}rejectOngoingRequest(e){if(this.stopped)return;const t=this.ongoingRequests.get(e.requestId);let r;r=e.errorType===HF.SERVER_TIMEOUT?new DF("Server timed out on request"):e.errorType===HF.UNKNOWN_RPC_METHOD?new UF(`Server does not implement method ${e.header.method}`):e.errorType===HF.SERVER_ERROR?new LF(e.errorMessage,e.errorClassName,e.errorCode):new BF("Unknown RPC Error"),t.rejectRequest(r,eU.SERVER_ERROR),this.ongoingRequests.delete(e.requestId)}handleClientError(e,t){if(this.stopped)return;const r=this.ongoingRequests.get(e);r&&(r.rejectRequest(t,eU.SERVER_ERROR),this.ongoingRequests.delete(e))}setOutgoingMessageListener(e){this.outgoingMessageListener=e}getRequestIds(e){return Array.from(this.ongoingRequests.entries()).filter((([t,r])=>r.fulfillsPredicate(e))).map((([e])=>e))}createResponseRpcMessage({request:e,body:t,errorType:r,errorClassName:n,errorCode:i,errorMessage:s}){return{body:t,header:{response:"response",method:e.header.method},requestId:e.requestId,errorType:r,errorClassName:n,errorCode:i,errorMessage:s}}}function iU(e){const t={};Object.assign(t,e);return e.methods.forEach((r=>{r.O.typeName===VF.typeName?t[r.name]=(...t)=>(async(e,t,r)=>{r.length<2?r.push({}):r[1]??={},r[1].isProtoRpc=!0,r[1].notification=!0,await t[e].apply(t,r)})(r.name,e,t):t[r.name]=(...t)=>((e,t,r)=>(r.length<2?r.push({}):r[1]??={},r[1].isProtoRpc=!0,t[e].apply(t,r)))(r.name,e,t).response})),t}var sU,oU={exports:{}},aU=oU.exports;var cU=(sU||(sU=1,function(e){!function(t){const r="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp(`^${r}\\.${r}\\.${r}\\.${r}$`,"i"),threeOctet:new RegExp(`^${r}\\.${r}\\.${r}$`,"i"),twoOctet:new RegExp(`^${r}\\.${r}$`,"i"),longValue:new RegExp(`^${r}$`,"i")},i=new RegExp("^0[0-7]+$","i"),s=new RegExp("^0x[a-f0-9]+$","i"),o="%[0-9a-z]{1,}",a="(?:[0-9a-f]+::?)+",c={zoneIndex:new RegExp(o,"i"),native:new RegExp(`^(::)?(${a})?([0-9a-f]+)?(::)?(${o})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${r}\\.${r}\\.${r}\\.${r}(${o})?)$`,"i"),transitional:new RegExp(`^((?:${a})|(?:::)(?:${a})?)${r}\\.${r}\\.${r}\\.${r}(${o})?$`,"i")};function u(e,t){if(e.indexOf("::")!==e.lastIndexOf("::"))return null;let r,n,i=0,s=-1,o=(e.match(c.zoneIndex)||[])[0];for(o&&(o=o.substring(1),e=e.replace(/%.+$/,""));(s=e.indexOf(":",s+1))>=0;)i++;if("::"===e.substr(0,2)&&i--,"::"===e.substr(-2,2)&&i--,i>t)return null;for(n=t-i,r=":";n--;)r+="0:";return":"===(e=e.replace("::",r))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){const t=e.split(":"),r=[];for(let e=0;e<t.length;e++)r.push(parseInt(t[e],16));return r}(),zoneId:o}}function l(e,t,r,n){if(e.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let i,s=0;for(;n>0;){if(i=r-n,i<0&&(i=0),e[s]>>i!=t[s]>>i)return!1;n-=r,s+=1}return!0}function h(e){if(s.test(e))return parseInt(e,16);if("0"===e[0]&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw new Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function d(e,t){for(;e.length<t;)e=`0${e}`;return e}const f={};f.IPv4=function(){function e(e){if(4!==e.length)throw new Error("ipaddr: ipv4 octet count should be 4");let t,r;for(t=0;t<e.length;t++)if(r=e[t],!(0<=r&&r<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=e}return e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,18,0,0]),15],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]],as112:[[new e([192,175,48,0]),24],[new e([192,31,196,0]),24]],amt:[[new e([192,52,193,0]),24]]},e.prototype.kind=function(){return"ipv4"},e.prototype.match=function(e,t){let r;if(void 0===t&&(r=e,e=r[0],t=r[1]),"ipv4"!==e.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return l(this.octets,e.octets,8,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1;const r={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0};let n,i,s;for(n=3;n>=0;n-=1){if(i=this.octets[n],!(i in r))return null;if(s=r[i],t&&0!==s)return null;8!==s&&(t=!0),e+=s}return 32-e},e.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return f.IPv6.parse(`::ffff:${this.toString()}`)},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(".")},e}(),f.IPv4.broadcastAddressFromCIDR=function(e){try{const t=this.parseCIDR(e),r=t[0].toByteArray(),n=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[];let s=0;for(;s<4;)i.push(parseInt(r[s],10)|255^parseInt(n[s],10)),s++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.isIPv4=function(e){return null!==this.parser(e)},f.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(e){return!1}},f.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch(e){return!1}},f.IPv4.isValidFourPartDecimal=function(e){return!(!f.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},f.IPv4.networkAddressFromCIDR=function(e){let t,r,n,i,s;try{for(t=this.parseCIDR(e),n=t[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.parse=function(e){const t=this.parser(e);if(null===t)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(t)},f.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){const e=parseInt(t[2]);if(e>=0&&e<=32){const r=[this.parse(t[1]),e];return Object.defineProperty(r,"toString",{value:function(){return this.join("/")}}),r}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},f.IPv4.parser=function(e){let t,r,i;if(t=e.match(n.fourOctet))return function(){const e=t.slice(1,6),n=[];for(let t=0;t<e.length;t++)r=e[t],n.push(h(r));return n}();if(t=e.match(n.longValue)){if(i=h(t[1]),i>4294967295||i<0)throw new Error("ipaddr: address outside defined range");return function(){const e=[];let t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e}().reverse()}return(t=e.match(n.twoOctet))?function(){const e=t.slice(1,4),r=[];if(i=h(e[1]),i>16777215||i<0)throw new Error("ipaddr: address outside defined range");return r.push(h(e[0])),r.push(i>>16&255),r.push(i>>8&255),r.push(255&i),r}():(t=e.match(n.threeOctet))?function(){const e=t.slice(1,5),r=[];if(i=h(e[2]),i>65535||i<0)throw new Error("ipaddr: address outside defined range");return r.push(h(e[0])),r.push(h(e[1])),r.push(i>>8&255),r.push(255&i),r}():null},f.IPv4.subnetMaskFromPrefixLength=function(e){if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");const t=[0,0,0,0];let r=0;const n=Math.floor(e/8);for(;r<n;)t[r]=255,r++;return n<4&&(t[n]=Math.pow(2,e%8)-1<<8-e%8),new this(t)},f.IPv6=function(){function e(e,t){let r,n;if(16===e.length)for(this.parts=[],r=0;r<=14;r+=2)this.parts.push(e[r]<<8|e[r+1]);else{if(8!==e.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=e}for(r=0;r<this.parts.length;r++)if(n=this.parts[r],!(0<=n&&n<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],discard:[new e([256,0,0,0,0,0,0,0]),64],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],benchmarking:[new e([8193,2,0,0,0,0,0,0]),48],amt:[new e([8193,3,0,0,0,0,0,0]),32],as112v6:[[new e([8193,4,274,0,0,0,0,0]),48],[new e([9760,79,32768,0,0,0,0,0]),48]],deprecated:[new e([8193,16,0,0,0,0,0,0]),28],orchid2:[new e([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new e([8193,48,0,0,0,0,0,0]),28],reserved:[[new e([8193,0,0,0,0,0,0,0]),23],[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},e.prototype.kind=function(){return"ipv6"},e.prototype.match=function(e,t){let r;if(void 0===t&&(r=e,e=r[0],t=r[1]),"ipv6"!==e.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return l(this.parts,e.parts,16,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1;const r={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0};let n,i;for(let s=7;s>=0;s-=1){if(n=this.parts[s],!(n in r))return null;if(i=r[n],t&&0!==i)return null;16!==i&&(t=!0),e+=i}return 128-e},e.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e;const t=[],r=this.parts;for(let n=0;n<r.length;n++)e=r[n],t.push(e>>8),t.push(255&e);return t},e.prototype.toFixedLengthString=function(){const e=function(){const e=[];for(let t=0;t<this.parts.length;t++)e.push(d(this.parts[t].toString(16),4));return e}.call(this).join(":");let t="";return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");const e=this.parts.slice(-2),t=e[0],r=e[1];return new f.IPv4([t>>8,255&t,r>>8,255&r])},e.prototype.toNormalizedString=function(){const e=function(){const e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}.call(this).join(":");let t="";return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toRFC5952String=function(){const e=/((^|:)(0(:|$)){2,})/g,t=this.toNormalizedString();let r,n=0,i=-1;for(;r=e.exec(t);)r[0].length>i&&(n=r.index,i=r[0].length);return i<0?t:`${t.substring(0,n)}::${t.substring(n+i)}`},e.prototype.toString=function(){return this.toRFC5952String()},e}(),f.IPv6.broadcastAddressFromCIDR=function(e){try{const t=this.parseCIDR(e),r=t[0].toByteArray(),n=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[];let s=0;for(;s<16;)i.push(parseInt(r[s],10)|255^parseInt(n[s],10)),s++;return new this(i)}catch(e){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},f.IPv6.isIPv6=function(e){return null!==this.parser(e)},f.IPv6.isValid=function(e){if("string"==typeof e&&-1===e.indexOf(":"))return!1;try{const t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch(e){return!1}},f.IPv6.isValidCIDR=function(e){if("string"==typeof e&&-1===e.indexOf(":"))return!1;try{return this.parseCIDR(e),!0}catch(e){return!1}},f.IPv6.networkAddressFromCIDR=function(e){let t,r,n,i,s;try{for(t=this.parseCIDR(e),n=t[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<16;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},f.IPv6.parse=function(e){const t=this.parser(e);if(null===t.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(t.parts,t.zoneId)},f.IPv6.parseCIDR=function(e){let t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]),t>=0&&t<=128))return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},f.IPv6.parser=function(e){let t,r,n,i,s,o;if(n=e.match(c.deprecatedTransitional))return this.parser(`::ffff:${n[1]}`);if(c.native.test(e))return u(e,8);if((n=e.match(c.transitional))&&(o=n[6]||"",t=n[1],n[1].endsWith("::")||(t=t.slice(0,-1)),t=u(t+o,6),t.parts)){for(s=[parseInt(n[2]),parseInt(n[3]),parseInt(n[4]),parseInt(n[5])],r=0;r<s.length;r++)if(i=s[r],!(0<=i&&i<=255))return null;return t.parts.push(s[0]<<8|s[1]),t.parts.push(s[2]<<8|s[3]),{parts:t.parts,zoneId:t.zoneId}}return null},f.IPv6.subnetMaskFromPrefixLength=function(e){if((e=parseInt(e))<0||e>128)throw new Error("ipaddr: invalid IPv6 prefix length");const t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let r=0;const n=Math.floor(e/8);for(;r<n;)t[r]=255,r++;return n<16&&(t[n]=Math.pow(2,e%8)-1<<8-e%8),new this(t)},f.fromByteArray=function(e){const t=e.length;if(4===t)return new f.IPv4(e);if(16===t)return new f.IPv6(e);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},f.isValid=function(e){return f.IPv6.isValid(e)||f.IPv4.isValid(e)},f.isValidCIDR=function(e){return f.IPv6.isValidCIDR(e)||f.IPv4.isValidCIDR(e)},f.parse=function(e){if(f.IPv6.isValid(e))return f.IPv6.parse(e);if(f.IPv4.isValid(e))return f.IPv4.parse(e);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},f.parseCIDR=function(e){try{return f.IPv6.parseCIDR(e)}catch(t){try{return f.IPv4.parseCIDR(e)}catch(e){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},f.process=function(e){const t=this.parse(e);return"ipv6"===t.kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t},f.subnetMatch=function(e,t,r){let n,i,s,o;for(i in null==r&&(r="unicast"),t)if(Object.prototype.hasOwnProperty.call(t,i))for(s=t[i],!s[0]||s[0]instanceof Array||(s=[s]),n=0;n<s.length;n++)if(o=s[n],e.kind()===o[0].kind()&&e.match.apply(e,o))return i;return r},e.exports?e.exports=f:t.ipaddr=f}(aU)}(oU)),oU.exports),uU=n(cU);
63
+ /**
64
+ * @license
65
+ * Copyright 2019 Google LLC
66
+ * SPDX-License-Identifier: Apache-2.0
67
+ */
68
+ const lU=Symbol("Comlink.proxy"),hU=Symbol("Comlink.endpoint"),dU=Symbol("Comlink.releaseProxy"),fU=Symbol("Comlink.finalizer"),pU=Symbol("Comlink.thrown"),gU=e=>"object"==typeof e&&null!==e||"function"==typeof e,mU=new Map([["proxy",{canHandle:e=>gU(e)&&e[lU],serialize(e){const{port1:t,port2:r}=new MessageChannel;return yU(e,t),[r,[r]]},deserialize:e=>(e.start(),wU(e))}],["throw",{canHandle:e=>gU(e)&&pU in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function yU(e,t=globalThis,r=["*"]){t.addEventListener("message",(function n(i){if(!i||!i.data)return;if(!function(e,t){for(const r of e){if(t===r||"*"===r)return!0;if(r instanceof RegExp&&r.test(t))return!0}return!1}(r,i.origin))return void console.warn(`Invalid origin '${i.origin}' for comlink proxy`);const{id:s,type:o,path:a}=Object.assign({path:[]},i.data),c=(i.data.argumentList||[]).map(TU);let u;try{const t=a.slice(0,-1).reduce(((e,t)=>e[t]),e),r=a.reduce(((e,t)=>e[t]),e);switch(o){case"GET":u=r;break;case"SET":t[a.slice(-1)[0]]=TU(i.data.value),u=!0;break;case"APPLY":u=r.apply(t,c);break;case"CONSTRUCT":u=IU(new r(...c));break;case"ENDPOINT":{const{port1:t,port2:r}=new MessageChannel;yU(e,r),u=function(e,t){return CU.set(e,t),e}(t,[t])}break;case"RELEASE":u=void 0;break;default:return}}catch(e){u={value:e,[pU]:0}}Promise.resolve(u).catch((e=>({value:e,[pU]:0}))).then((r=>{const[i,a]=PU(r);t.postMessage(Object.assign(Object.assign({},i),{id:s}),a),"RELEASE"===o&&(t.removeEventListener("message",n),bU(t),fU in e&&"function"==typeof e[fU]&&e[fU]())})).catch((e=>{const[r,n]=PU({value:new TypeError("Unserializable return value"),[pU]:0});t.postMessage(Object.assign(Object.assign({},r),{id:s}),n)}))})),t.start&&t.start()}function bU(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function wU(e,t){const r=new Map;return e.addEventListener("message",(function(e){const{data:t}=e;if(!t||!t.id)return;const n=r.get(t.id);if(n)try{n(t)}finally{r.delete(t.id)}})),kU(e,r,[],t)}function vU(e){if(e)throw new Error("Proxy has been released and is not useable")}function EU(e){return _U(e,new Map,{type:"RELEASE"}).then((()=>{bU(e)}))}const AU=new WeakMap,SU="FinalizationRegistry"in globalThis&&new FinalizationRegistry((e=>{const t=(AU.get(e)||0)-1;AU.set(e,t),0===t&&EU(e)}));function kU(e,t,r=[],n=function(){}){let i=!1;const s=new Proxy(n,{get(n,o){if(vU(i),o===dU)return()=>{!function(e){SU&&SU.unregister(e)}(s),EU(e),t.clear(),i=!0};if("then"===o){if(0===r.length)return{then:()=>s};const n=_U(e,t,{type:"GET",path:r.map((e=>e.toString()))}).then(TU);return n.then.bind(n)}return kU(e,t,[...r,o])},set(n,s,o){vU(i);const[a,c]=PU(o);return _U(e,t,{type:"SET",path:[...r,s].map((e=>e.toString())),value:a},c).then(TU)},apply(n,s,o){vU(i);const a=r[r.length-1];if(a===hU)return _U(e,t,{type:"ENDPOINT"}).then(TU);if("bind"===a)return kU(e,t,r.slice(0,-1));const[c,u]=RU(o);return _U(e,t,{type:"APPLY",path:r.map((e=>e.toString())),argumentList:c},u).then(TU)},construct(n,s){vU(i);const[o,a]=RU(s);return _U(e,t,{type:"CONSTRUCT",path:r.map((e=>e.toString())),argumentList:o},a).then(TU)}});return function(e,t){const r=(AU.get(t)||0)+1;AU.set(t,r),SU&&SU.register(e,t,e)}(s,e),s}function RU(e){const t=e.map(PU);return[t.map((e=>e[0])),(r=t.map((e=>e[1])),Array.prototype.concat.apply([],r))];var r}const CU=new WeakMap;function IU(e){return Object.assign(e,{[lU]:!0})}function PU(e){for(const[t,r]of mU)if(r.canHandle(e)){const[n,i]=r.serialize(e);return[{type:"HANDLER",name:t,value:n},i]}return[{type:"RAW",value:e},CU.get(e)||[]]}function TU(e){switch(e.type){case"HANDLER":return mU.get(e.name).deserialize(e.value);case"RAW":return e.value}}function _U(e,t,r,n){return new Promise((i=>{const s=new Array(4).fill(0).map((()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16))).join("-");t.set(s,i),e.start&&e.start(),e.postMessage(Object.assign({id:s},r),n)}))}var NU,MU;var xU,OU,DU,BU,LU="1.0.35";var FU=function(){if(BU)return DU;var e;if(BU=1,"object"==typeof globalThis)e=globalThis;else try{e=function(){if(MU)return NU;MU=1;var e=function(){if("object"==typeof self&&self)return self;if("object"==typeof window&&window)return window;throw new Error("Unable to resolve global `this`")};return NU=function(){if(this)return this;if("object"==typeof globalThis&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch(t){return e()}try{return __global__||e()}finally{delete Object.prototype.__global__}}()}()}catch(e){}finally{if(e||"undefined"==typeof window||(e=window),!e)throw new Error("Could not determine global this")}var t=e.WebSocket||e.MozWebSocket,r=OU?xU:(OU=1,xU=LU);function n(e,r){return r?new t(e,r):new t(e)}return t&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(n,e,{get:function(){return t[e]}})})),DU={w3cwebsocket:t?n:null,version:r}}();var UU,jU,qU,zU,KU,GU,VU,HU;function $U(){if(jU)return UU;jU=1;var e=BE();return UU=function(t,r){var n=-1,i=t.length,s=i-1;for(r=void 0===r?i:r;++n<r;){var o=e(n,s),a=t[o];t[o]=t[n],t[n]=a}return t.length=r,t},UU}var WU=function(){if(HU)return VU;HU=1;var e=function(){if(zU)return qU;zU=1;var e=Th(),t=$U();return qU=function(r){return t(e(r))},qU}(),t=function(){if(GU)return KU;GU=1;var e=$U(),t=nA();return KU=function(r){return e(t(r))}}(),r=qu();return VU=function(n){return(r(n)?e:t)(n)}}(),JU=n(WU),QU=function(e,t){return QU=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},QU(e,t)};function ZU(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}QU(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}"function"==typeof SuppressedError&&SuppressedError;var YU=function(){function e(e,t,r){void 0===r&&(r=1),this.t=void 0,this.i=void 0,this.h=void 0,this.u=e,this.o=t,this.l=r}return e.prototype.v=function(){var e=this,t=e.h.h===e;if(t&&1===e.l)e=e.i;else if(e.t)for(e=e.t;e.i;)e=e.i;else{if(t)return e.h;for(var r=e.h;r.t===e;)r=(e=r).h;e=r}return e},e.prototype.p=function(){var e=this;if(e.i){for(e=e.i;e.t;)e=e.t;return e}for(var t=e.h;t.i===e;)t=(e=t).h;return e.i!==t?t:e},e.prototype.T=function(){var e=this.h,t=this.i,r=t.t;return e.h===this?e.h=t:e.t===this?e.t=t:e.i=t,t.h=e,t.t=this,this.h=t,this.i=r,r&&(r.h=this),t},e.prototype.I=function(){var e=this.h,t=this.t,r=t.i;return e.h===this?e.h=t:e.t===this?e.t=t:e.i=t,t.h=e,t.i=this,this.h=t,this.t=r,r&&(r.h=this),t},e}(),XU=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.O=1,t}return ZU(t,e),t.prototype.T=function(){var t=e.prototype.T.call(this);return this.M(),t.M(),t},t.prototype.I=function(){var t=e.prototype.I.call(this);return this.M(),t.M(),t},t.prototype.M=function(){this.O=1,this.t&&(this.O+=this.t.O),this.i&&(this.O+=this.i.O)},t}(YU),ej=function(){function e(e){void 0===e&&(e=0),this.iteratorType=e}return e.prototype.equals=function(e){return this.C===e.C},e}(),tj=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ZU(t,e),t}(function(){function e(){this._=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._},enumerable:!1,configurable:!0}),e.prototype.size=function(){return this._},e.prototype.empty=function(){return 0===this._},e}());function rj(){throw new RangeError("Iterator access denied!")}var nj,ij,sj=function(e){function t(t,r){void 0===t&&(t=function(e,t){return e<t?-1:e>t?1:0}),void 0===r&&(r=!1);var n=e.call(this)||this;return n.N=void 0,n.g=t,n.enableIndex=r,n.S=r?XU:YU,n.A=new n.S,n}return ZU(t,e),t.prototype.m=function(e,t){for(var r=this.A;e;){var n=this.g(e.u,t);if(n<0)e=e.i;else{if(!(n>0))return e;r=e,e=e.t}}return r},t.prototype.B=function(e,t){for(var r=this.A;e;){this.g(e.u,t)<=0?e=e.i:(r=e,e=e.t)}return r},t.prototype.j=function(e,t){for(var r=this.A;e;){var n=this.g(e.u,t);if(n<0)r=e,e=e.i;else{if(!(n>0))return e;e=e.t}}return r},t.prototype.k=function(e,t){for(var r=this.A;e;){this.g(e.u,t)<0?(r=e,e=e.i):e=e.t}return r},t.prototype.R=function(e){for(;;){var t,r=e.h;if(r===this.A)return;if(1===e.l)return void(e.l=0);if(e===r.t)if(1===(t=r.i).l)t.l=0,r.l=1,r===this.N?this.N=r.T():r.T();else{if(t.i&&1===t.i.l)return t.l=r.l,r.l=0,t.i.l=0,void(r===this.N?this.N=r.T():r.T());t.t&&1===t.t.l?(t.l=1,t.t.l=0,t.I()):(t.l=1,e=r)}else if(1===(t=r.t).l)t.l=0,r.l=1,r===this.N?this.N=r.I():r.I();else{if(t.t&&1===t.t.l)return t.l=r.l,r.l=0,t.t.l=0,void(r===this.N?this.N=r.I():r.I());t.i&&1===t.i.l?(t.l=1,t.i.l=0,t.T()):(t.l=1,e=r)}}},t.prototype.G=function(e){if(1!==this._){for(var t=e;t.t||t.i;){if(t.i)for(t=t.i;t.t;)t=t.t;else t=t.t;var r=e.u;e.u=t.u,t.u=r;var n=e.o;e.o=t.o,t.o=n,e=t}this.A.t===t?this.A.t=t.h:this.A.i===t&&(this.A.i=t.h),this.R(t);var i=t.h;if(t===i.t?i.t=void 0:i.i=void 0,this._-=1,this.N.l=0,this.enableIndex)for(;i!==this.A;)i.O-=1,i=i.h}else this.clear()},t.prototype.P=function(e){for(var t="number"==typeof e?e:void 0,r="function"==typeof e?e:void 0,n=void 0===e?[]:void 0,i=0,s=this.N,o=[];o.length||s;)if(s)o.push(s),s=s.t;else{if(s=o.pop(),i===t)return s;n&&n.push(s),r&&r(s,i,this),i+=1,s=s.i}return n},t.prototype.q=function(e){for(;;){var t=e.h;if(0===t.l)return;var r=t.h;if(t===r.t){if((n=r.i)&&1===n.l){if(n.l=t.l=0,r===this.N)return;r.l=1,e=r;continue}if(e!==t.i)return t.l=0,r===this.N?this.N=r.I():r.I(),void(r.l=1);e.l=0,e.t&&(e.t.h=t),e.i&&(e.i.h=r),t.i=e.t,r.t=e.i,e.t=t,e.i=r,r===this.N?(this.N=e,this.A.h=e):(i=r.h).t===r?i.t=e:i.i=e,e.h=r.h,t.h=e,r.h=e,r.l=1}else{var n,i;if((n=r.t)&&1===n.l){if(n.l=t.l=0,r===this.N)return;r.l=1,e=r;continue}if(e!==t.t)return t.l=0,r===this.N?this.N=r.T():r.T(),void(r.l=1);e.l=0,e.t&&(e.t.h=r),e.i&&(e.i.h=t),r.i=e.t,t.t=e.i,e.t=r,e.i=t,r===this.N?(this.N=e,this.A.h=e):(i=r.h).t===r?i.t=e:i.i=e,e.h=r.h,t.h=e,r.h=e,r.l=1}return void(this.enableIndex&&(t.M(),r.M(),e.M()))}},t.prototype.D=function(e,t,r){if(void 0===this.N)return this._+=1,this.N=new this.S(e,t,0),this.N.h=this.A,this.A.h=this.A.t=this.A.i=this.N,this._;var n,i=this.A.t,s=this.g(i.u,e);if(0===s)return i.o=t,this._;if(s>0)i.t=new this.S(e,t),i.t.h=i,n=i.t,this.A.t=n;else{var o=this.A.i,a=this.g(o.u,e);if(0===a)return o.o=t,this._;if(a<0)o.i=new this.S(e,t),o.i.h=o,n=o.i,this.A.i=n;else{if(void 0!==r){var c=r.C;if(c!==this.A){var u=this.g(c.u,e);if(0===u)return c.o=t,this._;if(u>0){var l=c.v(),h=this.g(l.u,e);if(0===h)return l.o=t,this._;h<0&&(n=new this.S(e,t),void 0===l.i?(l.i=n,n.h=l):(c.t=n,n.h=c))}}}if(void 0===n)for(n=this.N;;){var d=this.g(n.u,e);if(d>0){if(void 0===n.t){n.t=new this.S(e,t),n.t.h=n,n=n.t;break}n=n.t}else{if(!(d<0))return n.o=t,this._;if(void 0===n.i){n.i=new this.S(e,t),n.i.h=n,n=n.i;break}n=n.i}}}}if(this.enableIndex)for(var f=n.h;f!==this.A;)f.O+=1,f=f.h;return this.q(n),this._+=1,this._},t.prototype.F=function(e,t){for(;e;){var r=this.g(e.u,t);if(r<0)e=e.i;else{if(!(r>0))return e;e=e.t}}return e||this.A},t.prototype.clear=function(){this._=0,this.N=void 0,this.A.h=void 0,this.A.t=this.A.i=void 0},t.prototype.updateKeyByIterator=function(e,t){var r=e.C;if(r===this.A&&rj(),1===this._)return r.u=t,!0;var n=r.p().u;if(r===this.A.t)return this.g(n,t)>0&&(r.u=t,!0);var i=r.v().u;return r===this.A.i?this.g(i,t)<0&&(r.u=t,!0):!(this.g(i,t)>=0||this.g(n,t)<=0)&&(r.u=t,!0)},t.prototype.eraseElementByPos=function(e){if(e<0||e>this._-1)throw new RangeError;var t=this.P(e);return this.G(t),this._},t.prototype.eraseElementByKey=function(e){if(0===this._)return!1;var t=this.F(this.N,e);return t!==this.A&&(this.G(t),!0)},t.prototype.eraseElementByIterator=function(e){var t=e.C;t===this.A&&rj();var r=void 0===t.i;return 0===e.iteratorType?r&&e.next():r&&void 0!==t.t||e.next(),this.G(t),e},t.prototype.getHeight=function(){if(0===this._)return 0;return function e(t){return t?Math.max(e(t.t),e(t.i))+1:0}(this.N)},t}(tj),oj=function(e){function t(t,r,n){var i=e.call(this,n)||this;return i.C=t,i.A=r,0===i.iteratorType?(i.pre=function(){return this.C===this.A.t&&rj(),this.C=this.C.v(),this},i.next=function(){return this.C===this.A&&rj(),this.C=this.C.p(),this}):(i.pre=function(){return this.C===this.A.i&&rj(),this.C=this.C.p(),this},i.next=function(){return this.C===this.A&&rj(),this.C=this.C.v(),this}),i}return ZU(t,e),Object.defineProperty(t.prototype,"index",{get:function(){var e=this.C,t=this.A.h;if(e===this.A)return t?t.O-1:0;var r=0;for(e.t&&(r+=e.t.O);e!==t;){var n=e.h;e===n.i&&(r+=1,n.t&&(r+=n.t.O)),e=n}return r},enumerable:!1,configurable:!0}),t.prototype.isAccessible=function(){return this.C!==this.A},t}(ej),aj=function(e){function t(t,r,n,i){var s=e.call(this,t,r,i)||this;return s.container=n,s}return ZU(t,e),Object.defineProperty(t.prototype,"pointer",{get:function(){this.C===this.A&&rj();var e=this;return new Proxy([],{get:function(t,r){return"0"===r?e.C.u:"1"===r?e.C.o:(t[0]=e.C.u,t[1]=e.C.o,t[r])},set:function(t,r,n){if("1"!==r)throw new TypeError("prop must be 1");return e.C.o=n,!0}})},enumerable:!1,configurable:!0}),t.prototype.copy=function(){return new t(this.C,this.A,this.container,this.iteratorType)},t}(oj),cj=function(e){function t(t,r,n){void 0===t&&(t=[]);var i=e.call(this,r,n)||this,s=i;return t.forEach((function(e){s.setElement(e[0],e[1])})),i}return ZU(t,e),t.prototype.begin=function(){return new aj(this.A.t||this.A,this.A,this)},t.prototype.end=function(){return new aj(this.A,this.A,this)},t.prototype.rBegin=function(){return new aj(this.A.i||this.A,this.A,this,1)},t.prototype.rEnd=function(){return new aj(this.A,this.A,this,1)},t.prototype.front=function(){if(0!==this._){var e=this.A.t;return[e.u,e.o]}},t.prototype.back=function(){if(0!==this._){var e=this.A.i;return[e.u,e.o]}},t.prototype.lowerBound=function(e){var t=this.m(this.N,e);return new aj(t,this.A,this)},t.prototype.upperBound=function(e){var t=this.B(this.N,e);return new aj(t,this.A,this)},t.prototype.reverseLowerBound=function(e){var t=this.j(this.N,e);return new aj(t,this.A,this)},t.prototype.reverseUpperBound=function(e){var t=this.k(this.N,e);return new aj(t,this.A,this)},t.prototype.forEach=function(e){this.P((function(t,r,n){e([t.u,t.o],r,n)}))},t.prototype.setElement=function(e,t,r){return this.D(e,t,r)},t.prototype.getElementByPos=function(e){if(e<0||e>this._-1)throw new RangeError;var t=this.P(e);return[t.u,t.o]},t.prototype.find=function(e){var t=this.F(this.N,e);return new aj(t,this.A,this)},t.prototype.getElementByKey=function(e){return this.F(this.N,e).o},t.prototype.union=function(e){var t=this;return e.forEach((function(e){t.setElement(e[0],e[1])})),this._},t.prototype[Symbol.iterator]=function(){var e,t,r,n;return function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}}(this,(function(i){switch(i.label){case 0:e=this._,t=this.P(),r=0,i.label=1;case 1:return r<e?[4,[(n=t[r]).u,n.o]]:[3,4];case 2:i.sent(),i.label=3;case 3:return++r,[3,1];case 4:return[2]}}))},t}(sj);function uj(){if(ij)return nj;return ij=1,nj=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0},nj}var lj,hj,dj,fj,pj,gj,mj,yj,bj=n(uj());function wj(){if(fj)return dj;fj=1;var e=Jc(),t=Hc(),r=(hj||(hj=1,lj=function(e,t,r,n){for(var i=r-1,s=e.length;++i<s;)if(n(e[i],t))return i;return-1}),lj),n=Qc(),i=Th(),s=Array.prototype.splice;return dj=function(o,a,c,u){var l=u?r:t,h=-1,d=a.length,f=o;for(o===a&&(a=i(a)),c&&(f=e(o,n(c)));++h<d;)for(var p=0,g=a[h],m=c?c(g):g;(p=l(f,m,p,u))>-1;)f!==o&&s.call(f,p,1),s.call(o,p,1);return o},dj}var vj=function(){if(yj)return mj;yj=1;var e=nu(),t=function(){if(gj)return pj;gj=1;var e=wj();return pj=function(t,r){return t&&t.length&&r&&r.length?e(t,r):t},pj}(),r=e(t);return mj=r}(),Ej=n(vj);const Aj="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,Sj=new Set,kj="object"==typeof process&&process?process:{},Rj=(e,t,r,n)=>{"function"==typeof kj.emitWarning?kj.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)};let Cj=globalThis.AbortController,Ij=globalThis.AbortSignal;if(void 0===Cj){Ij=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},Cj=class{constructor(){t()}signal=new Ij;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==kj.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,Rj("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}const Pj=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Tj=e=>Pj(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?_j:null:null;class _j extends Array{constructor(e){super(e),this.fill(0)}}class Nj{heap;length;static#Lt=!1;static create(e){const t=Tj(e);if(!t)return[];Nj.#Lt=!0;const r=new Nj(e,t);return Nj.#Lt=!1,r}constructor(e,t){if(!Nj.#Lt)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class Mj{#Ft;#Ut;#jt;#qt;#zt;#Kt;#Gt;#Vt;get perf(){return this.#Vt}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#Ht;#$t;#Wt;#Jt;#Qt;#Zt;#Yt;#Xt;#er;#tr;#rr;#nr;#ir;#sr;#or;#ar;#cr;#ur;static unsafeExposeInternals(e){return{starts:e.#ir,ttls:e.#sr,sizes:e.#nr,keyMap:e.#Wt,keyList:e.#Jt,valList:e.#Qt,next:e.#Zt,prev:e.#Yt,get head(){return e.#Xt},get tail(){return e.#er},free:e.#tr,isBackgroundFetch:t=>e.#lr(t),backgroundFetch:(t,r,n,i)=>e.#hr(t,r,n,i),moveToTail:t=>e.#dr(t),indexes:t=>e.#fr(t),rindexes:t=>e.#pr(t),isStale:t=>e.#gr(t)}}get max(){return this.#Ft}get maxSize(){return this.#Ut}get calculatedSize(){return this.#$t}get size(){return this.#Ht}get fetchMethod(){return this.#Kt}get memoMethod(){return this.#Gt}get dispose(){return this.#jt}get onInsert(){return this.#qt}get disposeAfter(){return this.#zt}constructor(e){const{max:t=0,ttl:r,ttlResolution:n=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:o,allowStale:a,dispose:c,onInsert:u,disposeAfter:l,noDisposeOnSet:h,noUpdateTTL:d,maxSize:f=0,maxEntrySize:p=0,sizeCalculation:g,fetchMethod:m,memoMethod:y,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:E,ignoreFetchAbort:A,perf:S}=e;if(void 0!==S&&"function"!=typeof S?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#Vt=S??Aj,0!==t&&!Pj(t))throw new TypeError("max option must be a nonnegative integer");const k=t?Tj(t):Array;if(!k)throw new Error("invalid max value: "+t);if(this.#Ft=t,this.#Ut=f,this.maxEntrySize=p||this.#Ut,this.sizeCalculation=g,this.sizeCalculation){if(!this.#Ut&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==y&&"function"!=typeof y)throw new TypeError("memoMethod must be a function if defined");if(this.#Gt=y,void 0!==m&&"function"!=typeof m)throw new TypeError("fetchMethod must be a function if specified");if(this.#Kt=m,this.#ar=!!m,this.#Wt=new Map,this.#Jt=new Array(t).fill(void 0),this.#Qt=new Array(t).fill(void 0),this.#Zt=new k(t),this.#Yt=new k(t),this.#Xt=0,this.#er=0,this.#tr=Nj.create(t),this.#Ht=0,this.#$t=0,"function"==typeof c&&(this.#jt=c),"function"==typeof u&&(this.#qt=u),"function"==typeof l?(this.#zt=l,this.#rr=[]):(this.#zt=void 0,this.#rr=void 0),this.#or=!!this.#jt,this.#ur=!!this.#qt,this.#cr=!!this.#zt,this.noDisposeOnSet=!!h,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!v,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!A,0!==this.maxEntrySize){if(0!==this.#Ut&&!Pj(this.#Ut))throw new TypeError("maxSize must be a positive integer if specified");if(!Pj(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#mr()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!o,this.ttlResolution=Pj(n)||0===n?n:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!Pj(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#yr()}if(0===this.#Ft&&0===this.ttl&&0===this.#Ut)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Ft&&!this.#Ut){const e="LRU_CACHE_UNBOUNDED";if((e=>!Sj.has(e))(e)){Sj.add(e);Rj("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,Mj)}}}getRemainingTTL(e){return this.#Wt.has(e)?1/0:0}#yr(){const e=new _j(this.#Ft),t=new _j(this.#Ft);this.#sr=e,this.#ir=t,this.#br=(r,n,i=this.#Vt.now())=>{if(t[r]=0!==n?i:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout((()=>{this.#gr(r)&&this.#wr(this.#Jt[r],"expire")}),n+1);e.unref&&e.unref()}},this.#vr=r=>{t[r]=0!==e[r]?this.#Vt.now():0},this.#Er=(i,s)=>{if(e[s]){const o=e[s],a=t[s];if(!o||!a)return;i.ttl=o,i.start=a,i.now=r||n();const c=i.now-a;i.remainingTTL=o-c}};let r=0;const n=()=>{const e=this.#Vt.now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>r=0),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{const s=this.#Wt.get(i);if(void 0===s)return 0;const o=e[s],a=t[s];if(!o||!a)return 1/0;return o-((r||n())-a)},this.#gr=i=>{const s=t[i],o=e[i];return!!o&&!!s&&(r||n())-s>o}}#vr=()=>{};#Er=()=>{};#br=()=>{};#gr=()=>!1;#mr(){const e=new _j(this.#Ft);this.#$t=0,this.#nr=e,this.#Ar=t=>{this.#$t-=e[t],e[t]=0},this.#Sr=(e,t,r,n)=>{if(this.#lr(t))return 0;if(!Pj(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!Pj(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r},this.#kr=(t,r,n)=>{if(e[t]=r,this.#Ut){const r=this.#Ut-e[t];for(;this.#$t>r;)this.#Rr(!0)}this.#$t+=e[t],n&&(n.entrySize=r,n.totalCalculatedSize=this.#$t)}}#Ar=e=>{};#kr=(e,t,r)=>{};#Sr=(e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#fr({allowStale:e=this.allowStale}={}){if(this.#Ht)for(let t=this.#er;this.#Cr(t)&&(!e&&this.#gr(t)||(yield t),t!==this.#Xt);)t=this.#Yt[t]}*#pr({allowStale:e=this.allowStale}={}){if(this.#Ht)for(let t=this.#Xt;this.#Cr(t)&&(!e&&this.#gr(t)||(yield t),t!==this.#er);)t=this.#Zt[t]}#Cr(e){return void 0!==e&&this.#Wt.get(this.#Jt[e])===e}*entries(){for(const e of this.#fr())void 0===this.#Qt[e]||void 0===this.#Jt[e]||this.#lr(this.#Qt[e])||(yield[this.#Jt[e],this.#Qt[e]])}*rentries(){for(const e of this.#pr())void 0===this.#Qt[e]||void 0===this.#Jt[e]||this.#lr(this.#Qt[e])||(yield[this.#Jt[e],this.#Qt[e]])}*keys(){for(const e of this.#fr()){const t=this.#Jt[e];void 0===t||this.#lr(this.#Qt[e])||(yield t)}}*rkeys(){for(const e of this.#pr()){const t=this.#Jt[e];void 0===t||this.#lr(this.#Qt[e])||(yield t)}}*values(){for(const e of this.#fr()){void 0===this.#Qt[e]||this.#lr(this.#Qt[e])||(yield this.#Qt[e])}}*rvalues(){for(const e of this.#pr()){void 0===this.#Qt[e]||this.#lr(this.#Qt[e])||(yield this.#Qt[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const r of this.#fr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;if(void 0!==i&&e(i,this.#Jt[r],this))return this.get(this.#Jt[r],t)}}forEach(e,t=this){for(const r of this.#fr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#Jt[r],this)}}rforEach(e,t=this){for(const r of this.#pr()){const n=this.#Qt[r],i=this.#lr(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#Jt[r],this)}}purgeStale(){let e=!1;for(const t of this.#pr({allowStale:!0}))this.#gr(t)&&(this.#wr(this.#Jt[t],"expire"),e=!0);return e}info(e){const t=this.#Wt.get(e);if(void 0===t)return;const r=this.#Qt[t],n=this.#lr(r)?r.__staleWhileFetching:r;if(void 0===n)return;const i={value:n};if(this.#sr&&this.#ir){const e=this.#sr[t],r=this.#ir[t];if(e&&r){const t=e-(this.#Vt.now()-r);i.ttl=t,i.start=Date.now()}}return this.#nr&&(i.size=this.#nr[t]),i}dump(){const e=[];for(const t of this.#fr({allowStale:!0})){const r=this.#Jt[t],n=this.#Qt[t],i=this.#lr(n)?n.__staleWhileFetching:n;if(void 0===i||void 0===r)continue;const s={value:i};if(this.#sr&&this.#ir){s.ttl=this.#sr[t];const e=this.#Vt.now()-this.#ir[t];s.start=Math.floor(Date.now()-e)}this.#nr&&(s.size=this.#nr[t]),e.unshift([r,s])}return e}load(e){this.clear();for(const[t,r]of e){if(r.start){const e=Date.now()-r.start;r.start=this.#Vt.now()-e}this.set(t,r.value,r)}}set(e,t,r={}){if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:a}=r;let{noUpdateTTL:c=this.noUpdateTTL}=r;const u=this.#Sr(e,t,r.size||0,o);if(this.maxEntrySize&&u>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#wr(e,"set"),this;let l=0===this.#Ht?void 0:this.#Wt.get(e);if(void 0===l)l=0===this.#Ht?this.#er:0!==this.#tr.length?this.#tr.pop():this.#Ht===this.#Ft?this.#Rr(!1):this.#Ht,this.#Jt[l]=e,this.#Qt[l]=t,this.#Wt.set(e,l),this.#Zt[this.#er]=l,this.#Yt[l]=this.#er,this.#er=l,this.#Ht++,this.#kr(l,u,a),a&&(a.set="add"),c=!1,this.#ur&&this.#qt?.(t,e,"add");else{this.#dr(l);const r=this.#Qt[l];if(t!==r){if(this.#ar&&this.#lr(r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||s||(this.#or&&this.#jt?.(t,e,"set"),this.#cr&&this.#rr?.push([t,e,"set"]))}else s||(this.#or&&this.#jt?.(r,e,"set"),this.#cr&&this.#rr?.push([r,e,"set"]));if(this.#Ar(l),this.#kr(l,u,a),this.#Qt[l]=t,a){a.set="replace";const e=r&&this.#lr(r)?r.__staleWhileFetching:r;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update");this.#ur&&this.onInsert?.(t,e,t===r?"update":"replace")}if(0===n||this.#sr||this.#yr(),this.#sr&&(c||this.#br(l,n,i),a&&this.#Er(a,l)),!s&&this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}return this}pop(){try{for(;this.#Ht;){const e=this.#Qt[this.#Xt];if(this.#Rr(!0),this.#lr(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}}}#Rr(e){const t=this.#Xt,r=this.#Jt[t],n=this.#Qt[t];return this.#ar&&this.#lr(n)?n.__abortController.abort(new Error("evicted")):(this.#or||this.#cr)&&(this.#or&&this.#jt?.(n,r,"evict"),this.#cr&&this.#rr?.push([n,r,"evict"])),this.#Ar(t),e&&(this.#Jt[t]=void 0,this.#Qt[t]=void 0,this.#tr.push(t)),1===this.#Ht?(this.#Xt=this.#er=0,this.#tr.length=0):this.#Xt=this.#Zt[t],this.#Wt.delete(r),this.#Ht--,t}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,i=this.#Wt.get(e);if(void 0!==i){const e=this.#Qt[i];if(this.#lr(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#gr(i))return r&&this.#vr(i),n&&(n.has="hit",this.#Er(n,i)),!0;n&&(n.has="stale",this.#Er(n,i))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=this.#Wt.get(e);if(void 0===n||!r&&this.#gr(n))return;const i=this.#Qt[n];return this.#lr(i)?i.__staleWhileFetching:i}#hr(e,t,r,n){const i=void 0===t?void 0:this.#Qt[t];if(this.#lr(i))return i;const s=new Cj,{signal:o}=r;o?.addEventListener("abort",(()=>s.abort(o.reason)),{signal:s.signal});const a={signal:s.signal,options:r,context:n},c=(n,i=!1)=>{const{aborted:o}=s.signal,c=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(o&&!i?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,c&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),o&&!c&&!i)return u(s.signal.reason);const h=l,d=this.#Qt[t];return(d===l||c&&i&&void 0===d)&&(void 0===n?void 0!==h.__staleWhileFetching?this.#Qt[t]=h.__staleWhileFetching:this.#wr(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,a.options))),n},u=n=>{const{aborted:i}=s.signal,o=i&&r.allowStaleOnFetchAbort,a=o||r.allowStaleOnFetchRejection,c=a||r.noDeleteOnFetchRejection,u=l;if(this.#Qt[t]===l){!c||void 0===u.__staleWhileFetching?this.#wr(e,"fetch"):o||(this.#Qt[t]=u.__staleWhileFetching)}if(a)return r.status&&void 0!==u.__staleWhileFetching&&(r.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw n};r.status&&(r.status.fetchDispatched=!0);const l=new Promise(((t,n)=>{const o=this.#Kt?.(e,i,a);o&&o instanceof Promise&&o.then((e=>t(void 0===e?void 0:e)),n),s.signal.addEventListener("abort",(()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))}))})).then(c,(e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e)))),h=Object.assign(l,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,h,{...a.options,status:void 0}),t=this.#Wt.get(e)):this.#Qt[t]=h,h}#lr(e){if(!this.#ar)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Cj}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:p,forceRefresh:g=!1,status:m,signal:y}=t;if(!this.#ar)return m&&(m.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,status:m});const b={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:o,size:a,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:f,ignoreFetchAbort:d,status:m,signal:y};let w=this.#Wt.get(e);if(void 0===w){m&&(m.fetch="miss");const t=this.#hr(e,w,b,p);return t.__returned=t}{const t=this.#Qt[w];if(this.#lr(t)){const e=r&&void 0!==t.__staleWhileFetching;return m&&(m.fetch="inflight",e&&(m.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const i=this.#gr(w);if(!g&&!i)return m&&(m.fetch="hit"),this.#dr(w),n&&this.#vr(w),m&&this.#Er(m,w),t;const s=this.#hr(e,w,b,p),o=void 0!==s.__staleWhileFetching&&r;return m&&(m.fetch=i?"stale":"refresh",o&&i&&(m.returnedStale=!0)),o?s.__staleWhileFetching:s.__returned=s}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=this.#Gt;if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:i,...s}=t,o=this.get(e,s);if(!i&&void 0!==o)return o;const a=r(e,o,{options:s,context:n});return this.set(e,a,s),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,o=this.#Wt.get(e);if(void 0!==o){const t=this.#Qt[o],a=this.#lr(t);return s&&this.#Er(s,o),this.#gr(o)?(s&&(s.get="stale"),a?(s&&r&&void 0!==t.__staleWhileFetching&&(s.returnedStale=!0),r?t.__staleWhileFetching:void 0):(i||this.#wr(e,"expire"),s&&r&&(s.returnedStale=!0),r?t:void 0)):(s&&(s.get="hit"),a?t.__staleWhileFetching:(this.#dr(o),n&&this.#vr(o),t))}s&&(s.get="miss")}#Et(e,t){this.#Yt[t]=e,this.#Zt[e]=t}#dr(e){e!==this.#er&&(e===this.#Xt?this.#Xt=this.#Zt[e]:this.#Et(this.#Yt[e],this.#Zt[e]),this.#Et(this.#er,e),this.#er=e)}delete(e){return this.#wr(e,"delete")}#wr(e,t){let r=!1;if(0!==this.#Ht){const n=this.#Wt.get(e);if(void 0!==n)if(r=!0,1===this.#Ht)this.#Ir(t);else{this.#Ar(n);const r=this.#Qt[n];if(this.#lr(r)?r.__abortController.abort(new Error("deleted")):(this.#or||this.#cr)&&(this.#or&&this.#jt?.(r,e,t),this.#cr&&this.#rr?.push([r,e,t])),this.#Wt.delete(e),this.#Jt[n]=void 0,this.#Qt[n]=void 0,n===this.#er)this.#er=this.#Yt[n];else if(n===this.#Xt)this.#Xt=this.#Zt[n];else{const e=this.#Yt[n];this.#Zt[e]=this.#Zt[n];const t=this.#Zt[n];this.#Yt[t]=this.#Yt[n]}this.#Ht--,this.#tr.push(n)}}if(this.#cr&&this.#rr?.length){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}return r}clear(){return this.#Ir("delete")}#Ir(e){for(const t of this.#pr({allowStale:!0})){const r=this.#Qt[t];if(this.#lr(r))r.__abortController.abort(new Error("deleted"));else{const n=this.#Jt[t];this.#or&&this.#jt?.(r,n,e),this.#cr&&this.#rr?.push([r,n,e])}}if(this.#Wt.clear(),this.#Qt.fill(void 0),this.#Jt.fill(void 0),this.#sr&&this.#ir&&(this.#sr.fill(0),this.#ir.fill(0)),this.#nr&&this.#nr.fill(0),this.#Xt=0,this.#er=0,this.#tr.length=0,this.#$t=0,this.#Ht=0,this.#cr&&this.#rr){const e=this.#rr;let t;for(;t=e?.shift();)this.#zt?.(...t)}}}var xj,Oj={exports:{}};var Dj=(xj||(xj=1,function(e){var t,r,n,i=(t={km:6371,mile:3960,meter:6371e3,nmi:3440},r=function(e){return e*Math.PI/180},n=function(e,t){switch(e){case"[lat,lon]":return{latitude:t[0],longitude:t[1]};case"[lon,lat]":return{latitude:t[1],longitude:t[0]};case"{lon,lat}":return{latitude:t.lat,longitude:t.lon};case"{lat,lng}":return{latitude:t.lat,longitude:t.lng};case"geojson":return{latitude:t.geometry.coordinates[1],longitude:t.geometry.coordinates[0]};default:return t}},function(e,i,s){var o=(s=s||{}).unit in t?t[s.unit]:t.km,a=n(s.format,e),c=n(s.format,i),u=r(c.latitude-a.latitude),l=r(c.longitude-a.longitude),h=r(a.latitude),d=r(c.latitude),f=Math.sin(u/2)*Math.sin(u/2)+Math.sin(l/2)*Math.sin(l/2)*Math.cos(h)*Math.cos(d),p=2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f));return s.threshold?s.threshold>o*p:o*p});e.exports&&(e.exports=i)}(Oj)),Oj.exports),Bj=n(Dj);const Lj={JFK:[100,40.639447,-73.779317],LGA:[200,40.777199,-73.872597],EWR:[300,40.692501,-74.168701],BUF:[400,42.94049835,-78.73220062],BFI:[500,47.529999,-122.302002],SEA:[600,47.449162,-122.311134],PDX:[700,45.58869934,-122.5979996],HIO:[800,45.540401,-122.949997],SMF:[900,38.69540023803711,-121.59100341796875],SFO:[1e3,37.61899948120117,-122.375],PAO:[1100,37.461101532,-122.114997864],SJC:[1200,37.362452,-121.929188],WVI:[1300,36.9356994629,-121.790000916],BUR:[1400,34.197703,-118.356378],LAX:[1500,33.942501,-118.407997],SAN:[1600,32.7336006165,-117.190002441],LAS:[1700,36.083361,-115.151817],PHX:[1800,33.435302,-112.005905],ABQ:[1900,35.040199,-106.609001],DEN:[2e3,39.861698150635,-104.672996521],SLC:[2100,40.785749,-111.979746],STP:[2200,44.93479,-93.060036],MSP:[2300,44.882,-93.221802],FSD:[2400,43.585463,-96.741152],OMA:[2500,41.3032,-95.894096],MCI:[2600,39.2976,-94.713898],OKC:[2700,35.393101,-97.6007],ADS:[2800,32.9686012268,-96.8364028931],DFW:[2900,32.896801,-97.038002],IAH:[3e3,29.984399795532227,-95.34140014648438],AUS:[3100,30.197535,-97.662015],SAT:[3200,29.533701,-98.469803],MFE:[3300,26.176141,-98.237965],HNL:[3400,21.32062,-157.924228],ANC:[3500,61.1744,-149.996002],BOS:[3600,42.3643,-71.005203],BGR:[3700,44.8074,-68.828102],YTO:[3800,43.6772,-79.6306],YYZ:[3900,43.6772,-79.6306],YOW:[4e3,45.322498,-75.669197],YUL:[4100,45.4706,-73.740799],YHZ:[4200,44.8807983398,-63.5085983276],YVR:[4300,49.193901062,-123.183998108],YYC:[4400,51.113899231,-114.019996643],YXE:[4500,52.170799255371094,-106.69999694824219],YWG:[4600,49.909999847399995,-97.2398986816],KEF:[4700,63.985001,-22.6056],DUB:[4800,53.428713,-6.262121],ORK:[4900,51.841301,-8.49111],MAN:[5e3,53.349375,-2.279521],LHR:[5100,51.4706,-.461941],LON:[5200,51.4706,-.461941],LCY:[5300,51.505299,.055278],EDI:[5400,55.950145,-3.372288],BRU:[5500,50.901402,4.48444],AMS:[5600,52.308601,4.76389],DUS:[5700,51.289501,6.76678],FRA:[5800,50.036521,8.561268],WIE:[5900,50.049800872802734,8.325400352478027],STR:[6e3,48.689899,9.22196],MUC:[6100,48.353802,11.7861],TXL:[6200,52.362247,13.500672],HAM:[6300,53.630402,9.98823],LUX:[6400,49.6233333,6.2044444],DLP:[6500,49.012798,2.55],CDG:[6600,49.012798,2.55],PAR:[6700,49.012798,2.55],BOD:[6800,44.8283,-.715556],MRS:[6900,43.438088,5.2125],LYS:[7e3,45.725556,5.081111],GVA:[7100,46.238098,6.10895],ZRH:[7200,47.458056,8.548056],MXP:[7300,45.6306,8.72811],LIN:[7400,45.445099,9.27674],FCO:[7500,41.804532,12.251998],PMO:[7600,38.175999,13.091],PRG:[7700,50.103514,14.256992],CPH:[7800,55.617900848389,12.656000137329],OSL:[7900,60.193901,11.1004],ARN:[8e3,59.651901245117,17.918600082397],BMA:[8100,59.354400634765625,17.941699981689453],GOT:[8200,57.662799835205,12.279800415039],RIX:[8300,56.923599,23.9711],TLL:[8400,59.41329956049999,24.832799911499997],HEL:[8500,60.3172,24.963301],LED:[8600,59.80030059814453,30.262500762939453],KLD:[8700,56.82469940185547,35.7577018737793],DME:[8800,55.40879821777344,37.90629959106445],SVX:[8900,56.743099212646,60.802700042725],KJA:[9e3,56.173077,92.492437],KHV:[9100,48.528338,135.188588],MSQ:[9200,53.888071,28.039964],VNO:[9300,54.634102,25.285801],WAW:[9400,52.1656990051,20.967100143399996],KBP:[9500,50.345001,30.894699],KIV:[9600,46.9277,28.931],OTP:[9700,44.572127,26.103396],IST:[9800,41.261297,28.741951],ADB:[9900,38.2924,27.157],ATH:[1e4,37.936401,23.9445],SKG:[10100,40.51928,22.970009],SOF:[10200,42.696357,23.417671],TIA:[10300,41.4147,19.7206],BEG:[10400,44.818401,20.309099],BUD:[10500,47.43018,19.262393],BTS:[10600,48.1702,17.2127],VIE:[10700,48.110298,16.5697],ZAG:[10800,45.742901,16.0688],TUN:[10900,36.851002,10.2272],AAE:[11e3,36.826781,7.81334],ALG:[11100,36.693886,3.214531],ORN:[11200,35.623901,-.621183],MAD:[11300,40.471926,-3.56264],BCN:[11400,41.2971,2.07846],LIS:[11500,38.7813,-9.13592],CMN:[11600,33.3675,-7.58997],DKR:[11700,14.7397,-17.4902],OUA:[11800,12.3532,-1.51242],ACC:[11900,5.605189800262451,-.16678600013256073],LOS:[12e3,6.5773701667785645,3.321160078048706],FIH:[12100,-4.38575,15.4446],LAD:[12200,-8.85837,13.2312],CPT:[12300,-33.9648017883,18.6016998291],DUR:[12400,-29.6144444444,31.1197222222],JNB:[12500,-26.1392,28.246],MPM:[12600,-25.920799,32.572601],GBE:[12700,-24.555201,25.9182],HRE:[12800,-17.931801,31.0928],TNR:[12900,-18.7969,47.478802],RUN:[13e3,-20.890087,55.518894],MRU:[13100,-20.430201,57.683601],DAR:[13200,-6.87811,39.202599],MBA:[13300,-4.03483,39.5942],NBO:[13400,-1.31923997402,36.9277992249],KGL:[13500,-1.96863,30.1395],JIB:[13600,11.5473,43.1595],CAI:[13700,30.111534,31.396694],TLV:[13800,32.011398,34.8867],HFA:[13900,32.80939865112305,35.04309844970703],ZDM:[14e3,31.91123,35.20756],AMM:[14100,31.7226009369,35.9931983948],BEY:[14200,33.820899963378906,35.488399505615234],LCA:[14300,34.875099,33.624901],EVN:[14400,40.1473007202,44.3959007263],TBS:[14500,41.669201,44.9547],GYD:[14600,40.467498779296875,50.04669952392578],LLK:[14700,38.757919,48.807042],EBL:[14800,36.23759841918945,43.963199615478516],ISU:[14900,35.5617485046,45.316738128699996],BGW:[15e3,33.262501,44.2346],NJF:[15100,31.989853,44.404317],XNH:[15200,30.935801,46.090099],BSR:[15300,30.549101,47.662102],KWI:[15400,29.226601,47.968899],RUH:[15500,24.9576,46.698799],DMM:[15600,26.471200942993164,49.79790115356445],JED:[15700,21.6796,39.156502],BAH:[15800,26.267295,50.63764],DOH:[15900,25.273056,51.608056],DXB:[16e3,25.2527999878,55.3643989563],FJR:[16100,25.1122,56.324001],MCT:[16200,23.593299865722656,58.284400939941406],MLE:[16300,4.191830158233643,73.52909851074219],CMB:[16400,7.180759906768799,79.88410186767578],MAA:[16500,12.990005,80.169296],BLR:[16600,13.1979,77.706299],HYD:[16700,17.231318,78.429855],NAG:[16800,21.092199,79.047203],BBI:[16900,20.244400024399997,85.8178024292],CCU:[17e3,22.654699325561523,88.44670104980469],AMD:[17100,23.0772,72.634697],BOM:[17200,19.0886993408,72.8678970337],PNQ:[17300,18.5821,73.919701],CNN:[17400,11.918614,75.547211],COK:[17500,10.152,76.401901],PAT:[17600,25.591299,85.087997],KNU:[17700,26.404301,80.410103],DEL:[17800,28.55563,77.09519],IXC:[17900,30.6735,76.788498],JSR:[18e3,23.1838,89.160797],CGP:[18100,22.249599,91.813301],DAC:[18200,23.843347,90.397783],PBH:[18300,27.4032,89.424599],KTM:[18400,27.6966,85.3591],LHE:[18500,31.521601,74.403603],ISB:[18600,33.549,72.82566],KHI:[18700,24.9065,67.160797],TAS:[18800,41.257900238,69.2811965942],ALA:[18900,43.354267,77.042828],ULN:[19e3,47.843102,106.766998],ICN:[19100,37.46910095214844,126.45099639892578],TYO:[19200,35.764702,140.386002],NRT:[19300,35.764702,140.386002],HND:[19400,35.552299,139.779999],ITM:[19500,34.785499572753906,135.43800354003906],KIX:[19600,34.427299,135.244003],FUK:[19700,33.585899353027344,130.4510040283203],OKA:[19800,26.195801,127.646004],GUM:[19900,13.4834,144.796005],CGY:[2e4,8.612203,124.456496],CEB:[20100,10.309261,123.97974],MNL:[20200,14.5086,121.019997],BWN:[20300,4.9442,114.928001],SGN:[20400,10.8188,106.652],HAN:[20500,21.221201,105.806999],PNH:[20600,11.5466,104.844002],VTE:[20700,17.988300323500003,102.56300354],MFM:[20800,22.149599,113.592003],HKG:[20900,22.308901,113.915001],KHH:[21e3,22.577101,120.349998],TPE:[21100,25.0777,121.233002],FOC:[21200,25.934669,119.66318],HYN:[21300,28.562201,121.429001],HGH:[21400,30.23609,120.428865],SHA:[21500,31.198104,121.33426],CZX:[21600,31.919701,119.778999],WHU:[21700,31.3906,118.408997],KHN:[21800,28.864815,115.90271],CGD:[21900,28.9189,111.639999],KWE:[22e3,26.541466,106.803331],KMG:[22100,25.110313,102.936743],LHW:[22200,36.515202,103.620003],ZHY:[22300,37.573125,105.154454],SJW:[22400,38.280701,114.696999],PKX:[22500,39.509945,116.41092],BJS:[22600,40.080101013183594,116.58499908447266],TSN:[22700,39.124401092499994,117.346000671],TNA:[22800,36.857201,117.216003],TAO:[22900,36.361953,120.088171],HAK:[23e3,19.9349,110.459],FUO:[23100,23.0833,113.07],ZGN:[23200,23.392401,113.299004],CAN:[23300,23.392401,113.299004],SZX:[23400,22.639299,113.810997],MDL:[23500,21.702199935913086,95.97789764404297],RGN:[23600,16.907300949099998,96.1332015991],CNX:[23700,18.766799926799997,98.962600708],BKK:[23800,13.681099891662598,100.74700164794922],URT:[23900,9.13259983063,99.135597229],KUL:[24e3,2.74558,101.709999],JHB:[24100,1.64131,103.669998],QPG:[24200,1.36042,103.910004],SIN:[24300,1.35019,103.994003],CGK:[24400,-6.1255698204,106.65599823],JOG:[24500,-7.78818,110.431999],DPS:[24600,-8.74817,115.167],DEX:[24700,-4.8557,139.482006],PER:[24800,-31.94029998779297,115.96700286865234],ADL:[24900,-34.947512,138.533393],MEL:[25e3,-37.673302,144.843002],HBA:[25100,-42.836101532,147.509994507],CBR:[25200,-35.3069,149.195007],SYD:[25300,-33.94609832763672,151.177001953125],BNE:[25400,-27.384199142456055,153.11700439453125],CHC:[25500,-43.48939895629883,172.53199768066406],WLG:[25600,-41.3272018433,174.804992676],AKL:[25700,-37.01199,174.786331],NOU:[25800,-22.014601,166.212997],SUV:[25900,-18.04330062866211,178.5590057373047],PPT:[26e3,-17.553699,-149.606995],GDL:[26100,20.52504,-103.301557],QRO:[26200,20.6173,-100.185997],MEX:[26300,19.435433,-99.082432],GUA:[26400,14.5833,-90.527496],TGU:[26500,14.0609,-87.217201],SJO:[26600,9.99386,-84.208801],PTY:[26700,9.0713596344,-79.3834991455],MDE:[26800,6.16454,-75.4231],BOG:[26900,4.70159,-74.1469],UIO:[27e3,-.125399,-78.354306],GYE:[27100,-2.15742,-79.883598],LIM:[27200,-12.0219,-77.114305],ARI:[27300,-18.348499,-70.338699],SCL:[27400,-33.393001556396484,-70.78579711914062],COR:[27500,-31.323601,-64.208],NQN:[27600,-38.949001,-68.155701],EZE:[27700,-34.8222,-58.5358],ASU:[27800,-25.240156,-57.519227],CGB:[27900,-15.6529,-56.116699],GYN:[28e3,-16.632,-49.220699],BSB:[28100,-15.869167,-47.920834],UDI:[28200,-18.883579,-48.225936],SJP:[28300,-20.817113,-49.406963],RAO:[28400,-21.134314,-47.774053],VCP:[28500,-23.007404,-47.134502],SOD:[28600,-23.478001,-47.490002],GRU:[28700,-23.431944,-46.467778],QWJ:[28800,-23.431944,-46.467778],SJK:[28900,-23.2292,-45.8615],GIG:[29e3,-22.809999,-43.250557],CNF:[29100,-19.63571,-43.966928],CAW:[29200,-21.698299,-41.301701],VIX:[29300,-20.258,-40.285],SSA:[29400,-12.908611,-38.322498],REC:[29500,-8.125984,-34.923316],JDO:[29600,-7.21932,-39.269096],FOR:[29700,-3.775833,-38.532222],BEL:[29800,-1.379279,-48.476207],MAO:[29900,-3.03861,-60.049702],POA:[3e4,-29.994712,-51.166592],FLN:[30100,-27.670279,-48.552502],ITJ:[30200,-26.879431,-48.650979],NVT:[30300,-26.879431,-48.650979],BNU:[30400,-26.831661,-49.093569],JOI:[30500,-26.224501,-48.797401],CWB:[30600,-25.5285,-49.1758],CFC:[30700,-26.787423,-50.939942],XAP:[30800,-27.134199,-52.656601],PBM:[30900,5.45283,-55.187801],GEO:[31e3,6.49855,-58.254101],BGI:[31100,13.0746,-59.4925],GND:[31200,12.0042,-61.786201],CUR:[31300,12.1889,-68.959801],SDQ:[31400,18.42970085144,-69.668899536133],STI:[31500,19.406099319458008,-70.60469818115234],KIN:[31600,17.935699462890625,-76.7874984741211],MIA:[31700,25.79319953918457,-80.29060363769531],TPA:[31800,27.975500106811523,-82.533203125],GNV:[31900,29.6900997162,-82.2717971802],JAX:[32e3,30.49410057067871,-81.68789672851562],TLH:[32100,30.3965,-84.350304],MGM:[32200,32.300598,-86.393997],ATL:[32300,33.6367,-84.428101],PDK:[32400,33.8755989075,-84.3020019531],BNA:[32500,36.1245002746582,-86.6781997680664],MEM:[32600,35.04240036010742,-89.97669982910156],STL:[32700,38.748697,-90.370003],IND:[32800,39.7173,-86.294403],CHI:[32900,41.9786,-87.9048],ORD:[33e3,41.9786,-87.9048],DTW:[33100,42.212398529052734,-83.35340118408203],CLE:[33200,41.411701,-81.8498],PIT:[33300,40.49150085,-80.23290253],CMH:[33400,39.998001,-82.891899],LCK:[33500,39.813801,-82.927803],CLT:[33600,35.2140007019043,-80.94309997558594],RDU:[33700,35.877602,-78.787498],ORF:[33800,36.8946,-76.201202],RIC:[33900,37.50519943237305,-77.3197021484375],IAD:[34e3,38.9445,-77.455803],DCA:[34100,38.8521,-77.037697],PHL:[34200,39.87189865112305,-75.24109649658203],NYC:[34300,40.639447,-73.779317]},Fj=new Bv("fetchAirportCodeFromCdn"),Uj=async(e,t,r)=>(await Xv(fetch(e,{method:"HEAD"}),r)).headers.get(t),jj=async()=>{const e=2e3;try{return await(async(e,t)=>{const r=await Uj(e,"X-Amz-Cf-Pop",t);if(!r||r.length<3)throw new Error("Could not get airport code from Amazon");return r.substring(0,3)})("https://d47ahk2wrqweh.cloudfront.net/cdn-location",e)}catch(e){Fj.warn(e)}try{return await(async e=>{const t=await Uj("https://www.fastly.com","X-Served-By",e);if(!t||t.length<3)throw new Error("Could not get airport code from Fastly");return t.substring(t.length-3)})(e)}catch(e){Fj.warn(e)}try{return await(async e=>{const t=await Uj("https://www.cloudflare.com","CF-RAY",e);if(!t||t.length<3)throw new Error("Could not get airport code from Cloudflare");return t.substring(t.length-3)})(e)}catch(e){Fj.warn(e)}throw new Error("Could not get airport code from any CDN")},qj=new Bv("getLocalRegion");let zj,Kj;const Gj=async()=>{let e;return e=await(async()=>{let e;try{e=await jj()}catch{return}return e})(),void 0!==e&&Lj[e]?Lj[e][0]:(()=>{const e=Object.keys(Lj),t=e[Math.floor(Math.random()*e.length)],r=Lj[t][0]+99;return qj.warn(`Could not get airport code, using random region: ${r}`),r})()};var Vj,Hj,$j={exports:{}},Wj=$j.exports;function Jj(){return Vj||(Vj=1,function(e){(function(){var t,r,n,i,s,o,a,c,u,l,h,d,f,p,g;n=Math.floor,l=Math.min,r=function(e,t){return e<t?-1:e>t?1:0},u=function(e,t,i,s,o){var a;if(null==i&&(i=0),null==o&&(o=r),i<0)throw new Error("lo must be non-negative");for(null==s&&(s=e.length);i<s;)o(t,e[a=n((i+s)/2)])<0?s=a:i=a+1;return[].splice.apply(e,[i,i-i].concat(t)),t},o=function(e,t,n){return null==n&&(n=r),e.push(t),p(e,0,e.length-1,n)},s=function(e,t){var n,i;return null==t&&(t=r),n=e.pop(),e.length?(i=e[0],e[0]=n,g(e,0,t)):i=n,i},c=function(e,t,n){var i;return null==n&&(n=r),i=e[0],e[0]=t,g(e,0,n),i},a=function(e,t,n){var i;return null==n&&(n=r),e.length&&n(e[0],t)<0&&(t=(i=[e[0],t])[0],e[0]=i[1],g(e,0,n)),t},i=function(e,t){var i,s,o,a,c,u;for(null==t&&(t=r),c=[],s=0,o=(a=function(){u=[];for(var t=0,r=n(e.length/2);0<=r?t<r:t>r;0<=r?t++:t--)u.push(t);return u}.apply(this).reverse()).length;s<o;s++)i=a[s],c.push(g(e,i,t));return c},f=function(e,t,n){var i;if(null==n&&(n=r),-1!==(i=e.indexOf(t)))return p(e,0,i,n),g(e,i,n)},h=function(e,t,n){var s,o,c,u,l;if(null==n&&(n=r),!(o=e.slice(0,t)).length)return o;for(i(o,n),c=0,u=(l=e.slice(t)).length;c<u;c++)s=l[c],a(o,s,n);return o.sort(n).reverse()},d=function(e,t,n){var o,a,c,h,d,f,p,g,m;if(null==n&&(n=r),10*t<=e.length){if(!(c=e.slice(0,t).sort(n)).length)return c;for(a=c[c.length-1],h=0,f=(p=e.slice(t)).length;h<f;h++)n(o=p[h],a)<0&&(u(c,o,0,null,n),c.pop(),a=c[c.length-1]);return c}for(i(e,n),m=[],d=0,g=l(t,e.length);0<=g?d<g:d>g;0<=g?++d:--d)m.push(s(e,n));return m},p=function(e,t,n,i){var s,o,a;for(null==i&&(i=r),s=e[n];n>t&&i(s,o=e[a=n-1>>1])<0;)e[n]=o,n=a;return e[n]=s},g=function(e,t,n){var i,s,o,a,c;for(null==n&&(n=r),s=e.length,c=t,o=e[t],i=2*t+1;i<s;)(a=i+1)<s&&!(n(e[i],e[a])<0)&&(i=a),e[t]=e[i],i=2*(t=i)+1;return e[t]=o,p(e,c,t,n)},t=function(){function e(e){this.cmp=null!=e?e:r,this.nodes=[]}return e.push=o,e.pop=s,e.replace=c,e.pushpop=a,e.heapify=i,e.updateItem=f,e.nlargest=h,e.nsmallest=d,e.prototype.push=function(e){return o(this.nodes,e,this.cmp)},e.prototype.pop=function(){return s(this.nodes,this.cmp)},e.prototype.peek=function(){return this.nodes[0]},e.prototype.contains=function(e){return-1!==this.nodes.indexOf(e)},e.prototype.replace=function(e){return c(this.nodes,e,this.cmp)},e.prototype.pushpop=function(e){return a(this.nodes,e,this.cmp)},e.prototype.heapify=function(){return i(this.nodes,this.cmp)},e.prototype.updateItem=function(e){return f(this.nodes,e,this.cmp)},e.prototype.clear=function(){return this.nodes=[]},e.prototype.empty=function(){return 0===this.nodes.length},e.prototype.size=function(){return this.nodes.length},e.prototype.clone=function(){var t;return(t=new e).nodes=this.nodes.slice(0),t},e.prototype.toArray=function(){return this.nodes.slice(0)},e.prototype.insert=e.prototype.push,e.prototype.top=e.prototype.peek,e.prototype.front=e.prototype.peek,e.prototype.has=e.prototype.contains,e.prototype.copy=e.prototype.clone,e}(),e.exports=t}).call(Wj)}($j)),$j.exports}Hj||(Hj=1,Jj());const Qj=(e,t)=>yL.distance(e,t),Zj=e=>gw(e),Yj=e=>mw(e),Xj=e=>Zj(e.nodeId),eq=(e,t)=>yw(e.nodeId,t.nodeId),tq=()=>Zj(so(20));class rq extends Sl{options;contactsById=new Map;contactIds=[];constructor(e){super(),this.options=e,this.compareIds=this.compareIds.bind(this)}getClosestContactId(){return this.contactIds[0]}getContactIds(){return this.contactIds}addContact(e){const t=e.getNodeId();if(!this.options.excludedNodeIds?.has(t)&&!(!this.options.allowToContainReferenceId&&this.options.referenceId===t||void 0!==this.options.nodeIdDistanceLimit&&this.compareIds(this.options.nodeIdDistanceLimit,t)<0||this.contactsById.has(t)))if(void 0===this.options.maxSize||this.contactIds.length<this.options.maxSize){this.contactsById.set(t,e);const r=pL(this.contactIds,t,(e=>this.distanceToReferenceId(e)));this.contactIds.splice(r,0,t),this.hasEventListeners()&&this.emit("contactAdded",e)}else if(this.compareIds(this.contactIds[this.options.maxSize-1],t)>0){const r=this.contactIds.pop(),n=this.contactsById.get(r);this.contactsById.delete(r),this.contactsById.set(t,e);const i=pL(this.contactIds,t,(e=>this.distanceToReferenceId(e)));this.contactIds.splice(i,0,t),this.hasEventListeners()&&(this.emit("contactRemoved",n),this.emit("contactAdded",e))}}addContacts(e){e.forEach((e=>this.addContact(e)))}getContact(e){return this.contactsById.get(e)}has(e){return this.contactsById.has(e)}getClosestContacts(e){return(void 0===e?this.contactIds:this.contactIds.slice(0,Math.max(e,0))).map((e=>this.contactsById.get(e)))}getFurthestContacts(e){const t=[...this.getClosestContacts()].reverse();return void 0===e?t:t.slice(0,Math.max(e,0))}compareIds(e,t){return this.distanceToReferenceId(e)-this.distanceToReferenceId(t)}distanceToReferenceId(e){return Qj(Yj(this.options.referenceId),Yj(e))}removeContact(e){if(this.contactsById.has(e)){const t=this.contactsById.get(e),r=this.contactIds.findIndex((t=>t===e));return this.contactIds.splice(r,1),this.contactsById.delete(e),this.hasEventListeners()&&this.emit("contactRemoved",t),!0}return!1}getAllContactsInUndefinedOrder(){return this.contactsById.values()}getSize(e){let t=0;if(void 0!==e)for(const r of e)this.has(r)&&t++;return this.contactIds.length-t}clear(){this.contactsById.clear(),this.contactIds=[]}stop(){this.removeAllListeners(),this.clear()}hasEventListeners(){return this.eventNames().length>0}}class nq{values=new Set;queue=[];maxItemCount;constructor(e){this.maxItemCount=e}add(e){if(this.values.add(e),this.queue.push(e),this.queue.length>this.maxItemCount){const e=this.queue.shift();this.values.delete(e)}}isMostLikelyDuplicate(e){return this.values.has(e)}size(){return this.values.size}clear(){this.values.clear(),this.queue=[]}}var iq;!function(e){e.CONNECTION_FAILED="CONNECTION_FAILED",e.COULD_NOT_ROUTE="COULD_NOT_ROUTE",e.STARTING_WEBSOCKET_SERVER_FAILED="STARTING_WEBSOCKET_SERVER_FAILED",e.WEBSOCKET_CONNECTION_REQUEST_REJECTED="WEBSOCKET_CONNECTION_REQUEST_REJECTED",e.COULD_NOT_START="COULD_NOT_START",e.COULD_NOT_STOP="COULD_NOT_STOP",e.CANNOT_CONNECT_TO_SELF="CANNOT_CONNECT_TO_SELF",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.ILLEGAL_RTC_PEER_CONNECTION_STATE="ILLEGAL_RTC_PEER_CONNECTION_STATE",e.ILLEGAL_ARGUMENTS="ILLEGAL_ARGUMENTS",e.CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT="CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT",e.CONNECTION_LOCKER="CONNECTION_LOCKER",e.DHT_JOIN_TIMEOUT="DHT_JOIN_TIMEOUT",e.SEND_FAILED="SEND_FAILED",e.GETTING_DATA_FAILED="GETTING_DATA_FAILED",e.CONNECTION_NOT_OPEN="CONNECTION_NOT_OPEN"}(iq||(iq={}));class sq extends Error{code;originalError;constructor(e,t,r){super(t),this.code=e,this.originalError=r}}class oq extends sq{constructor(e,t){super(iq.CONNECTION_FAILED,e,t)}}class aq extends sq{constructor(e,t){super(iq.STARTING_WEBSOCKET_SERVER_FAILED,e,t)}}class cq extends sq{constructor(e,t){super(iq.COULD_NOT_START,e,t)}}class uq extends sq{constructor(e,t){super(iq.CANNOT_CONNECT_TO_SELF,e,t)}}class lq extends sq{constructor(e,t){super(iq.CONNECTIVITY_RESPONSE_NOT_RECEIVED_BEFORE_TIMEOUT,e,t)}}class hq extends sq{constructor(e,t){super(iq.SEND_FAILED,e,t)}}const dq=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};const fq=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var pq;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(pq||(pq={}));const gq=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>fq},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",pq]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>dq}])}};const mq=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var yq,bq,wq,vq,Eq,Aq;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(yq||(yq={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(bq||(bq={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}(wq||(wq={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(vq||(vq={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(Eq||(Eq={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(Aq||(Aq={}));const Sq=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>fq},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>mq},{no:5,name:"ttl",kind:"scalar",T:13}])}};const kq=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const Rq=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>fq}])}};const Cq=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>Fq}])}};const Iq=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>Pq}])}};const Pq=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>fq},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>mq},{no:5,name:"storedAt",kind:"message",T:()=>mq},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const Tq=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const _q=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>Fq},{no:2,name:"requestId",kind:"scalar",T:9}])}};const Nq=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const Mq=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>Fq},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>Fq},{no:3,name:"requestId",kind:"scalar",T:9}])}};const xq=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",yq]}])}};const Oq=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>Fq},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>Pq},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>Fq}])}};const Dq=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const Bq=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const Lq=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const Fq=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",bq]},{no:3,name:"udp",kind:"message",T:()=>Uq},{no:4,name:"tcp",kind:"message",T:()=>Uq},{no:5,name:"websocket",kind:"message",T:()=>Uq},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const Uq=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const jq=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>Fq},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>Hq},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>Fq},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>Fq},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const qq=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",vq]}])}};const zq=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const Kq=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>Uq},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const Gq=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>Fq},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>Fq},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const Vq=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>Fq},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",Eq]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const Hq=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>Fq},{no:3,name:"targetDescriptor",kind:"message",T:()=>Fq},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>gq},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>zq},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>Kq},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>Gq},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>Vq},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>xq}])}};const $q=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const Wq=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const Jq=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const Qq=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const Zq=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const Yq=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const Xq=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const ez=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const tz=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",Aq]}])}};const rz=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const nz=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const iz=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>Pq}])}};const sz=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const oz=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>Fq}])}},az=new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:Tq,O:_q},{name:"getClosestRingPeers",options:{},I:Nq,O:Mq},{name:"ping",options:{},I:Dq,O:Bq},{name:"leaveNotice",options:{},I:Lq,O:dq}]),cz=new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:jq,O:qq},{name:"forwardMessage",options:{},I:jq,O:qq}]),uz=new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:jq,O:qq}]),lz=new vF("dht.StoreRpc",[{name:"storeData",options:{},I:Sq,O:kq},{name:"replicateData",options:{},I:Iq,O:dq}]),hz=new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:Oq,O:dq}]),dz=new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:$q,O:dq}]),fz=new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:Wq,O:dq},{name:"rtcOffer",options:{},I:Jq,O:dq},{name:"rtcAnswer",options:{},I:Qq,O:dq},{name:"iceCandidate",options:{},I:Zq,O:dq}]),pz=new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:Yq,O:ez},{name:"unlockRequest",options:{},I:Xq,O:dq},{name:"gracefulDisconnect",options:{},I:tz,O:dq},{name:"setPrivate",options:{},I:rz,O:dq}]),gz=new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:nz,O:iz},{name:"externalStoreData",options:{},I:Rq,O:Cq},{name:"externalFindClosestNodes",options:{},I:sz,O:oz}]);class mz{_transport;typeName=az.typeName;methods=az.methods;options=az.options;constructor(e){this._transport=e}getClosestPeers(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}getClosestRingPeers(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}ping(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}leaveNotice(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class yz{_transport;typeName=cz.typeName;methods=cz.methods;options=cz.options;constructor(e){this._transport=e}routeMessage(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}forwardMessage(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class bz{_transport;typeName=uz.typeName;methods=uz.methods;options=uz.options;constructor(e){this._transport=e}routeRequest(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class wz{_transport;typeName=lz.typeName;methods=lz.methods;options=lz.options;constructor(e){this._transport=e}storeData(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}replicateData(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class vz{_transport;typeName=hz.typeName;methods=hz.methods;options=hz.options;constructor(e){this._transport=e}sendResponse(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Ez{_transport;typeName=dz.typeName;methods=dz.methods;options=dz.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Az{_transport;typeName=fz.typeName;methods=fz.methods;options=fz.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}rtcOffer(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}rtcAnswer(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}iceCandidate(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class Sz{_transport;typeName=pz.typeName;methods=pz.methods;options=pz.options;constructor(e){this._transport=e}lockRequest(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}unlockRequest(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}gracefulDisconnect(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}setPrivate(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class kz{_transport;typeName=gz.typeName;methods=gz.methods;options=gz.options;constructor(e){this._transport=e}externalFetchData(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}externalStoreData(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}externalFindClosestNodes(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}const Rz={connect:!0,sendIfStopped:!1,bufferWhileConnecting:!0};class Cz extends WF{targetDescriptor;sourceDescriptor;clientId;connect;sendIfStopped;bufferWhileConnecting;incomingSourceDescriptor}class Iz extends nU{ownServiceId;constructor(e,t,r){super(r),this.ownServiceId=e,this.setOutgoingMessageListener(((e,r,n)=>{let i;i=n.targetDescriptor?n.targetDescriptor:n.incomingSourceDescriptor;const s={messageId:xF(),serviceId:this.ownServiceId,body:{oneofKind:"rpcMessage",rpcMessage:e},targetDescriptor:i},o=void 0!==e.header.response?{connect:!1,sendIfStopped:!0,bufferWhileConnecting:!0}:{connect:n?.connect??Rz.connect,sendIfStopped:n?.sendIfStopped??Rz.sendIfStopped,bufferWhileConnecting:n?.bufferWhileConnecting??Rz.bufferWhileConnecting};return t(s,o)}))}handleMessageFromPeer(e){if(e.serviceId===this.ownServiceId&&"rpcMessage"===e.body.oneofKind){const t=new Cz;t.incomingSourceDescriptor=e.sourceDescriptor,this.handleIncomingMessage(e.body.rpcMessage,t)}}}class Pz{localLocks=new Map;remoteLocks=new Map;weakLocks=new Map;remotePrivateConnections=new Set;getLocalLockedConnectionCount(){return this.localLocks.size}getRemoteLockedConnectionCount(){return this.remoteLocks.size}getWeakLockedConnectionCount(){return this.weakLocks.size}isLocalLocked(e,t){return void 0===t?this.localLocks.has(e):this.localLocks.has(e)&&this.localLocks.get(e).has(t)}isRemoteLocked(e,t){return void 0===t?this.remoteLocks.has(e):!(!this.remoteLocks.has(e)||!this.remoteLocks.get(e).has(t))}isWeakLocked(e){return this.weakLocks.has(e)}isLocked(e){return this.isLocalLocked(e)||this.isRemoteLocked(e)||this.isWeakLocked(e)}addLocalLocked(e,t){this.localLocks.has(e)||this.localLocks.set(e,new Set),this.localLocks.get(e).add(t)}addRemoteLocked(e,t){this.remoteLocks.has(e)||this.remoteLocks.set(e,new Set),this.remoteLocks.get(e).add(t)}addWeakLocked(e,t){this.weakLocks.has(e)||this.weakLocks.set(e,new Set),this.weakLocks.get(e).add(t)}removeLocalLocked(e,t){this.localLocks.has(e)&&(this.localLocks.get(e)?.delete(t),0===this.localLocks.get(e)?.size&&this.localLocks.delete(e))}removeRemoteLocked(e,t){this.remoteLocks.has(e)&&(this.remoteLocks.get(e)?.delete(t),0===this.remoteLocks.get(e)?.size&&this.remoteLocks.delete(e))}removeWeakLocked(e,t){this.weakLocks.has(e)&&(this.weakLocks.get(e)?.delete(t),0===this.weakLocks.get(e)?.size&&this.weakLocks.delete(e))}addPrivate(e){this.remotePrivateConnections.add(e)}removePrivate(e){this.remotePrivateConnections.delete(e)}getPrivateConnections(){return this.remotePrivateConnections}isPrivate(e){return this.remotePrivateConnections.has(e)}clearAllLocks(e){this.localLocks.delete(e),this.remoteLocks.delete(e),this.weakLocks.delete(e)}clear(){this.localLocks.clear(),this.remoteLocks.clear(),this.weakLocks.clear()}}const Tz=e=>void 0!==e?Xj(e):"unknown",_z=()=>xF(),Nz=new Bv("ManagedConnection");class Mz extends Sl{connection;connectionId;remotePeerDescriptor;lastUsedTimestamp=Date.now();replacedAsDuplicate=!1;stopped=!1;openedAt=Date.now();bytesSent=0;bytesReceived=0;messagesSent=0;messagesReceived=0;constructor(e,t){super(),this.connectionId=_z(),this.connection=t,t.on("data",(e=>{this.lastUsedTimestamp=Date.now(),this.messagesReceived+=1,this.bytesReceived+=e.length,this.emit("managedData",e,this.getPeerDescriptor())})),t.on("disconnected",(e=>this.onDisconnected(e))),this.lastUsedTimestamp=Date.now(),this.remotePeerDescriptor=e}onDisconnected(e){Nz.trace(Tz(this.remotePeerDescriptor)+" onDisconnected() "+e),this.replacedAsDuplicate||this.emit("disconnected",e),this.removeAllListeners()}replaceAsDuplicate(){Nz.trace(Tz(this.remotePeerDescriptor)+" replaceAsDuplicate"),this.replacedAsDuplicate=!0}send(e){if(this.stopped)throw new hq("ManagedConnection is stopped");this.lastUsedTimestamp=Date.now(),this.messagesSent+=1,this.bytesSent+=e.length,this.connection.send(e)}async close(e){this.stopped||(await this.connection.close(e),this.removeAllListeners())}getNodeId(){return Xj(this.remotePeerDescriptor)}getLastUsedTimestamp(){return this.lastUsedTimestamp}getPeerDescriptor(){return this.remotePeerDescriptor}getDiagnosticInfo(){return{remotePeerDescriptor:this.remotePeerDescriptor,lastUsedTimestamp:this.lastUsedTimestamp,replacedAsDuplicate:this.replacedAsDuplicate,stopped:this.stopped,openedAt:this.openedAt,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived}}}var xz;!function(e){e.WEBSOCKET_SERVER="websocket-server",e.WEBSOCKET_CLIENT="websocket-client",e.WEBRTC="webrtc",e.SIMULATOR_SERVER="simulator-server",e.SIMULATOR_CLIENT="simulator-client"}(xz||(xz={}));const Oz=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8"].map((e=>uU.parseCIDR(e)));function Dz(e){if(uU.IPv4.isValid(e)){const t=uU.IPv4.parse(e);for(const e of Oz)if(t.match(e))return!0}return!1}const Bz=e=>{const t="localhost"===e.host||Dz(e.host);return e.tls||t},Lz=(e,t)=>t.websocket&&(e.type!==bq.BROWSER||Bz(t.websocket))?xz.WEBSOCKET_CLIENT:e.websocket&&(t.type!==bq.BROWSER||Bz(e.websocket))?xz.WEBSOCKET_SERVER:xz.WEBRTC,Fz=5e3,Uz=(e,t)=>{const r=Lz(e,t);return r===xz.WEBSOCKET_CLIENT?5e3:r===xz.WEBSOCKET_SERVER?7500:(xz.WEBRTC,1e4)};class jz{localPeerDescriptor;remotePeerDescriptor;client;timeout;constructor(e,t,r,n,i){this.localPeerDescriptor=e,this.remotePeerDescriptor=t,this.client=iU(new n(r.getRpcClientTransport())),this.timeout=i}getPeerDescriptor(){return this.remotePeerDescriptor}getLocalPeerDescriptor(){return this.localPeerDescriptor}getClient(){return this.client}formDhtRpcOptions(e){return{sourceDescriptor:this.localPeerDescriptor,targetDescriptor:this.remotePeerDescriptor,timeout:this.timeout??Uz(this.localPeerDescriptor,this.remotePeerDescriptor),...e}}}const qz=new Bv("ConnectionLockRpcRemote");class zz extends jz{async lockRequest(e){qz.trace(`Requesting locked connection to ${Xj(this.getPeerDescriptor())}`);const t={lockId:e},r=this.formDhtRpcOptions();try{return(await this.getClient().lockRequest(t,r)).accepted}catch(e){return qz.debug("Connection lock rejected",{err:e}),!1}}unlockRequest(e){qz.trace(`Requesting connection to be unlocked from ${Xj(this.getPeerDescriptor())}`);const t={lockId:e},r=this.formDhtRpcOptions({notification:!0});this.getClient().unlockRequest(t,r).catch((e=>{qz.trace("failed to send unlockRequest")}))}async gracefulDisconnect(e){qz.trace(`Notifying a graceful disconnect to ${Xj(this.getPeerDescriptor())}`);const t={disconnectMode:e},r=this.formDhtRpcOptions({connect:!1,sendIfStopped:!0,timeout:2e3});await this.getClient().gracefulDisconnect(t,r)}async setPrivate(e){qz.trace(`Setting isPrivate: ${e} for ${Xj(this.getPeerDescriptor())}`);const t={isPrivate:e},r=this.formDhtRpcOptions({connect:!1,notification:!0});await this.getClient().setPrivate(t,r)}}const Kz=new Bv("ConnectionLockRpcLocal");class Gz{options;constructor(e){this.options=e}async lockRequest(e,t){const r=t.incomingSourceDescriptor;if(eq(r,this.options.getLocalPeerDescriptor())){return{accepted:!1}}const n=Xj(r);this.options.addRemoteLocked(n,e.lockId);return{accepted:!0}}async unlockRequest(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.removeRemoteLocked(n,e.lockId),{}}async gracefulDisconnect(e,t){const r=t.incomingSourceDescriptor;return Kz.trace(Tz(r)+" received gracefulDisconnect notice"),e.disconnectMode===Aq.LEAVING?await this.options.closeConnection(r,!0,"graceful leave notified"):await this.options.closeConnection(r,!1,"graceful disconnect notified"),{}}async setPrivate(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.setPrivate(n,e.isPrivate),{}}}const Vz=(e,t)=>Hz(e+","+t)<Hz(t+","+e)?"local":"remote",Hz=e=>_v(e).readInt32LE(0);class $z{buffer=[];deferredPromise=new eb;push(e){return this.buffer.push(e),this.deferredPromise}getBuffer(){return this.buffer}resolve(){this.buffer.length=0,this.deferredPromise.resolve()}reject(){this.buffer.length=0,this.deferredPromise.reject(new hq("Could not send buffered messages"))}}var Wz;!function(e){e.OPEN_INTERNET="open_internet",e.UNKNOWN="unknown"}(Wz||(Wz={}));const Jz=new Bv("ConnectionManager");var Qz;!function(e){e.IDLE="idle",e.RUNNING="running",e.STOPPING="stopping",e.STOPPED="stopped"}(Qz||(Qz={}));const Zz="system/connection-manager";class Yz extends Sl{options;metricsContext;duplicateMessageDetector=new nq(1e4);metrics;locks=new Pz;endpoints=new Map;connectorFacade;rpcCommunicator;disconnectorIntervalRef;state=Qz.IDLE;privateClientMode=!1;constructor(e){super(),this.options=e,this.onData=this.onData.bind(this),this.send=this.send.bind(this),this.onNewConnection=this.onNewConnection.bind(this),this.metricsContext=this.options.metricsContext??new $v,this.metrics={sendMessagesPerSecond:new Hv,sendBytesPerSecond:new Hv,receiveMessagesPerSecond:new Hv,receiveBytesPerSecond:new Hv,connectionAverageCount:new Gv(0),connectionTotalFailureCount:new qv},this.metricsContext.addMetrics("node",this.metrics),this.connectorFacade=this.options.createConnectorFacade(),this.send=this.send.bind(this),this.rpcCommunicator=new Iz(Zz,this.send,{rpcRequestTimeout:1e4});const t=new Gz({addRemoteLocked:(e,t)=>this.locks.addRemoteLocked(e,t),removeRemoteLocked:(e,t)=>this.locks.removeRemoteLocked(e,t),closeConnection:(e,t,r)=>this.closeConnection(e,t,r),getLocalPeerDescriptor:()=>this.getLocalPeerDescriptor(),setPrivate:(e,t)=>{this.options.allowIncomingPrivateConnections?t?this.locks.addPrivate(e):this.locks.removePrivate(e):Jz.debug(`node ${e} attemted to set a connection as private, but it is not allowed`)}});this.rpcCommunicator.registerRpcMethod(Yq,ez,"lockRequest",((e,r)=>t.lockRequest(e,r))),this.rpcCommunicator.registerRpcNotification(Xq,"unlockRequest",((e,r)=>t.unlockRequest(e,r))),this.rpcCommunicator.registerRpcNotification(tz,"gracefulDisconnect",((e,r)=>t.gracefulDisconnect(e,r))),this.rpcCommunicator.registerRpcNotification(rz,"setPrivate",((e,r)=>t.setPrivate(e,r)))}garbageCollectConnections(e,t){if(this.endpoints.size<=e)return;const r=new rq({referenceId:Xj(this.getLocalPeerDescriptor()),maxSize:1e5,allowToContainReferenceId:!1});this.endpoints.forEach((e=>{if(e.connected){const n=e.connection,i=n.getNodeId();!this.locks.isLocked(i)&&!this.locks.isPrivate(i)&&Date.now()-n.getLastUsedTimestamp()>t&&(Jz.trace("disconnecting in timeout interval: "+Tz(n.getPeerDescriptor())),r.addContact(n))}}));const n=r.getFurthestContacts(this.endpoints.size-e);for(const e of n){const t=e.getPeerDescriptor();Jz.trace("garbageCollecting "+Xj(t)),this.gracefullyDisconnectAsync(t,Aq.NORMAL).catch((e=>{}))}}async start(){if(this.state===Qz.RUNNING||this.state===Qz.STOPPED)throw new cq(`Cannot start already ${this.state} module`);this.state=Qz.RUNNING,Jz.trace("Starting ConnectionManager..."),await this.connectorFacade.start((e=>this.onNewConnection(e)),(e=>this.hasConnection(e)),this),this.disconnectorIntervalRef=setInterval((()=>{Jz.trace("disconnectorInterval");this.garbageCollectConnections(this.options.maxConnections??80,2e4)}),5e3)}async stop(){this.state!==Qz.STOPPED&&this.state!==Qz.STOPPING&&(this.state=Qz.STOPPING,Jz.trace("Stopping ConnectionManager"),this.disconnectorIntervalRef&&clearInterval(this.disconnectorIntervalRef),await Promise.all(Array.from(this.endpoints.values()).map((async e=>{if(e.connected)try{await this.gracefullyDisconnectAsync(e.connection.getPeerDescriptor(),Aq.LEAVING)}catch(e){Jz.error(e)}else{const t=e.connection;Jz.trace("handshake of connection not completed, force-closing");const r=eE(t,"disconnected",2e3);t.close(!0);try{await r,Jz.trace("resolving after receiving disconnected event from non-handshaked connection")}catch(t){e.buffer.reject(),Jz.trace("force-closing non-handshaked connection timed out "+t)}}}))),await this.connectorFacade.stop(),this.state=Qz.STOPPED,this.rpcCommunicator.stop(),this.duplicateMessageDetector.clear(),this.locks.clear(),this.removeAllListeners())}getLocalLockedConnectionCount(){return this.locks.getLocalLockedConnectionCount()}getRemoteLockedConnectionCount(){return this.locks.getRemoteLockedConnectionCount()}getWeakLockedConnectionCount(){return this.locks.getWeakLockedConnectionCount()}async send(e,t=Rz){if((this.state===Qz.STOPPED||this.state===Qz.STOPPING)&&!t.sendIfStopped)return;const r=e.targetDescriptor;if(this.isConnectionToSelf(r))throw new uq("Cannot send to self");const n=Xj(r);Jz.trace(`Sending message to: ${n}`),e={...e,sourceDescriptor:this.getLocalPeerDescriptor()};let i=this.endpoints.get(n)?.connection;if(!i&&t.connect)i=this.connectorFacade.createConnection(r),this.onNewConnection(i);else if(!i||i&&!this.endpoints.get(n).connected&&!t.connect)throw new hq("No connection to target, connect flag is false");const s=Hq.toBinary(e);if(this.metrics.sendBytesPerSecond.record(s.byteLength),this.metrics.sendMessagesPerSecond.record(1),this.endpoints.get(n).connected)i.send(s);else if(t.bufferWhileConnecting)return this.endpoints.get(n).buffer.push(s)}isConnectionToSelf(e){return eq(e,this.getLocalPeerDescriptor())||this.isOwnWebsocketServer(e)}isOwnWebsocketServer(e){const t=this.getLocalPeerDescriptor();return void 0!==e.websocket&&void 0!==t.websocket&&(e.websocket.port===t.websocket.port&&e.websocket.host===t.websocket.host)}getLocalPeerDescriptor(){return this.connectorFacade.getLocalPeerDescriptor()}hasConnection(e){return this.getConnections().some((t=>Xj(t)==e))}getConnectionCount(){return this.getConnections().length}hasLocalLockedConnection(e){return this.locks.isLocalLocked(e)}hasRemoteLockedConnection(e){return this.locks.isRemoteLocked(e)}handleMessage(e){const t=e.body.oneofKind;Jz.trace("Received message of type "+t),"rpcMessage"===t?this.duplicateMessageDetector.isMostLikelyDuplicate(e.messageId)?Jz.trace("handleMessage filtered duplicate "+Xj(e.sourceDescriptor)+" "+e.serviceId+" "+e.messageId):(this.duplicateMessageDetector.add(e.messageId),e.serviceId===Zz?this.rpcCommunicator?.handleMessageFromPeer(e):(Jz.trace('emit "message" '+Xj(e.sourceDescriptor)+" "+e.serviceId+" "+e.messageId),this.emit("message",e))):Jz.trace("Filtered out non-RPC message of type "+t)}onData(e,t){if(this.state===Qz.STOPPED)return;let r;this.metrics.receiveBytesPerSecond.record(e.byteLength),this.metrics.receiveMessagesPerSecond.record(1);try{r=Hq.fromBinary(e)}catch(e){return void Jz.debug(`Parsing incoming data into Message failed: ${e}`)}r.sourceDescriptor=t;try{this.handleMessage(r)}catch(e){Jz.debug(`Handling incoming data failed: ${e}`)}}onConnected(e,t){const r=new Mz(e,t);r.on("managedData",this.onData),r.once("disconnected",(t=>this.onDisconnected(e,t)));const n=Xj(e),i=this.endpoints.get(n),s=i.buffer,o=i.connection,a=s.getBuffer();for(;a.length>0;)Jz.trace("emptying buffer"),r.send(a.shift());s.resolve(),o.destroy(),this.endpoints.set(n,{connected:!0,connection:r}),this.privateClientMode&&this.setPrivateForConnection(e,this.privateClientMode).catch((()=>{})),this.emit("connected",e),this.onConnectionCountChange()}onDisconnected(e,t){const r=Xj(e);Jz.trace(r+" onDisconnected() gracefulLeave: "+t);const n=this.endpoints.get(r);n&&(this.locks.clearAllLocks(r),!1===n.connected&&n.buffer.reject(),this.endpoints.delete(r),Jz.trace(r+" deleted connection in onDisconnected() gracefulLeave: "+t),this.emit("disconnected",e,t),this.onConnectionCountChange())}onNewConnection(e){return this.state!==Qz.STOPPED&&(Jz.trace("onNewConnection()"),!!this.acceptNewConnection(e)&&(e.once("connected",((e,t)=>this.onConnected(e,t))),e.once("disconnected",(t=>this.onDisconnected(e.getPeerDescriptor(),t))),!0))}acceptNewConnection(e){const t=Xj(e.getPeerDescriptor());if(Jz.trace(t+" acceptNewConnection()"),this.endpoints.has(t)){if("remote"===Vz(Xj(this.getLocalPeerDescriptor()),t)){let r;const n=this.endpoints.get(t);this.endpoints.get(t).connected?(Jz.debug("replacing connected connection",{nodeId:t}),r=new $z):r=n.buffer;const i=n.connection;return Jz.trace("replaced: "+t),i.replaceAsDuplicate(),this.endpoints.set(t,{connected:!1,connection:e,buffer:r}),!0}return!1}return Jz.trace(t+" added to connections at acceptNewConnection"),this.endpoints.set(t,{connected:!1,buffer:new $z,connection:e}),!0}async closeConnection(e,t,r){const n=Xj(e);if(Jz.trace(n+" closeConnection() "+r),this.locks.clearAllLocks(n),this.endpoints.has(n)){const e=this.endpoints.get(n).connection;await e.close(t)}else Jz.trace(n+" closeConnection() this.endpoints did not have the id"),this.emit("disconnected",e,!1)}lockConnection(e,t){if(this.state===Qz.STOPPED||eq(e,this.getLocalPeerDescriptor()))return;const r=Xj(e),n=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);this.locks.addLocalLocked(r,t),n.lockRequest(t).then((e=>Jz.trace("LockRequest successful"))).catch((e=>{Jz.debug(e)}))}unlockConnection(e,t){if(this.state===Qz.STOPPED||eq(e,this.getLocalPeerDescriptor()))return;const r=Xj(e);this.locks.removeLocalLocked(r,t);const n=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);this.endpoints.has(r)&&n.unlockRequest(t)}weakLockConnection(e,t){this.state!==Qz.STOPPED&&e!==Xj(this.getLocalPeerDescriptor())&&this.locks.addWeakLocked(e,t)}weakUnlockConnection(e,t){this.state!==Qz.STOPPED&&e!==Xj(this.getLocalPeerDescriptor())&&this.locks.removeWeakLocked(e,t)}async enablePrivateClientMode(){this.privateClientMode=!0,await Promise.all(this.getConnectedEndpoints().map((e=>{const t=e.connection.getPeerDescriptor();return this.setPrivateForConnection(t,!0)})))}async disablePrivateClientMode(){this.privateClientMode=!1,await Promise.all(this.getConnectedEndpoints().map((e=>{const t=e.connection.getPeerDescriptor();return this.setPrivateForConnection(t,!1)})))}getConnectedEndpoints(){return Array.from(this.endpoints.values()).filter((e=>e.connected))}isPrivateClientMode(){return this.privateClientMode}async setPrivateForConnection(e,t){const r=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);await r.setPrivate(t)}async gracefullyDisconnectAsync(e,t){const r=this.endpoints.get(Xj(e));if(r)if(r.connected){const n=r.connection,i=new Promise(((e,t)=>{eE(n,"disconnected",2e3).then((()=>{Jz.trace("disconnected event received in gracefullyDisconnectAsync()")})).catch((e=>{Jz.trace("force-closing connection after timeout "+e),n.close(!0)})).finally((()=>{Jz.trace("resolving after receiving disconnected event"),e()}))}));await Promise.all([i,this.doGracefullyDisconnectAsync(e,t)])}else r.connection.close(!0);else Jz.debug("gracefullyDisconnectedAsync() tried on a non-existing connection")}async doGracefullyDisconnectAsync(e,t){const r=Xj(e);Jz.trace(r+" gracefullyDisconnectAsync()");const n=new zz(this.getLocalPeerDescriptor(),e,this.rpcCommunicator,Sz);try{await n.gracefulDisconnect(t)}catch(e){Jz.trace(r+" remote.gracefulDisconnect() failed"+e)}}getConnections(){return Array.from(this.endpoints.values()).map((e=>e)).filter((e=>e.connected&&!this.locks.isPrivate(Xj(e.connection.getPeerDescriptor())))).map((e=>e.connection.getPeerDescriptor()))}onConnectionCountChange(){this.metrics.connectionAverageCount.record(this.endpoints.size)}getDiagnosticInfo(){return{connections:Array.from(this.endpoints.values()).filter((e=>e.connected)).map((e=>e.connection)).map((e=>e.getDiagnosticInfo())),connectionCount:this.endpoints.size}}}new Bv("SimulatorConnection");const Xz="1.1",eK=e=>{const t=tK(Xz).major,r=tK(e)?.major;return!(void 0===r||r<t)},tK=e=>{const t=e.split(".");if(2===t.length){const e=t.map((e=>Number(e)));if(!e.some((e=>isNaN(e))))return{major:e[0],minor:e[1]}}};var rK="103.6.0-rc.0";const nK=new Bv("Handshaker"),iK=(e,t,r,n)=>{const i=new aK(e,r),s=()=>{i.stop(),r.off("disconnected",u),r.off("connected",c),i.off("handshakeCompleted",a),i.off("handshakeFailed",o),t.off("disconnected",l)},o=e=>{e!==Eq.INVALID_TARGET_PEER_DESCRIPTOR&&e!==Eq.UNSUPPORTED_PROTOCOL_VERSION||(t.close(!1),s())},a=e=>{nK.trace("handshake completed for outgoing connection, "+Xj(e)),t.onHandshakeCompleted(r),s()},c=()=>i.sendHandshakeRequest(n),u=e=>{t.close(e),s()},l=()=>{r.close(!1),s()};return i.once("handshakeFailed",o),i.once("handshakeCompleted",a),r.once("connected",c),r.once("disconnected",u),t.once("disconnected",l),i},sK=(e,t,r,n)=>{r.sendHandshakeResponse(n),t.destroy(),e.destroy()},oK=(e,t,r)=>{e.sendHandshakeResponse(),t.onHandshakeCompleted(r)};let aK=class extends Sl{static HANDSHAKER_SERVICE_ID="system/handshaker";localPeerDescriptor;connection;onDataListener;constructor(e,t){super(),this.localPeerDescriptor=e,this.connection=t,this.onDataListener=e=>this.onData(e),this.connection.on("data",this.onDataListener)}onData(e){try{const t=Hq.fromBinary(e);if("handshakeRequest"===t.body.oneofKind){nK.trace("handshake request received");const e=t.body.handshakeRequest;this.emit("handshakeRequest",e.sourcePeerDescriptor,e.protocolVersion,e.targetPeerDescriptor)}if("handshakeResponse"===t.body.oneofKind){nK.trace("handshake response received");const e=t.body.handshakeResponse,r=eK(e.protocolVersion)?e.error:Eq.UNSUPPORTED_PROTOCOL_VERSION;void 0!==r?this.emit("handshakeFailed",r):this.emit("handshakeCompleted",e.sourcePeerDescriptor)}}catch(e){nK.debug("error while parsing handshake message",e)}}sendHandshakeRequest(e){const t=((e,t)=>{const r={sourcePeerDescriptor:e,targetPeerDescriptor:t,protocolVersion:Xz,applicationVersion:rK};return{serviceId:aK.HANDSHAKER_SERVICE_ID,messageId:xF(),body:{oneofKind:"handshakeRequest",handshakeRequest:r}}})(this.localPeerDescriptor,e);this.connection.send(Hq.toBinary(t)),nK.trace("handshake request sent")}sendHandshakeResponse(e){const t=((e,t)=>{const r={sourcePeerDescriptor:e,error:t,protocolVersion:Xz,applicationVersion:rK};return{serviceId:aK.HANDSHAKER_SERVICE_ID,messageId:xF(),body:{oneofKind:"handshakeResponse",handshakeResponse:r}}})(this.localPeerDescriptor,e);this.connection.send(Hq.toBinary(t)),nK.trace("handshake response sent")}stop(){this.connection.off("data",this.onDataListener),this.removeAllListeners()}};const cK=new Bv("PendingConnection");class uK extends Sl{connectingAbortController=new AbortController;remotePeerDescriptor;replacedAsDuplicate=!1;stopped=!1;constructor(e,t=15e3){super(),this.remotePeerDescriptor=e,Yy((()=>{this.close(!1)}),t,this.connectingAbortController.signal)}replaceAsDuplicate(){cK.trace(Tz(this.remotePeerDescriptor)+" replaceAsDuplicate"),this.replacedAsDuplicate=!0}onHandshakeCompleted(e){this.replacedAsDuplicate||this.emit("connected",this.remotePeerDescriptor,e)}close(e){this.stopped||(this.stopped=!0,this.connectingAbortController.abort(),this.replacedAsDuplicate||this.emit("disconnected",e))}destroy(){this.stopped||(this.stopped=!0,this.connectingAbortController.abort(),this.removeAllListeners())}getPeerDescriptor(){return this.remotePeerDescriptor}}new Bv("SimulatorConnector");class lK extends Iz{transport;messageListener;disconnectedListener;constructor(e,t,r){super(e,((e,r)=>t.send(e,r)),r),this.messageListener=e=>{this.handleMessageFromPeer(e)},this.disconnectedListener=e=>{this.getRequestIds((t=>eq(e,t.getCallContext().targetDescriptor))).forEach((e=>this.handleClientError(e,new qF.Disconnected("Peer disconnected"))))},this.transport=t,t.on("message",this.messageListener),t.on("disconnected",this.disconnectedListener)}destroy(){this.transport.off("message",this.messageListener),this.transport.off("disconnected",this.disconnectedListener),this.stop()}}const hK="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;var dK;!function(e){e.OFFER="offer",e.ANSWER="answer"}(dK||(dK={}));var fK;!function(e){e.DISCONNECTED="disconnected",e.FAILED="failed",e.CLOSED="closed"}(fK||(fK={}));const pK=new Bv("DirectWebrtcConnection (browser)");let gK;const mK=new Promise((e=>{gK=e}));if(hK){const e=t=>{if("streamr-webrtc-bridge-port"===t.data?.type&&t.data.port){const r=wU(t.data.port);gK(r),self.removeEventListener("message",e)}};self.addEventListener("message",e)}var yK;!function(e){e.DISCONNECTED="disconnected",e.FAILED="failed",e.CLOSED="closed"}(yK||(yK={}));const bK=new Bv("WorkerWebrtcConnection");const wK=hK?class extends Sl{connectionId;connectionType=xz.WEBRTC;iceServers;bufferThresholdHigh;bufferThresholdLow;dataChannel;bridge;closed=!1;connected=!1;earlyTimeout;messageQueue=[];startPromise;constructor(e){super(),this.connectionId=_z(),this.iceServers=e.iceServers??[],this.bufferThresholdHigh=e.bufferThresholdHigh??2**17,this.bufferThresholdLow=e.bufferThresholdLow??32768,this.earlyTimeout=setTimeout((()=>{this.doClose(!1,"timed out due to remote descriptor not being set")}),5e3)}start(e){this.startPromise=this.doStart(e),this.startPromise.catch((e=>{bK.warn("Failed to start worker WebRTC connection",{err:e}),this.doClose(!1,"Failed to start")}))}async doStart(e){this.bridge=await mK;const t=this.iceServers.map((({url:e,port:t,username:r,password:n})=>({urls:`${e}:${t}`,username:r,credential:n})));await this.bridge.start(this.connectionId,t,e,IU({onLocalCandidate:(e,t)=>{this.closed||this.emit("localCandidate",e,t)},onLocalDescription:(e,t)=>{this.closed||this.emit("localDescription",e,t)},onConnectionStateChange:e=>{e!==yK.CLOSED&&e!==yK.DISCONNECTED&&e!==yK.FAILED||this.doClose(!1)},onDataChannel:e=>{this.closed||(this.setupDataChannel(e),"open"===e.readyState&&this.onDataChannelOpen())}}))}async setRemoteDescription(e,t){if(this.startPromise&&await this.startPromise,!this.bridge||this.closed)return;await this.bridge.setRemoteDescription(this.connectionId,e,t)&&clearTimeout(this.earlyTimeout)}addRemoteCandidate(e,t){this.doAddRemoteCandidate(e,t).catch((e=>{bK.warn("Failed to add remote candidate via bridge",{err:e})}))}async doAddRemoteCandidate(e,t){this.startPromise&&await this.startPromise,this.bridge&&!this.closed&&await this.bridge.addRemoteCandidate(this.connectionId,e,t)}isOpen(){return this.connected}async close(e,t){this.doClose(e,t)}destroy(){this.removeAllListeners(),this.doClose(!1)}send(e){this.connected&&this.dataChannel?this.dataChannel.bufferedAmount>this.bufferThresholdHigh?this.messageQueue.push(e):this.dataChannel.send(e):this.closed||this.messageQueue.push(e)}setConnectionId(e){const t=this.connectionId;this.connectionId=e,this.bridge&&t!==e&&this.bridge.renameConnection(t,e).catch((()=>{}))}setupDataChannel(e){this.dataChannel=e,this.dataChannel.binaryType="arraybuffer",this.dataChannel.bufferedAmountLowThreshold=this.bufferThresholdLow,e.onopen=()=>{bK.trace("dc.onOpen (worker)"),this.onDataChannelOpen()},e.onclose=()=>{bK.trace("dc.onClosed (worker)"),this.doClose(!1)},e.onerror=e=>{bK.warn("Data channel error (worker)",{err:e})},e.onmessage=e=>{bK.trace("dc.onmessage (worker)"),this.emit("data",new Uint8Array(e.data))},e.onbufferedamountlow=()=>{for(bK.trace("dc.onBufferedAmountLow (worker)");this.messageQueue.length>0&&this.dataChannel.bufferedAmount<this.bufferThresholdHigh;){const e=this.messageQueue.shift();this.dataChannel.send(e)}}}onDataChannelOpen(){this.connected=!0,this.flushMessageQueue(),this.emit("connected")}flushMessageQueue(){for(;this.messageQueue.length>0&&this.dataChannel&&this.dataChannel.bufferedAmount<this.bufferThresholdHigh;){const e=this.messageQueue.shift();this.dataChannel.send(e)}}doClose(e,t){if(!this.closed){if(this.closed=!0,this.connected=!1,this.messageQueue.length=0,clearTimeout(this.earlyTimeout),this.stopListening(),this.emit("disconnected",e,void 0,t),this.removeAllListeners(),void 0!==this.dataChannel)try{this.dataChannel.close()}catch(e){bK.warn("Failed to close data channel (worker)",{err:e})}this.dataChannel=void 0,this.bridge?.close(this.connectionId).catch((()=>{}))}}stopListening(){void 0!==this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onclose=null,this.dataChannel.onerror=null,this.dataChannel.onbufferedamountlow=null,this.dataChannel.onmessage=null)}}:class extends Sl{connectionId;connectionType=xz.WEBRTC;lastState="connecting";iceServers;peerConnection;bufferThresholdHigh=2**17;bufferThresholdLow=32768;dataChannel;makingOffer=!1;isOffering=!1;closed=!1;earlyTimeout;messageQueue=[];constructor(e){super(),this.connectionId=_z(),this.iceServers=e.iceServers??[],this.earlyTimeout=setTimeout((()=>{this.doClose(!1,"timed out due to remote descriptor not being set")}),5e3)}start(e){this.isOffering=e;const t=this.iceServers.map((({url:e,port:t,username:r,password:n})=>({urls:`${e}:${t}`,username:r,credential:n})));if(this.peerConnection=new RTCPeerConnection({iceServers:t}),this.peerConnection.onicecandidate=e=>{null!==e.candidate&&null!==e.candidate.sdpMid&&this.emit("localCandidate",e.candidate.candidate,e.candidate.sdpMid)},this.peerConnection.onicegatheringstatechange=()=>{pK.trace(`conn.onGatheringStateChange: ${this.peerConnection?.iceGatheringState}`)},this.peerConnection.onconnectionstatechange=()=>this.onStateChange(),e){this.peerConnection.onnegotiationneeded=async()=>{if(void 0!==this.peerConnection){this.makingOffer=!0;try{await this.peerConnection.setLocalDescription()}catch(e){pK.warn("Failed to set local description",{err:e})}null!==this.peerConnection.localDescription&&this.emit("localDescription",this.peerConnection.localDescription?.sdp,this.peerConnection.localDescription?.type)}this.makingOffer=!1};const e=this.peerConnection.createDataChannel("streamrDataChannel");this.setupDataChannel(e)}else this.peerConnection.ondatachannel=e=>{this.setupDataChannel(e.channel)}}async setRemoteDescription(e,t){const r=t.toLowerCase()===dK.OFFER&&(this.makingOffer||"stable"!=this.peerConnection?.signalingState);if(!(this.isOffering&&r)){try{await(this.peerConnection?.setRemoteDescription({sdp:e,type:t.toLowerCase()})),clearTimeout(this.earlyTimeout)}catch(e){pK.warn("Failed to set remote description",{err:e})}if(t.toLowerCase()===dK.OFFER&&void 0!==this.peerConnection){try{await this.peerConnection.setLocalDescription()}catch(e){pK.warn("Failed to set local description",{err:e})}null!==this.peerConnection.localDescription&&this.emit("localDescription",this.peerConnection.localDescription.sdp,this.peerConnection.localDescription.type)}}}addRemoteCandidate(e,t){this.peerConnection?.addIceCandidate({candidate:e,sdpMid:t}).catch((e=>{pK.warn("Failed to add ICE candidate",{err:e})}))}isOpen(){return"connected"===this.lastState}async close(e,t){this.doClose(e,t)}doClose(e,t){if(!this.closed){if(this.closed=!0,this.lastState="closed",clearTimeout(this.earlyTimeout),this.stopListening(),this.emit("disconnected",e,void 0,t),this.removeAllListeners(),void 0!==this.dataChannel)try{this.dataChannel.close()}catch(e){pK.warn("Failed to close data channel",{err:e})}if(this.dataChannel=void 0,void 0!==this.peerConnection)try{this.peerConnection.close()}catch(e){pK.warn("Failed to close connection",{err:e})}this.peerConnection=void 0}}destroy(){this.removeAllListeners(),this.doClose(!1)}send(e){"connected"===this.lastState?this.dataChannel.bufferedAmount>this.bufferThresholdHigh?this.messageQueue.push(e):this.dataChannel?.send(e):pK.warn("Tried to send on a connection with last state "+this.lastState)}setupDataChannel(e){this.dataChannel=e,this.dataChannel.binaryType="arraybuffer",this.dataChannel.bufferedAmountLowThreshold=this.bufferThresholdLow,e.onopen=()=>{pK.trace("dc.onOpen"),this.onDataChannelOpen()},e.onclose=()=>{pK.trace("dc.onClosed"),this.doClose(!1)},e.onerror=e=>{pK.warn("Data channel error",{err:e})},e.onmessage=e=>{pK.trace("dc.onmessage"),this.emit("data",new Uint8Array(e.data))},e.onbufferedamountlow=()=>{for(pK.trace("dc.onBufferedAmountLow");this.messageQueue.length>0&&this.dataChannel.bufferedAmount<this.bufferThresholdHigh;){const e=this.messageQueue.shift();this.dataChannel.send(e)}}}stopListening(){void 0!==this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onclose=null,this.dataChannel.onerror=null,this.dataChannel.onbufferedamountlow=null,this.dataChannel.onmessage=null),void 0!==this.peerConnection&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.onicecandidate=null,this.peerConnection.onicegatheringstatechange=null,this.peerConnection.onnegotiationneeded=null,this.peerConnection.ondatachannel=null)}onDataChannelOpen(){this.lastState="connected",this.emit("connected")}onStateChange(){this.peerConnection.connectionState!==fK.CLOSED&&this.peerConnection.connectionState!==fK.DISCONNECTED&&this.peerConnection.connectionState!==fK.FAILED||this.doClose(!1)}setConnectionId(e){this.connectionId=e}},vK=new Bv("WebrtcConnectorRpcRemote");class EK extends jz{requestConnection(){const e=this.formDhtRpcOptions({notification:!0});this.getClient().requestConnection({},e).catch((e=>{vK.trace("Failed to send requestConnection")}))}sendRtcOffer(e,t){const r={connectionId:t,description:e},n=this.formDhtRpcOptions();this.getClient().rtcOffer(r,n).catch((e=>{vK.trace("Failed to send rtcOffer")}))}sendRtcAnswer(e,t){const r={connectionId:t,description:e},n=this.formDhtRpcOptions();this.getClient().rtcAnswer(r,n).catch((e=>{vK.trace("Failed to send rtcAnswer")}))}sendIceCandidate(e,t,r){const n={connectionId:r,mid:t,candidate:e},i=this.formDhtRpcOptions();this.getClient().iceCandidate(n,i).catch((e=>{vK.trace("Failed to send iceCandidate")}))}}const AK=new Bv("WebrtcConnectorRpcLocal");class SK{options;constructor(e){this.options=e}async requestConnection(e){const t=e.incomingSourceDescriptor;if(this.options.ongoingConnectAttempts.has(Xj(t)))return{};const r=this.options.connect(t,!1);return this.options.onNewConnection(r),{}}async rtcOffer(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);let i,s;return this.options.ongoingConnectAttempts.has(n)?(s=this.options.ongoingConnectAttempts.get(n).managedConnection,i=this.options.ongoingConnectAttempts.get(n).connection):(s=this.options.connect(r,!0),i=this.options.ongoingConnectAttempts.get(n).connection,this.options.onNewConnection(s)),i.setConnectionId(e.connectionId),i.setRemoteDescription(e.description,"offer"),{}}async rtcAnswer(e,t){const r=t.incomingSourceDescriptor,n=Xj(r),i=this.options.ongoingConnectAttempts.get(n)?.connection;return i?i.connectionId!==e.connectionId?(AK.trace("Ignoring RTC answer due to connectionId mismatch"),{}):(i.setRemoteDescription(e.description,"answer"),{}):{}}async iceCandidate(e,t){const r=t.incomingSourceDescriptor,n=Xj(r),i=this.options.ongoingConnectAttempts.get(n)?.connection;return i?i.connectionId!==e.connectionId?(AK.trace("Ignoring remote candidate due to connectionId mismatch"),{}):(this.isIceCandidateAllowed(e.candidate)&&i.addRemoteCandidate(e.candidate,e.mid),{}):{}}isIceCandidateAllowed(e){if(!this.options.allowPrivateAddresses){const t=function(e){const t=e.split(" ").filter((e=>e.length>0));return t.length>=5&&uU.isValid(t[4])?t[4]:void 0}(e);if(void 0!==t&&Dz(t))return!1}return!0}}const kK=new Bv("WebrtcConnector");class RK{static WEBRTC_CONNECTOR_SERVICE_ID="system/webrtc-connector";rpcCommunicator;ongoingConnectAttempts=new Map;localPeerDescriptor;stopped=!1;options;constructor(e){this.options=e,this.rpcCommunicator=new lK(RK.WEBRTC_CONNECTOR_SERVICE_ID,e.transport,{rpcRequestTimeout:15e3}),this.registerLocalRpcMethods(e)}registerLocalRpcMethods(e){const t=new SK({connect:(e,t)=>this.connect(e,t),onNewConnection:e=>this.options.onNewConnection(e),ongoingConnectAttempts:this.ongoingConnectAttempts,rpcCommunicator:this.rpcCommunicator,getLocalPeerDescriptor:()=>this.localPeerDescriptor,allowPrivateAddresses:e.allowPrivateAddresses??!0});this.rpcCommunicator.registerRpcNotification(Wq,"requestConnection",(async(e,r)=>this.stopped?{}:t.requestConnection(r))),this.rpcCommunicator.registerRpcNotification(Jq,"rtcOffer",(async(e,r)=>this.stopped?{}:t.rtcOffer(e,r))),this.rpcCommunicator.registerRpcNotification(Qq,"rtcAnswer",(async(e,r)=>this.stopped?{}:t.rtcAnswer(e,r))),this.rpcCommunicator.registerRpcNotification(Zq,"iceCandidate",(async(e,r)=>this.stopped?{}:t.iceCandidate(e,r)))}connect(e,t){if(eq(e,this.localPeerDescriptor))throw new uq("Cannot open WebRTC Connection to self");kK.trace(`Opening WebRTC connection to ${Xj(e)}`);const r=Xj(e),n=this.ongoingConnectAttempts.get(r);if(n)return n.managedConnection;const i=this.createConnection(e),s=Xj(this.localPeerDescriptor),o=Xj(e),a="local"===Vz(s,o);let c;const u=new EK(this.localPeerDescriptor,e,this.rpcCommunicator,Az),l=()=>{this.ongoingConnectAttempts.delete(r),i.off("disconnected",l),c.off("disconnected",l),c.off("connected",l)};if(a)c=new uK(e),iK(this.localPeerDescriptor,c,i,e),i.once("localDescription",(e=>{kK.trace("Sending offer to remote peer"),u.sendRtcOffer(e,i.connectionId)}));else{c=new uK(e);const t=((e,t,r)=>{const n=new aK(e,r),i=()=>{n.stop(),t.off("disconnected",s),r.off("disconnected",s)},s=e=>{t.close(e),i()};return n.on("handshakeRequest",(()=>{i()})),r.once("disconnected",s),t.once("disconnected",(()=>{r.close(!1),i()})),n})(this.localPeerDescriptor,c,i);i.once("localDescription",(e=>{u.sendRtcAnswer(e,i.connectionId)})),t.on("handshakeRequest",((e,r)=>{eK(r)?oK(t,c,i):sK(c,i,t,Eq.UNSUPPORTED_PROTOCOL_VERSION),l()}))}return this.ongoingConnectAttempts.set(o,{managedConnection:c,connection:i}),i.on("disconnected",l),c.on("disconnected",l),c.on("connected",l),i.on("localCandidate",((e,t)=>{void 0!==this.options.externalIp&&(e=((e,t)=>{const r=e.split(" ");return"host"===r[7]&&(r[4]=t),r.join(" ")})(e,this.options.externalIp),kK.debug(`onLocalCandidate injected external ip ${e} ${t}`)),u.sendIceCandidate(e,t,i.connectionId)})),i.start(a),t||a||u.requestConnection(),c}createConnection(e){return new wK({remotePeerDescriptor:e,iceServers:this.options.iceServers,bufferThresholdLow:this.options.bufferThresholdLow,bufferThresholdHigh:this.options.bufferThresholdHigh,portRange:this.options.portRange})}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async stop(){kK.trace("stop()"),this.stopped=!0;const e=Array.from(this.ongoingConnectAttempts.values());await Promise.allSettled(e.map((async e=>{e.connection.destroy(),e.managedConnection.close(!1)}))),this.rpcCommunicator.destroy()}}const CK=new Bv("AbstractWebsocketClientConnection");class IK extends Sl{connectionId;connectionType=xz.WEBSOCKET_CLIENT;destroyed=!1;constructor(){super(),this.connectionId=_z()}send(e){this.destroyed?CK.debug("Tried to send() on stopped connection"):1===this.socket?.readyState?(CK.trace(`Sending data with size ${e.byteLength}`),this.socket?.send(e)):CK.debug("Tried to send data on a non-open connection",{id:this.connectionId,readyState:this.socket.readyState,destroyed:this.destroyed})}async close(e){this.emit("disconnected",e,void 0,"close() called"),this.removeAllListeners(),this.destroyed?CK.debug("Tried to close() a stopped connection",{id:this.connectionId}):(CK.trace(`Closing socket for connection ${this.connectionId}`),this.socket?.close(e?3001:void 0))}destroy(){CK.trace("destroy() a connection"),this.destroyed?CK.debug("Tried to destroy() a stopped connection"):(this.removeAllListeners(),this.socket&&(this.stopListening(),this.socket.close(),this.socket=void 0),this.destroyed=!0)}onOpen(){this.destroyed||(CK.trace("WebSocket Client Connected"),1===this.socket?.readyState&&this.emit("connected"))}onMessage(e){this.emit("data",e)}onClose(e,t){this.destroyed||(CK.trace("Websocket Closed"),this.doDisconnect(e,t))}onError(e){this.destroyed||(CK.trace("WebSocket Client error: "+e?.message,{error:e}),this.emit("error",e.name))}doDisconnect(e,t){this.destroyed=!0,this.stopListening(),this.socket=void 0;const r=1001===e||3001===e;this.emit("disconnected",r,e,t),this.removeAllListeners()}}const PK=new Bv("WebsocketClientConnection (browser)");class TK extends IK{socket;connect(e,t){this.destroyed?PK.debug("Tried to connect() a stopped connection"):(this.socket=new FU.w3cwebsocket(e,void 0,void 0,void 0,{rejectUnauthorized:!t}),this.socket.binaryType="arraybuffer",this.socket.onerror=e=>this.onError(e),this.socket.onopen=()=>this.onOpen(),this.socket.onclose=e=>this.onClose(e.code,e.reason),this.socket.onmessage=e=>{this.destroyed||("string"==typeof e.data?PK.debug("Received string data, only binary data is supported"):this.onMessage(new Uint8Array(e.data)))})}stopListening(){this.socket&&(this.socket.onopen=void 0,this.socket.onclose=void 0,this.socket.onerror=void 0,this.socket.onmessage=void 0)}}class _K{options;constructor(e){this.options=e}async requestConnection(e,t){if(this.options.abortSignal.aborted)return{};const r=t.incomingSourceDescriptor;if(!this.options.hasConnection(Xj(r))){const e=this.options.connect(r);this.options.onNewConnection(e)}return{}}}const NK=(e,t)=>(e.tls?"wss://":"ws://")+e.host+":"+e.port+(void 0!==t?"?action="+t:"");class MK{static WEBSOCKET_CONNECTOR_SERVICE_ID="system/websocket-connector";websocketServer;geoIpLocator;localPeerDescriptor;connectingConnections=new Map;abortController=new AbortController;options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new _K({connect:e=>this.connect(e),hasConnection:e=>this.connectingConnections.has(e)||this.options.hasConnection(e),onNewConnection:e=>this.options.onNewConnection(e),abortSignal:this.abortController.signal});this.options.rpcCommunicator.registerRpcNotification($q,"requestConnection",(async(t,r)=>this.abortController.signal.aborted?{}:e.requestConnection(t,r)))}isPossibleToFormConnection(e){return Lz(this.localPeerDescriptor,e)===xz.WEBSOCKET_CLIENT}connect(e){const t=Xj(e),r=this.connectingConnections.get(t);if(r)return r;const n=new TK,i=NK(e.websocket),s=new uK(e);iK(this.localPeerDescriptor,s,n,e),this.connectingConnections.set(t,s);const o=()=>{this.connectingConnections.has(t)&&this.connectingConnections.delete(t),n.off("disconnected",o),s.off("disconnected",o),s.off("connected",o)};return n.on("disconnected",o),s.on("disconnected",o),s.on("connected",o),n.connect(i,!1),s}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async destroy(){this.abortController.abort();Array.from(this.connectingConnections.values()).forEach((e=>e.close(!0))),await(this.websocketServer?.stop()),this.geoIpLocator?.stop()}}class xK extends Sl{constructor(e){super()}async start(){throw new Error("WebsocketServer is not supported in browser environment")}async stop(){throw new Error("WebsocketServer is not supported in browser environment")}updateCertificate(e,t){throw new Error("WebsocketServer is not supported in browser environment")}}const OK=new Bv("AutoCertifierClientFacade");class DK{autoCertifierClient;rpcCommunicator;options;constructor(e){this.options=e,this.rpcCommunicator=new lK("system/auto-certificer",e.transport),this.autoCertifierClient=e.createClientFactory?e.createClientFactory():(()=>{throw new Error("AutoCertifierClient is not supported in browser environment")})(e.configFile,e.url,this.rpcCommunicator,e.wsServerPort)}async start(){this.autoCertifierClient.on("updatedCertificate",(e=>{this.options.setHost(e.fqdn),this.options.updateCertificate(e.certificate,e.privateKey),OK.trace("Updated certificate")})),await Promise.all([eE(this.autoCertifierClient,"updatedCertificate",6e4),this.autoCertifierClient.start()])}stop(){this.autoCertifierClient.stop(),this.rpcCommunicator.destroy()}}const BK=new Bv("connectivityChecker"),LK=async({url:e,allowSelfSignedCertificate:t,timeoutMs:r=1e3})=>{const n=new TK;let i;try{const s=tE(n,["connected","error"],r);n.connect(e,t),i=await s}catch{throw new oq("WebSocket connection timed out")}if("error"===i.winnerName)throw new oq("Could not open WebSocket connection");return n},FK="system/connectivity-checker",UK=async(e,t)=>{let r;const n={host:t.websocket.host,port:t.websocket.port,tls:t.websocket.tls},i=NK(n,"connectivityRequest");BK.debug(`Attempting connectivity check with entrypoint ${i}`);try{r=await LK({url:i,allowSelfSignedCertificate:e.allowSelfSignedCertificate})}catch(e){throw new oq(`Failed to connect to entrypoint for connectivity check: ${i}`,e)}const s={serviceId:FK,messageId:xF(),body:{oneofKind:"connectivityRequest",connectivityRequest:e}};try{const e=new Promise(((e,t)=>{const n=setTimeout((()=>{r.close(!1),t(new lq("timeout"))}),5e3),i=s=>{r.close(!1);try{const o=Hq.fromBinary(s);if("connectivityResponse"===o.body.oneofKind){BK.debug("ConnectivityResponse received: "+JSON.stringify(Hq.toJson(o)));const s=o.body.connectivityResponse,a=s.protocolVersion;r.off("data",i),clearTimeout(n),eK(a)?e(s):t(`Unsupported version: ${a}`)}}catch(e){BK.trace("Could not parse message",{err:e})}};r.on("data",i)}));return r.send(Hq.toBinary(s)),BK.trace("ConnectivityRequest sent: "+JSON.stringify(Hq.toJson(s))),await e}catch(e){throw BK.error("error getting connectivityresponse"),e}},jK=new Bv("connectivityRequestHandler"),qK=async(e,t,r)=>{const n=t.host??e.getRemoteIpAddress(),i=e.getRemoteIpAddress();let s;if(0!==t.port?s=await zK(t,i,n):(jK.trace("ConnectivityRequest port is 0, replying without connectivityProbe"),s={host:n,natType:Wz.UNKNOWN,ipAddress:mE(i),protocolVersion:Xz}),void 0!==r){const e=r.lookup(i);void 0!==e&&(s.latitude=e.latitude,s.longitude=e.longitude)}const o={serviceId:FK,messageId:xF(),body:{oneofKind:"connectivityResponse",connectivityResponse:s}};e.send(Hq.toBinary(o)),jK.trace("ConnectivityResponse sent: "+JSON.stringify(Hq.toJson(o)))},zK=async(e,t,r)=>{let n,i;try{const s={host:r,port:e.port,tls:e.tls},o=NK(s,"connectivityProbe");jK.trace(`Attempting Connectivity Check to ${o}`),n=await LK({url:o,allowSelfSignedCertificate:e.allowSelfSignedCertificate}),jK.trace("Connectivity test produced positive result, communicating reply to the requester "+r+":"+e.port),i={host:r,natType:Wz.OPEN_INTERNET,websocket:{host:r,port:e.port,tls:e.tls},ipAddress:mE(t),protocolVersion:Xz}}catch(e){jK.debug("error",{err:e}),i={host:r,natType:Wz.UNKNOWN,ipAddress:mE(t),protocolVersion:Xz}}return n&&n.close(!1),i},KK=new Bv("WebsocketClientConnectorRpcRemote");class GK extends jz{async requestConnection(){KK.trace(`Requesting WebSocket connection from ${Xj(this.getLocalPeerDescriptor())}`);const e=this.formDhtRpcOptions();return this.getClient().requestConnection({},e)}}const VK=new Bv("WebsocketServerConnector");class HK{websocketServer;geoIpLocator;ongoingConnectRequests=new Map;host;autoCertifierClient;selectedPort;localPeerDescriptor;abortController=new AbortController;options;constructor(e){this.options=e,this.websocketServer=e.portRange?new xK({portRange:e.portRange,tlsCertificate:e.tlsCertificate,maxMessageSize:e.maxMessageSize,enableTls:e.serverEnableTls}):void 0,this.host=e.host}async start(){if(!this.abortController.signal.aborted&&this.websocketServer){if(this.websocketServer.on("connected",(e=>{const t=e,r=new URLSearchParams(t.resourceURL.query??"").get("action");var n,i;VK.trace("WebSocket client connected",{action:r,remoteAddress:t.getRemoteIpAddress()}),"connectivityRequest"===r?(n=t,i=this.geoIpLocator,n.on("data",(async e=>{jK.trace("server received data");try{const t=Hq.fromBinary(e);if("connectivityRequest"===t.body.oneofKind){jK.trace("ConnectivityRequest received: "+JSON.stringify(Hq.toJson(t)));try{await qK(n,t.body.connectivityRequest,i),jK.trace("handleIncomingConnectivityRequest ok")}catch(e){jK.error("handleIncomingConnectivityRequest",{err:e})}}}catch(e){jK.trace("Could not parse message",{err:e})}}))):"connectivityProbe"===r||(void 0!==this.localPeerDescriptor?this.attachHandshaker(e):(VK.trace("incoming Websocket connection before localPeerDescriptor was set, closing connection"),e.close(!1).catch((()=>{}))))})),this.options.geoIpDatabaseFolder)try{this.geoIpLocator=await(()=>{throw new Error("GeoIpLocator is not supported in browser environment")})(this.options.geoIpDatabaseFolder)}catch(e){VK.error("Failed to start GeoIpLocator",{err:e})}const e=await this.websocketServer.start();this.selectedPort=e}}attachHandshaker(e){const t=new aK(this.localPeerDescriptor,e);t.once("handshakeRequest",((r,n,i)=>{this.onServerSocketHandshakeRequest(r,e,t,n,i)}))}onServerSocketHandshakeRequest(e,t,r,n,i){const s=Xj(e);if(this.ongoingConnectRequests.has(s)){const{pendingConnection:e,delFunc:o}=this.ongoingConnectRequests.get(s);eK(n)?i&&!eq(this.localPeerDescriptor,i)?(sK(e,t,r,Eq.INVALID_TARGET_PEER_DESCRIPTOR),o()):oK(r,e,t):(sK(e,t,r,Eq.UNSUPPORTED_PROTOCOL_VERSION),o())}else{const s=new uK(e);eK(n)?i&&!eq(this.localPeerDescriptor,i)?sK(s,t,r,Eq.INVALID_TARGET_PEER_DESCRIPTOR):this.options.onNewConnection(s)?oK(r,s,t):sK(s,t,r,Eq.DUPLICATE_CONNECTION):sK(s,t,r,Eq.UNSUPPORTED_PROTOCOL_VERSION)}}async checkConnectivity(e){if(this.abortController.signal.aborted)return{host:"127.0.0.1",natType:Wz.UNKNOWN,ipAddress:mE("127.0.0.1"),protocolVersion:Xz};if(!this.options.entrypoints||0===this.options.entrypoints.length)return{host:this.host,natType:Wz.OPEN_INTERNET,websocket:{host:this.host,port:this.selectedPort,tls:void 0!==this.options.tlsCertificate},ipAddress:mE("127.0.0.1"),protocolVersion:Xz};const t=JU(this.options.entrypoints);for(;t.length>0&&!this.abortController.signal.aborted;){const r=t[0];try{const t={port:this.selectedPort??0,host:this.host,tls:!!this.websocketServer&&this.options.serverEnableTls,allowSelfSignedCertificate:e};if(this.abortController.signal.aborted)throw new oq("ConnectivityChecker is destroyed");return await UK(t,r)}catch(e){const n=`Failed to connect to entrypoint with id ${Xj(r)} and URL ${NK(r.websocket)}`;VK.error(n,{err:e}),t.shift(),await Qv(2e3,this.abortController.signal)}}throw new aq(`Failed to connect to the entrypoints after ${this.options.entrypoints.length} attempts\nAttempted hosts: ${this.options.entrypoints.map((e=>`${e.websocket.host}:${e.websocket.port}`)).join(", ")}`)}async autoCertify(){this.autoCertifierClient=new DK({configFile:this.options.autoCertifierConfigFile,transport:this.options.autoCertifierTransport,url:this.options.autoCertifierUrl,wsServerPort:this.selectedPort,setHost:e=>this.setHost(e),updateCertificate:(e,t)=>this.websocketServer.updateCertificate(e,t)}),VK.trace("AutoCertifying subdomain..."),await this.autoCertifierClient.start()}setHost(e){VK.trace(`Setting host name to ${e}`),this.host=e}connect(e){const t=Xj(e);return this.ongoingConnectRequests.has(t)?this.ongoingConnectRequests.get(t).pendingConnection:this.requestConnectionFromPeer(this.localPeerDescriptor,e)}requestConnectionFromPeer(e,t){setImmediate((()=>{new GK(e,t,this.options.rpcCommunicator,Ez).requestConnection().then((()=>{VK.trace("Sent WebsocketConnectionRequest notification to peer",{targetPeerDescriptor:t})}),(e=>{VK.debug("Failed to send WebsocketConnectionRequest notification to peer ",{error:e,targetPeerDescriptor:t})}))}));const r=new uK(t),n=Xj(t),i=()=>{r.off("connected",i),r.off("disconnected",i),this.ongoingConnectRequests.delete(n)};return r.on("connected",i),r.on("disconnected",i),this.ongoingConnectRequests.set(n,{pendingConnection:r,delFunc:i}),r}isPossibleToFormConnection(e){return Lz(this.localPeerDescriptor,e)===xz.WEBSOCKET_SERVER}setLocalPeerDescriptor(e){this.localPeerDescriptor=e}async destroy(){this.abortController.abort();Array.from(this.ongoingConnectRequests.values()).forEach((e=>e.pendingConnection.close(!0))),await(this.websocketServer?.stop()),this.geoIpLocator?.stop()}}const $K=new Bv("ConnectorFacade");class WK{options;localPeerDescriptor;websocketConnectorRpcCommunicator;websocketClientConnector;websocketServerConnector;webrtcConnector;constructor(e){this.options=e}async start(e,t,r){$K.trace("Creating WebsocketConnectorRpcLocal"),this.websocketConnectorRpcCommunicator=new lK(MK.WEBSOCKET_CONNECTOR_SERVICE_ID,this.options.transport,{rpcRequestTimeout:15e3});const n={onNewConnection:e,hasConnection:t,rpcCommunicator:this.websocketConnectorRpcCommunicator};this.websocketClientConnector=new MK(n);const i={rpcCommunicator:this.websocketConnectorRpcCommunicator,onNewConnection:e,hasConnection:t,portRange:this.options.websocketPortRange,host:this.options.websocketHost,entrypoints:this.options.entryPoints,tlsCertificate:this.options.tlsCertificate,serverEnableTls:this.options.websocketServerEnableTls,autoCertifierUrl:this.options.autoCertifierUrl,autoCertifierConfigFile:this.options.autoCertifierConfigFile,autoCertifierTransport:r,maxMessageSize:this.options.maxMessageSize,geoIpDatabaseFolder:this.options.geoIpDatabaseFolder};this.websocketServerConnector=new HK(i),this.webrtcConnector=new RK({onNewConnection:e,transport:this.options.transport,iceServers:this.options.iceServers,allowPrivateAddresses:this.options.webrtcAllowPrivateAddresses,bufferThresholdLow:this.options.webrtcDatachannelBufferThresholdLow,bufferThresholdHigh:this.options.webrtcDatachannelBufferThresholdHigh,externalIp:this.options.externalIp,portRange:this.options.webrtcPortRange,maxMessageSize:this.options.maxMessageSize}),await this.websocketServerConnector.start();const s=!this.options.tlsCertificate&&!0===this.options.websocketServerEnableTls,o=await this.websocketServerConnector.checkConnectivity(s),a=await this.options.createLocalPeerDescriptor(o);if(this.setLocalPeerDescriptor(a),a.websocket&&!this.options.tlsCertificate&&this.options.websocketServerEnableTls)try{await this.websocketServerConnector.autoCertify();const e=await this.websocketServerConnector.checkConnectivity(!1),t=await this.options.createLocalPeerDescriptor(e);void 0!==t.websocket?this.setLocalPeerDescriptor(t):($K.warn("Connectivity check failed after auto-certification, disabling WebSocket server TLS"),await this.restartWebsocketServerConnector({...i,serverEnableTls:!1}))}catch(e){$K.warn("Failed to auto-certify, disabling WebSocket server TLS",{err:e}),await this.restartWebsocketServerConnector({...i,serverEnableTls:!1})}}setLocalPeerDescriptor(e){this.localPeerDescriptor=e,this.websocketServerConnector.setLocalPeerDescriptor(e),this.websocketClientConnector.setLocalPeerDescriptor(e),this.webrtcConnector.setLocalPeerDescriptor(e)}async restartWebsocketServerConnector(e){await this.websocketServerConnector.destroy(),this.websocketServerConnector=new HK(e),await this.websocketServerConnector.start();const t=await this.websocketServerConnector.checkConnectivity(!1),r=await this.options.createLocalPeerDescriptor(t);this.setLocalPeerDescriptor(r)}createConnection(e){return this.websocketClientConnector.isPossibleToFormConnection(e)?this.websocketClientConnector.connect(e):this.websocketServerConnector.isPossibleToFormConnection(e)?this.websocketServerConnector.connect(e):this.webrtcConnector.connect(e,!1)}getLocalPeerDescriptor(){return this.localPeerDescriptor}async stop(){this.websocketConnectorRpcCommunicator.destroy(),await this.websocketServerConnector.destroy(),await this.websocketClientConnector.destroy(),await this.webrtcConnector.stop()}}function JK(e){const t=Buffer.alloc(4);return t.writeUInt32BE(e),t}const QK=new TE,ZK=async(e,t,r)=>{const n=so(32),i=so(20);let s;s=void 0!==r?Yj(r):await(async(e,t)=>{const r=Buffer.alloc(4);r.writeUInt32BE(e);const n=QK.keccakHash(r),i=await QK.createSignature(r,t);return Buffer.concat([n.subarray(n.length-13,n.length),i.subarray(i.length-7,i.length)])})(e.ipAddress,n);const o={nodeId:s,type:bq.BROWSER,ipAddress:e.ipAddress,region:t,publicKey:i};return e.websocket&&(o.websocket={host:e.websocket.host,port:e.websocket.port,tls:e.websocket.tls}),o.signature=await QK.createSignature((e=>{const t=Buffer.from(","),r=[void 0!==e.type?JK(e.type):new Uint8Array(0),t,void 0!==e.udp?Uq.toBinary(e.udp):new Uint8Array(0),t,void 0!==e.tcp?Uq.toBinary(e.tcp):new Uint8Array(0),t,void 0!==e.websocket?Uq.toBinary(e.websocket):new Uint8Array(0),t,void 0!==e.region?JK(e.region):new Uint8Array(0),t,void 0!==e.ipAddress?JK(e.ipAddress):new Uint8Array(0),t,void 0!==e.publicKey?Buffer.from(e.publicKey):new Uint8Array(0)];return Buffer.concat(r)})(o),n),o};class YK{peerDescriptor;constructor(e){this.peerDescriptor=e}getPeerDescriptor(){return this.peerDescriptor}getNodeId(){return Xj(this.peerDescriptor)}}const XK=(e,t,r)=>{const n=new rq({referenceId:e,allowToContainReferenceId:!0,excludedNodeIds:r?.excludedNodeIds,maxSize:r?.maxCount});for(const e of t)n.addContact(new YK(e));return n.getClosestContacts().map((e=>e.getPeerDescriptor()))},eG=new Bv("DhtNodeRpcLocal");class tG{options;constructor(e){this.options=e}async getClosestPeers(e,t){this.options.addContact(t.incomingSourceDescriptor);return{peers:XK(Zj(e.nodeId),this.options.getNeighbors(),{maxCount:this.options.peerDiscoveryQueryBatchSize}),requestId:e.requestId}}async getClosestRingPeers(e,t){this.options.addContact(t.incomingSourceDescriptor);const r=this.options.getClosestRingContactsTo(e.ringId,this.options.peerDiscoveryQueryBatchSize);return{leftPeers:r.left,rightPeers:r.right,requestId:e.requestId}}async ping(e,t){eG.trace("received ping request: "+Xj(t.incomingSourceDescriptor)),setImmediate((()=>{this.options.addContact(t.incomingSourceDescriptor)}));return{requestId:e.requestId}}async leaveNotice(e){const t=e.incomingSourceDescriptor,r=Xj(t);return eG.trace("received leave notice: "+r),this.options.removeContact(r),{}}}const rG=new Bv("DhtNodeRpcRemote");class nG extends jz{static counter=0;vectorClock;id;serviceId;constructor(e,t,r,n,i){super(e,t,n,mz,i),this.id=this.getPeerDescriptor().nodeId,this.vectorClock=nG.counter++,this.serviceId=r}async getClosestPeers(e){rG.trace(`Requesting getClosestPeers on ${this.serviceId} from ${this.getNodeId()}`);const t={nodeId:Yj(e),requestId:xF()};try{return(await this.getClient().getClosestPeers(t,this.formDhtRpcOptions())).peers}catch(e){throw rG.trace(`getClosestPeers error ${this.serviceId}`,{err:e}),e}}async getClosestRingPeers(e){rG.trace(`Requesting getClosestRingPeers on ${this.serviceId} from ${this.getNodeId()}`);const t={ringId:e,requestId:xF()};try{const e=await this.getClient().getClosestRingPeers(t,this.formDhtRpcOptions());return{left:e.leftPeers??[],right:e.rightPeers??[]}}catch(e){throw rG.trace(`getClosestRingPeers error ${this.serviceId}`,{err:e}),e}}async ping(){rG.trace(`Requesting ping on ${this.serviceId} from ${this.getNodeId()}`);const e={requestId:xF()},t=this.formDhtRpcOptions();try{if((await this.getClient().ping(e,t)).requestId===e.requestId)return!0}catch(e){rG.trace(`ping failed on ${this.serviceId} to ${this.getNodeId()}`,{err:e})}return!1}leaveNotice(){rG.trace(`Sending leaveNotice on ${this.serviceId} from ${this.getNodeId()}`);const e=this.formDhtRpcOptions({notification:!0});this.getClient().leaveNotice({},e).catch((e=>{rG.trace("Failed to send leaveNotice"+e)}))}getNodeId(){return Xj(this.getPeerDescriptor())}}class iG{options;constructor(e){this.options=e}async externalFetchData(e,t){const r=t.incomingSourceDescriptor,n=await this.options.executeRecursiveOperation(Zj(e.key),yq.FETCH_DATA,Xj(r));return iz.create({entries:n.dataEntries??[]})}async externalStoreData(e,t){const r=t.incomingSourceDescriptor,n=await this.options.storeDataToDht(Zj(e.key),e.data,Xj(r));return Cq.create({storers:n})}async externalFindClosestNodes(e,t){const r=t.incomingSourceDescriptor,n=await this.options.executeRecursiveOperation(Zj(e.nodeId),yq.FIND_CLOSEST_NODES,Xj(r));return oz.create({closestNodes:n.closestNodes})}}const sG=1e4;class oG extends jz{async externalFetchData(e){const t={key:Yj(e)},r=this.formDhtRpcOptions({timeout:sG});try{return(await this.getClient().externalFetchData(t,r)).entries}catch{return[]}}async storeData(e,t){const r={key:Yj(e),data:t},n=this.formDhtRpcOptions({timeout:sG});try{return(await this.getClient().externalStoreData(r,n)).storers}catch{return[]}}async externalFindClosestNode(e){const t={nodeId:Yj(e)},r=this.formDhtRpcOptions({timeout:sG});try{return(await this.getClient().externalFindClosestNodes(t,r)).closestNodes}catch{return[]}}}class aG extends Sl{contactsById=new Map;contactIds=[];localNodeId;maxSize;constructor(e,t){super(),this.localNodeId=e,this.maxSize=t}getContact(e){return this.contactsById.get(e)}getSize(){return this.contactIds.length}clear(){this.contactsById.clear(),this.contactIds=[]}stop(){this.removeAllListeners(),this.clear()}}class cG extends aG{randomness;constructor(e,t,r=.2){super(e,t),this.randomness=r}addContact(e){if(this.localNodeId!==e.getNodeId()&&!this.contactsById.has(e.getNodeId())){if(Math.random()<this.randomness){if(this.getSize()===this.maxSize&&this.getSize()>0){const e=this.contactIds[0];this.removeContact(e)}this.contactIds.push(e.getNodeId()),this.contactsById.set(e.getNodeId(),e),this.emit("contactAdded",e)}}}removeContact(e){if(this.contactsById.has(e)){const t=this.contactsById.get(e),r=this.contactIds.findIndex((t=>t===e));return this.contactIds.splice(r,1),this.contactsById.delete(e),this.emit("contactRemoved",t),!0}return!1}getContacts(e){return(void 0===e?this.contactIds:this.contactIds.slice(0,Math.max(e,0))).map((e=>this.contactsById.get(e)))}}const uG=2**120-1,lG=e=>e.reduce(((e,t)=>e<<BigInt(8)|BigInt(t)),BigInt(0)),hG=e=>Number(lG(e)),dG=e=>{const t=Buffer.alloc(4);t.writeUInt32BE(e.region??0,0);const r=Buffer.alloc(4);r.writeUInt32BE(e.ipAddress??0,0);const n=[t,r,Buffer.from(e.nodeId.subarray(e.nodeId.length-7,e.nodeId.length))],i=Buffer.concat(n);return new Uint8Array(i)},fG=e=>{const t=dG(e);return Number(lG(t))},pG=(e,t)=>{const r=Math.abs(e-t);return e>t?r:uG-r},gG=(e,t)=>{const r=Math.abs(e-t);return e>t?uG-r:r};class mG extends Sl{numNeighborsPerSide=5;referenceId;excludedIds;leftNeighbors;rightNeighbors;constructor(e,t){super(),this.referenceId=hG(e),this.excludedIds=t??new Set,this.leftNeighbors=new cj,this.rightNeighbors=new cj}addContact(e){const t=fG(e.getPeerDescriptor());if(t===this.referenceId||this.excludedIds.has(Xj(e.getPeerDescriptor())))return;let r=!1,n=!1;const i=pG(this.referenceId,t),s=this.leftNeighbors.back();(void 0===s||i<s[0])&&(this.leftNeighbors.setElement(i,e),r=!0,this.leftNeighbors.size()>this.numNeighborsPerSide&&(this.leftNeighbors.eraseElementByIterator(this.leftNeighbors.rBegin()),n=!0));const o=gG(this.referenceId,t),a=this.rightNeighbors.back();(void 0===a||o<a[0])&&(this.rightNeighbors.setElement(o,e),r=!0,this.rightNeighbors.size()>this.numNeighborsPerSide&&(this.rightNeighbors.eraseElementByIterator(this.rightNeighbors.rBegin()),n=!0)),this.hasEventListeners()&&(r||n)&&(r&&this.emit("contactAdded",e),n&&this.emit("contactRemoved",e))}removeContact(e){if(void 0===e)return;const t=fG(e.getPeerDescriptor()),r=pG(this.referenceId,t),n=gG(this.referenceId,t);let i=!1;this.leftNeighbors.eraseElementByKey(r)&&(i=!0),this.rightNeighbors.eraseElementByKey(n)&&(i=!0),this.hasEventListeners()&&i&&this.emit("contactRemoved",e)}getContact(e){const t=fG(e),r=pG(this.referenceId,t),n=gG(this.referenceId,t);return this.leftNeighbors.getElementByKey(r)?this.leftNeighbors.getElementByKey(r):this.rightNeighbors.getElementByKey(n)?this.rightNeighbors.getElementByKey(n):void 0}getClosestContacts(e){const t=[],r=[];let n=0;for(const r of this.leftNeighbors){if(null!=e&&n>=e)break;t.push(r[1]),n++}let i=0;for(const t of this.rightNeighbors){if(null!=e&&i>=e)break;r.push(t[1]),i++}return{left:t,right:r}}getAllContacts(){const e=[];for(const t of this.leftNeighbors)e.push(t[1]);for(const t of this.rightNeighbors)e.push(t[1]);return e}hasEventListeners(){return this.eventNames().length>0}}const yG=new Bv("PeerManager");class bG extends Sl{neighbors;nearbyContacts;activeContacts;ringContacts;randomContacts;stopped=!1;options;constructor(e){super(),this.options=e,this.neighbors=new yL({localNodeId:Yj(this.options.localNodeId),numberOfNodesPerKBucket:this.options.numberOfNodesPerKBucket,numberOfNodesToPing:this.options.numberOfNodesPerKBucket}),this.ringContacts=new mG(dG(this.options.localPeerDescriptor)),this.ringContacts.on("contactAdded",(e=>{this.emit("ringContactAdded",e.getPeerDescriptor())})),this.ringContacts.on("contactRemoved",(e=>{this.emit("ringContactRemoved",e.getPeerDescriptor())})),this.neighbors.on("ping",((e,t)=>this.onKBucketPing(e,t))),this.neighbors.on("removed",(e=>this.onKBucketRemoved(Xj(e.getPeerDescriptor())))),this.neighbors.on("added",(e=>this.onKBucketAdded(e))),this.neighbors.on("updated",(()=>{})),this.nearbyContacts=new rq({referenceId:this.options.localNodeId,maxSize:this.options.maxContactCount,allowToContainReferenceId:!1}),this.nearbyContacts.on("contactRemoved",(e=>{this.stopped||(this.emit("nearbyContactRemoved",e.getPeerDescriptor()),this.randomContacts.addContact(this.options.createDhtNodeRpcRemote(e.getPeerDescriptor())))})),this.nearbyContacts.on("contactAdded",(e=>this.emit("nearbyContactAdded",e.getPeerDescriptor()))),this.activeContacts=new Set,this.randomContacts=new cG(this.options.localNodeId,this.options.maxContactCount),this.randomContacts.on("contactRemoved",(e=>this.emit("randomContactRemoved",e.getPeerDescriptor()))),this.randomContacts.on("contactAdded",(e=>this.emit("randomContactAdded",e.getPeerDescriptor())))}onKBucketPing(e,t){if(this.stopped)return;const r=new rq({referenceId:this.options.localNodeId,allowToContainReferenceId:!1});r.addContacts(e);const n=r.getFurthestContacts(1)[0].getNodeId();this.options.connectionLocker?.weakUnlockConnection(n,this.options.lockId),this.neighbors.remove(Yj(n)),this.neighbors.add(t)}onKBucketRemoved(e){this.stopped||(this.options.connectionLocker?.weakUnlockConnection(e,this.options.lockId),yG.trace(`Removed contact ${e}`),0===this.neighbors.count()&&this.emit("kBucketEmpty"))}onKBucketAdded(e){if(!this.stopped&&e.getNodeId()!==this.options.localNodeId){const t=e.getPeerDescriptor(),r=Xj(t);this.options.connectionLocker?.weakLockConnection(r,this.options.lockId),this.options.hasConnection(e.getNodeId())||void 0!==this.options.neighborPingLimit&&this.neighbors.count()>this.options.neighborPingLimit?yG.trace(`Added new contact ${r}`):(yG.trace("starting ping "+r),e.ping().then((e=>{e?yG.trace(`Added new contact ${r}`):(yG.trace("ping failed "+r),this.options.connectionLocker?.weakUnlockConnection(r,this.options.lockId),this.removeContact(r),this.addNearbyContactToNeighbors())})).catch((e=>{this.options.connectionLocker?.weakUnlockConnection(r,this.options.lockId),this.removeContact(r),this.addNearbyContactToNeighbors()})))}}addNearbyContactToNeighbors(){if(this.stopped)return;const e=this.getNearbyActiveContactNotInNeighbors();e&&this.addContact(e.getPeerDescriptor())}getNearbyActiveContactNotInNeighbors(){for(const e of this.nearbyContacts.getContactIds())if(!this.neighbors.get(Yj(e))&&this.activeContacts.has(e))return this.nearbyContacts.getContact(e)}removeContact(e){this.stopped||(yG.trace(`Removing contact ${e}`),this.ringContacts.removeContact(this.nearbyContacts.getContact(e)),this.neighbors.remove(Yj(e)),this.nearbyContacts.removeContact(e),this.activeContacts.delete(e),this.randomContacts.removeContact(e))}removeNeighbor(e){this.neighbors.remove(Yj(e))}async pruneOfflineNodes(e){yG.trace("Pruning offline nodes",{nodes:e.length});const t=await(async(e,t)=>{const r=[];return await Promise.allSettled(e.map((async e=>{await e.ping()?t.add(e.getNodeId()):(t.delete(e.getNodeId()),r.push(e.getPeerDescriptor()))}))),r})(e,this.activeContacts);t.forEach((e=>{yG.trace("Removing offline node",{node:Xj(e)}),this.removeContact(Xj(e))}))}stop(){this.stopped=!0,this.neighbors.toArray().forEach((e=>{e.leaveNotice(),this.neighbors.remove(e.id)})),this.neighbors.removeAllListeners(),this.ringContacts.getAllContacts().forEach((e=>{e.leaveNotice(),this.ringContacts.removeContact(e)})),this.nearbyContacts.stop(),this.randomContacts.stop()}getNearbyContacts(){return this.nearbyContacts}getClosestRingContactsTo(e,t,r){const n=new mG(e,r);return this.ringContacts.getAllContacts().map((e=>n.addContact(e))),n.getClosestContacts(t??8)}getRandomContacts(){return this.randomContacts}getRingContacts(){return this.ringContacts}getNearbyContactCount(e){return this.nearbyContacts.getSize(e)}getNeighborCount(){return this.neighbors.count()}getNeighbors(){return this.neighbors.toArray()}setContactActive(e){this.activeContacts.add(e)}addContact(e){if(this.stopped)return;const t=Xj(e);if(t!==this.options.localNodeId){yG.trace(`Adding new contact ${t}`);const r=this.options.createDhtNodeRpcRemote(e),n=null!==this.neighbors.get(e.nodeId),i=void 0!==this.nearbyContacts.getContact(t),s=void 0!==this.ringContacts.getContact(e);(n||i)&&this.randomContacts.addContact(r),n||this.neighbors.add(r),i||this.nearbyContacts.addContact(r),s||this.ringContacts.addContact(r)}}}const wG=new Bv("DiscoverySession");class vG{id=xF();noProgressCounter=0;ongoingRequests=new Set;doneGate=new uE(!1);options;constructor(e){this.options=e}addContacts(e){if(!this.options.abortSignal.aborted&&!this.doneGate.isOpen())for(const t of e)this.options.peerManager.addContact(t)}async fetchClosestNeighborsFromRemote(e){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return[];const t=Xj(e);wG.trace(`Getting closest neighbors from remote: ${t}`),this.options.contactedPeers.add(t);const r=this.options.createDhtNodeRpcRemote(e),n=await r.getClosestPeers(this.options.targetId);return this.options.peerManager.setContactActive(t),n}onRequestSucceeded(e,t){if(!this.ongoingRequests.has(e))return;this.ongoingRequests.delete(e);const r=Yj(this.options.targetId),n=this.getClosestNeighbor(),i=Qj(r,n.nodeId);this.addContacts(t);const s=this.getClosestNeighbor();Qj(r,s.nodeId)>=i&&this.noProgressCounter++}getClosestNeighbor(){return XK(this.options.targetId,this.options.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),{maxCount:1})[0]}onRequestFailed(e){this.ongoingRequests.has(e)&&(this.ongoingRequests.delete(e),this.options.peerManager.removeContact(e))}findMoreContacts(){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return;const e=XK(this.options.targetId,Array.from(this.options.peerManager.getNearbyContacts().getAllContactsInUndefinedOrder(),(e=>e.getPeerDescriptor())),{maxCount:this.options.parallelism,excludedNodeIds:this.options.contactedPeers});if(0===e.length&&0===this.ongoingRequests.size||this.noProgressCounter>=this.options.noProgressLimit)this.doneGate.open();else for(const t of e){if(this.ongoingRequests.size>=this.options.parallelism)break;const e=Xj(t);this.ongoingRequests.add(e),this.fetchClosestNeighborsFromRemote(t).then((t=>this.onRequestSucceeded(e,t))).catch((()=>this.onRequestFailed(e))).finally((()=>{this.findMoreContacts()}))}}async findClosestNodes(e){0!==this.options.peerManager.getNearbyContactCount(this.options.contactedPeers)&&(setImmediate((()=>{this.findMoreContacts()})),await Xv(this.doneGate.waitUntilOpen(),e,"discovery session timed out",this.options.abortSignal))}}const EG=new Bv("RingDiscoverySession");class AG{id=xF();noProgressCounter=0;ongoingRequests=new Set;doneGate=new uE(!1);options;numContactedPeers=0;targetIdAsRingId;constructor(e){this.options=e,this.targetIdAsRingId=hG(this.options.targetId)}addContacts(e){if(!this.options.abortSignal.aborted&&!this.doneGate.isOpen())for(const t of e)this.options.peerManager.addContact(t)}async fetchClosestContactsFromRemote(e){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return{left:[],right:[]};EG.trace(`Getting closest ring peers from contact: ${Xj(e.getPeerDescriptor())}`),this.numContactedPeers++,this.options.contactedPeers.add(e.getNodeId());const t=await e.getClosestRingPeers(this.options.targetId);return this.options.peerManager.setContactActive(e.getNodeId()),t}onRequestSucceeded(e,t){if(!this.ongoingRequests.has(e))return;this.ongoingRequests.delete(e);const r=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,1),n=pG(this.targetIdAsRingId,fG(r.left[0].getPeerDescriptor())),i=pG(this.targetIdAsRingId,fG(r.right[0].getPeerDescriptor()));this.addContacts(t.left.concat(t.right));const s=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,1),o=pG(this.targetIdAsRingId,fG(s.left[0].getPeerDescriptor())),a=pG(this.targetIdAsRingId,fG(s.right[0].getPeerDescriptor()));o>=n&&a>=i&&this.noProgressCounter++}onRequestFailed(e){this.ongoingRequests.has(e.getNodeId())&&(this.ongoingRequests.delete(e.getNodeId()),this.options.peerManager.removeContact(e.getNodeId()))}findMoreContacts(){if(this.options.abortSignal.aborted||this.doneGate.isOpen())return;const e=this.options.peerManager.getClosestRingContactsTo(this.options.targetId,this.options.parallelism,this.options.contactedPeers);if(0===e.left.length&&0===e.right.length||this.noProgressCounter>=this.options.noProgressLimit)return void this.doneGate.open();const t=[],r=new Set,n=Math.max(e.left.length,e.right.length);for(let i=0;i<n;i++)i<e.left.length&&(r.has(e.left[i].getNodeId())||(t.push(e.left[i]),r.add(e.left[i].getNodeId()))),i<e.right.length&&(r.has(e.right[i].getNodeId())||(t.push(e.right[i]),r.add(e.right[i].getNodeId())));for(const e of t){if(this.ongoingRequests.size>=this.options.parallelism)break;this.ongoingRequests.add(e.getNodeId()),this.fetchClosestContactsFromRemote(e).then((t=>this.onRequestSucceeded(e.getNodeId(),t))).catch((()=>this.onRequestFailed(e))).finally((()=>{this.findMoreContacts()}))}}async findClosestNodes(e){0!==this.options.peerManager.getNearbyContactCount(this.options.contactedPeers)&&(setImmediate((()=>{this.findMoreContacts()})),await Xv(this.doneGate.waitUntilOpen(),e,"discovery session timed out",this.options.abortSignal))}}const SG="layer0",kG=new Bv("PeerDiscovery");class RG{ongoingDiscoverySessions=new Map;ongoingRingDiscoverySessions=new Map;rejoinOngoing=!1;joinCalled=!1;recoveryIntervalStarted=!1;options;constructor(e){this.options=e}async joinDht(e,t=!0,r=!0){const n=new Set,i=t?{enabled:!0,contactedPeers:new Set}:{enabled:!1};await Promise.all(e.map((e=>this.joinThroughEntryPoint(e,n,i,r))))}async joinThroughEntryPoint(e,t,r,n=!0){if(this.isStopped())return;if(this.joinCalled=!0,kG.debug("Joining "+(this.options.serviceId===SG?"The Streamr Network":`Control Layer for ${this.options.serviceId}`)+` via entrypoint ${Xj(e)}`),eq(e,this.options.localPeerDescriptor))return;this.options.connectionLocker?.lockConnection(e,`${this.options.serviceId}::joinDht`),this.options.peerManager.addContact(e);const i=Xj(this.options.localPeerDescriptor),s=[this.createSession(i,t)];r.enabled&&s.push(this.createSession((e=>{const t=Yj(e).map((e=>~e));return Zj(t)})(i),r.contactedPeers)),await this.runSessions(s,e,n),this.options.connectionLocker?.unlockConnection(e,`${this.options.serviceId}::joinDht`)}async joinRing(){const e=new Set,t=[this.createRingSession(dG(this.options.localPeerDescriptor),e)];await this.runRingSessions(t)}createSession(e,t){const r={targetId:e,parallelism:this.options.parallelism,noProgressLimit:this.options.joinNoProgressLimit,peerManager:this.options.peerManager,contactedPeers:t,abortSignal:this.options.abortSignal,createDhtNodeRpcRemote:this.options.createDhtNodeRpcRemote};return new vG(r)}createRingSession(e,t){const r={targetId:e,parallelism:this.options.parallelism,noProgressLimit:this.options.joinNoProgressLimit,peerManager:this.options.peerManager,contactedPeers:t,abortSignal:this.options.abortSignal,createDhtNodeRpcRemote:this.options.createDhtNodeRpcRemote};return new AG(r)}async runSessions(e,t,r){try{for(const t of e)this.ongoingDiscoverySessions.set(t.id,t),await t.findClosestNodes(this.options.joinTimeout)}catch(e){kG.debug(`DHT join on ${this.options.serviceId} timed out`)}finally{this.isStopped()||(0===this.options.peerManager.getNeighborCount()?r&&Yy((()=>this.rejoinDht(t)),1e3,this.options.abortSignal):await this.ensureRecoveryIntervalIsRunning()),e.forEach((e=>this.ongoingDiscoverySessions.delete(e.id)))}}async runRingSessions(e){try{for(const t of e)this.ongoingRingDiscoverySessions.set(t.id,t),await t.findClosestNodes(this.options.joinTimeout)}catch(e){kG.debug(`Ring join on ${this.options.serviceId} timed out`)}finally{e.forEach((e=>this.ongoingDiscoverySessions.delete(e.id)))}}async rejoinDht(e,t=new Set,r=new Set){if(!this.isStopped()&&!this.rejoinOngoing){kG.debug(`Rejoining DHT ${this.options.serviceId}`),this.rejoinOngoing=!0;try{await this.joinThroughEntryPoint(e,t,{enabled:!0,contactedPeers:r}),kG.debug(`Rejoined DHT successfully ${this.options.serviceId}!`)}catch{kG.warn(`Rejoining DHT ${this.options.serviceId} failed`),this.isStopped()||Yy((()=>this.rejoinDht(e)),5e3,this.options.abortSignal)}finally{this.rejoinOngoing=!1}}}async ensureRecoveryIntervalIsRunning(){this.recoveryIntervalStarted||(this.recoveryIntervalStarted=!0,await Jv((()=>this.fetchClosestAndRandomNeighbors()),6e4,!0,this.options.abortSignal))}async fetchClosestAndRandomNeighbors(){if(this.isStopped())return;const e=Xj(this.options.localPeerDescriptor),t=this.getClosestNeighbors(e,this.options.parallelism),r=this.getClosestNeighbors(tq(),1);await Promise.allSettled([...t.map((async t=>{const r=this.options.createDhtNodeRpcRemote(t),n=await r.getClosestPeers(e);for(const e of n)this.options.peerManager.addContact(e)})),...r.map((async e=>{const t=this.options.createDhtNodeRpcRemote(e),r=await t.getClosestPeers(tq());for(const e of r)this.options.peerManager.addContact(e)}))])}getClosestNeighbors(e,t){return XK(e,this.options.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),{maxCount:t})}isJoinOngoing(){return!this.joinCalled||this.ongoingDiscoverySessions.size>0}isJoinCalled(){return this.joinCalled}isStopped(){return this.options.abortSignal.aborted}}const CG=e=>bj(e.routingPath),IG=new Bv("RouterRpcRemote");class PG extends jz{async routeMessage(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{const n=await this.getClient().routeMessage(t,r);if(n.error===vq.DUPLICATE&&yw(e.target,this.getPeerDescriptor().nodeId))return!0;if(void 0!==n.error)return!1}catch(t){const r=CG(e),n=Xj(r||e.sourcePeer),i=Xj(this.getPeerDescriptor());return IG.trace(`Failed to send routeMessage from ${n} to ${i}`,{err:t}),!1}return!0}async forwardMessage(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{if(void 0!==(await this.getClient().forwardMessage(t,r)).error)return!1}catch(t){const r=CG(e),n=Xj(r||e.sourcePeer),i=Xj(this.getPeerDescriptor());return IG.trace(`Failed to send forwardMessage from ${n} to ${i}`,{err:t}),!1}return!0}}const TG=new Bv("RecursiveOperationRpcRemote");class _G extends jz{async routeRequest(e){const t={target:e.target,sourcePeer:e.sourcePeer,message:e.message,requestId:e.requestId??xF(),reachableThrough:e.reachableThrough??[],routingPath:e.routingPath,parallelRootNodeIds:e.parallelRootNodeIds},r=this.formDhtRpcOptions({connect:!1});try{const e=await this.getClient().routeRequest(t,r);if(void 0!==e.error)return TG.trace("Next hop responded with error "+e.error),!1}catch(t){const r=CG(e),n=Xj(r||e.sourcePeer),i=Xj(this.getPeerDescriptor());return TG.debug(`Failed to send routeRequest message from ${n} to ${i}`,{err:t}),!1}return!0}}const NG=new Bv("RoutingSession");class MG extends YK{routerRpcRemote;recursiveOperationRpcRemote;constructor(e,t,r){super(e),this.routerRpcRemote=new PG(t,e,r,yz,2e3),this.recursiveOperationRpcRemote=new _G(t,e,r,bz,2e3)}getRouterRpcRemote(){return this.routerRpcRemote}getRecursiveOperationRpcRemote(){return this.recursiveOperationRpcRemote}}var xG;!function(e){e[e.ROUTE=0]="ROUTE",e[e.FORWARD=1]="FORWARD",e[e.RECURSIVE=2]="RECURSIVE"}(xG||(xG={}));class OG extends Sl{sessionId=xF();ongoingRequests=new Set;contactedPeers=new Set;failedHopCounter=0;successfulHopCounter=0;stopped=!1;options;constructor(e){super(),this.options=e}onRequestFailed(e){if(NG.trace("onRequestFailed() sessionId: "+this.sessionId),this.stopped)return;if(this.ongoingRequests.has(e)&&this.ongoingRequests.delete(e),this.deleteParallelRootIfSource(e),this.failedHopCounter+=1,this.failedHopCounter>=2)return NG.trace(`Stopping routing after 2 failed attempts for sessionId: ${this.sessionId}`),void this.emitFailure();const t=this.updateAndGetRoutablePeers();0===t.length&&0===this.ongoingRequests.size?(NG.trace("routing failed, emitting routingFailed sessionId: "+this.sessionId),this.emitFailure()):(NG.trace("routing failed, retrying to route sessionId: "+this.sessionId+" failedHopCounter: "+this.failedHopCounter),this.sendMoreRequests(t))}emitFailure(){this.successfulHopCounter>=1?this.emit("partialSuccess"):this.emit("routingFailed")}onRequestSucceeded(){if(NG.trace("onRequestSucceeded() sessionId: "+this.sessionId),this.stopped)return;if(this.successfulHopCounter+=1,this.successfulHopCounter>=this.options.parallelism)return void this.emit("routingSucceeded");const e=this.updateAndGetRoutablePeers();0===e.length?this.emit("routingSucceeded"):e.length>0&&0===this.ongoingRequests.size&&this.sendMoreRequests(e)}async sendRouteMessageRequest(e){if(this.stopped)return!1;const t={...this.options.routedMessage,routingPath:this.options.routedMessage.routingPath.concat([this.options.localPeerDescriptor])};return this.options.mode===xG.FORWARD?e.getRouterRpcRemote().forwardMessage(t):this.options.mode===xG.RECURSIVE?e.getRecursiveOperationRpcRemote().routeRequest(t):e.getRouterRpcRemote().routeMessage(t)}updateAndGetRoutablePeers(){NG.trace("getRoutablePeers() sessionId: "+this.sessionId);const e=CG(this.options.routedMessage),t=e?Xj(e):void 0,r=Zj(this.options.routedMessage.target);let n;if(this.options.routingTablesCache.has(r,t)&&this.options.routingTablesCache.get(r,t).getSize()>0)n=this.options.routingTablesCache.get(r,t);else{n=new rq({referenceId:Zj(this.options.routedMessage.target),maxSize:5,allowToContainReferenceId:!0,nodeIdDistanceLimit:t});const e=this.options.getConnections().map((e=>new MG(e,this.options.localPeerDescriptor,this.options.rpcCommunicator)));n.addContacts(e),this.options.routingTablesCache.set(r,n,t)}return n.getClosestContacts().filter((e=>!this.contactedPeers.has(e.getNodeId())&&!this.options.excludedNodeIds.has(e.getNodeId())))}sendMoreRequests(e){if(NG.trace("sendMoreRequests() sessionId: "+this.sessionId),!this.stopped)if(0!==e.length)for(;this.ongoingRequests.size<this.options.parallelism&&e.length>0&&!this.stopped;){const t=e.shift();NG.trace(`Sending routeMessage request to contact: ${Xj(t.getPeerDescriptor())} (sessionId=${this.sessionId})`),this.contactedPeers.add(t.getNodeId()),this.ongoingRequests.add(t.getNodeId()),this.addParallelRootIfSource(t.getNodeId()),setImmediate((async()=>{try{await this.sendRouteMessageRequest(t)?this.onRequestSucceeded():this.onRequestFailed(t.getNodeId())}catch(e){NG.debug("Unable to route message ",{err:e})}finally{NG.trace("sendRouteMessageRequest returned")}}))}else this.emitFailure()}addParallelRootIfSource(e){this.options.mode===xG.RECURSIVE&&eq(this.options.localPeerDescriptor,this.options.routedMessage.sourcePeer)&&this.options.routedMessage.parallelRootNodeIds.push(e)}deleteParallelRootIfSource(e){this.options.mode===xG.RECURSIVE&&eq(this.options.localPeerDescriptor,this.options.routedMessage.sourcePeer)&&Ej(this.options.routedMessage.parallelRootNodeIds,e)}stop(){this.stopped=!0,this.emit("stopped"),this.removeAllListeners()}}const DG=new Bv("RecursiveOperationSessionRpcRemote");class BG extends jz{sendResponse(e,t,r,n){const i={routingPath:e,closestConnectedNodes:t,dataEntries:r,noCloserNodesFound:n};this.getClient().sendResponse(i,this.formDhtRpcOptions()).catch((e=>{DG.trace("Failed to send RecursiveOperationResponse")}))}}const LG=new Bv("RecursiveOperationSessionRpcLocal");class FG{options;constructor(e){this.options=e}async sendResponse(e,t){const r=Xj(t.incomingSourceDescriptor);return LG.trace("RecursiveOperationResponse arrived: "+JSON.stringify(e)),this.options.onResponseReceived(r,e.routingPath,e.closestConnectedNodes,e.dataEntries,e.noCloserNodesFound),{}}}const UG=1e4;class jG extends Sl{id=xF();rpcCommunicator;results;foundData=new Map;allKnownHops=new Set;reportedHops=new Set;timeoutTask;completionEventEmitted=!1;noCloserNodesReceivedCounter=0;noCloserNodesReceivedFrom=new Set;options;constructor(e){super(),this.options=e,this.results=new rq({referenceId:e.targetId,maxSize:10,allowToContainReferenceId:!0}),this.rpcCommunicator=new lK(this.id,e.transport,{rpcRequestTimeout:UG}),this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new FG({onResponseReceived:(e,t,r,n,i)=>{this.onResponseReceived(e,t,r,n,i)}});this.rpcCommunicator.registerRpcNotification(Oq,"sendResponse",((t,r)=>e.sendResponse(t,r)))}start(e){const t=this.wrapRequest(e);this.options.doRouteRequest(t)}wrapRequest(e){const t={sessionId:this.getId(),operation:this.options.operation};return{message:{messageId:xF(),serviceId:e,body:{oneofKind:"recursiveOperationRequest",recursiveOperationRequest:t}},requestId:xF(),target:Yj(this.options.targetId),sourcePeer:this.options.localPeerDescriptor,reachableThrough:[],routingPath:[],parallelRootNodeIds:[]}}isCompleted(){const e=new Set(this.allKnownHops);return this.reportedHops.forEach((t=>{e.delete(t)})),this.noCloserNodesReceivedCounter>=1&&0===e.size&&(!(this.options.operation!==yq.FETCH_DATA||!(this.hasNonStaleData()||this.noCloserNodesReceivedCounter>=this.options.waitedRoutingPathCompletions))||this.options.operation!==yq.FETCH_DATA)}hasNonStaleData(){return Array.from(this.foundData.values()).some((e=>!1===e.stale))}onResponseReceived(e,t,r,n,i){this.addKnownHops(t),t.length>=1&&this.setHopAsReported(t[t.length-1]),r.forEach((e=>{this.results.addContact(new YK(e))})),this.processFoundData(n),(i||this.noCloserNodesReceivedFrom.has(e))&&this.onNoCloserPeersFound(e)}addKnownHops(e){const t=Xj(this.options.localPeerDescriptor);e.forEach((e=>{const r=Xj(e);t!==r&&this.allKnownHops.add(r)}))}setHopAsReported(e){const t=Xj(this.options.localPeerDescriptor),r=Xj(e);t!==r&&this.reportedHops.add(r),this.isCompleted()&&!this.completionEventEmitted&&this.isCompleted()&&(this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0),this.emit("completed"),this.completionEventEmitted=!0)}processFoundData(e){e.forEach((e=>{const t=Zj(e.creator),r=this.foundData.get(t);(!r||r.createdAt<e.createdAt||r.createdAt<=e.createdAt&&e.deleted)&&this.foundData.set(t,e)}))}onNoCloserPeersFound(e){this.noCloserNodesReceivedCounter+=1,this.noCloserNodesReceivedFrom.add(e),this.isCompleted()?(this.emit("completed"),this.completionEventEmitted=!0,this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0)):this.timeoutTask||this.completionEventEmitted||(this.timeoutTask=setTimeout((()=>{this.completionEventEmitted||(this.emit("completed"),this.completionEventEmitted=!0)}),4e3))}getResults(){return{closestNodes:this.results.getClosestContacts().map((e=>e.getPeerDescriptor())),dataEntries:Array.from(this.foundData.values())}}getId(){return this.id}stop(){this.timeoutTask&&(clearTimeout(this.timeoutTask),this.timeoutTask=void 0),this.rpcCommunicator.destroy(),this.emit("completed")}}const qG=new Bv("RouterRpcLocal"),zG=(e,t)=>({requestId:e.requestId,error:t});class KG{options;constructor(e){this.options=e}async routeMessage(e){return this.options.duplicateRequestDetector.isMostLikelyDuplicate(e.requestId)?(qG.trace(`Routing message ${e.requestId} from ${Xj(e.sourcePeer)} to ${Zj(e.target)} is likely a duplicate`),zG(e,vq.DUPLICATE)):(qG.trace(`Processing received routeMessage ${e.requestId}`),this.options.duplicateRequestDetector.add(e.requestId),yw(this.options.localPeerDescriptor.nodeId,e.target)?(qG.trace(`routing message targeted to self ${e.requestId}`),this.options.setForwardingEntries(e),this.options.handleMessage(e.message),zG(e)):this.options.doRouteMessage(e))}async forwardMessage(e){return this.options.duplicateRequestDetector.isMostLikelyDuplicate(e.requestId)?(qG.trace(`Forwarding message ${e.requestId} from ${Xj(e.sourcePeer)} to ${Zj(e.target)} is likely a duplicate`),zG(e,vq.DUPLICATE)):(qG.trace(`Processing received forward routeMessage ${e.requestId}`),this.options.duplicateRequestDetector.add(e.requestId),yw(this.options.localPeerDescriptor.nodeId,e.target)?this.forwardToDestination(e):this.options.doRouteMessage(e,xG.FORWARD))}forwardToDestination(e){qG.trace(`Forwarding found message targeted to self ${e.requestId}`);const t=e.message;return eq(this.options.localPeerDescriptor,t.targetDescriptor)?(this.options.handleMessage(t),zG(e)):this.options.doRouteMessage({...e,requestId:xF(),target:t.targetDescriptor.nodeId})}}const GG=new Bv("RecursiveOperationRpcLocal");class VG{options;constructor(e){this.options=e}async routeRequest(e){if(this.options.isMostLikelyDuplicate(e.requestId))return zG(e,vq.DUPLICATE);const t=Xj(CG(e)??e.sourcePeer);return GG.trace(`Received routeRequest call from ${t}`),this.options.addToDuplicateDetector(e.requestId),this.options.doRouteRequest(e)}}const HG=new Bv("RecursiveOperationManager");class $G{ongoingSessions=new Map;stopped=!1;options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new VG({doRouteRequest:e=>this.doRouteRequest(e),addContact:e=>this.options.addContact(e),isMostLikelyDuplicate:e=>this.options.router.isMostLikelyDuplicate(e),addToDuplicateDetector:e=>this.options.router.addToDuplicateDetector(e)});this.options.rpcCommunicator.registerRpcMethod(jq,qq,"routeRequest",(async t=>this.stopped?zG(t,vq.STOPPED):e.routeRequest(t)))}async execute(e,t,r,n=!0){if(this.stopped)return{closestNodes:[]};const i=new jG({transport:this.options.sessionTransport,targetId:e,localPeerDescriptor:this.options.localPeerDescriptor,waitedRoutingPathCompletions:this.options.connectionsView.getConnectionCount()>1?2:1,operation:t,doRouteRequest:e=>this.doRouteRequest(e,r)});if(0===this.options.connectionsView.getConnectionCount()){const t=Array.from(this.options.localDataStore.values(e));return i.onResponseReceived(Xj(this.options.localPeerDescriptor),[this.options.localPeerDescriptor],[this.options.localPeerDescriptor],t,!0),i.getResults()}if(this.ongoingSessions.set(i.getId(),i),!0===n)try{const e=eE(i,"completed",UG);i.start(this.options.serviceId),await e}catch(e){HG.debug("start failed",{err:e})}else i.start(this.options.serviceId),await Qv(50);if(t===yq.FETCH_DATA){const t=Array.from(this.options.localDataStore.values(e));t.length>0&&this.sendResponse([this.options.localPeerDescriptor],this.options.localPeerDescriptor,i.getId(),[],t,!0)}else t===yq.DELETE_DATA&&this.options.localDataStore.markAsDeleted(e,Xj(this.options.localPeerDescriptor));return this.ongoingSessions.delete(i.getId()),i.stop(),i.getResults()}sendResponse(e,t,r,n,i,s=!1){if(eq(this.options.localPeerDescriptor,t)&&this.ongoingSessions.has(r))this.ongoingSessions.get(r).onResponseReceived(Xj(this.options.localPeerDescriptor),e,n,i,s);else{const o=new lK(r,this.options.sessionTransport,{rpcRequestTimeout:UG});new BG(this.options.localPeerDescriptor,t,o,vz,1e4).sendResponse(e,n,i,s),o.destroy()}}doRouteRequest(e,t){if(this.stopped)return zG(e,vq.STOPPED);const r=Zj(e.target),n=e.message.body.recursiveOperationRequest,i=this.getClosestConnectedNodes(r,5),s=n.operation===yq.FETCH_DATA?Array.from(this.options.localDataStore.values(r)):[];if(n.operation===yq.DELETE_DATA&&this.options.localDataStore.markAsDeleted(r,Xj(e.sourcePeer)),yw(this.options.localPeerDescriptor.nodeId,e.target))return this.sendResponse(e.routingPath,e.sourcePeer,n.sessionId,i,s,!0),zG(e);{const o=this.options.router.doRouteMessage(e,xG.RECURSIVE,t);if(void 0===o.error||o.error===vq.NO_TARGETS){const t=o.error===vq.NO_TARGETS||i.length>0&&CG(e)&&!this.isPeerCloserToIdThanSelf(i[0],r);this.sendResponse(e.routingPath,e.sourcePeer,n.sessionId,i,s,t)}return o}}getClosestConnectedNodes(e,t){const r=this.options.connectionsView.getConnections().map((e=>this.options.createDhtNodeRpcRemote(e))),n=new rq({referenceId:e,maxSize:t,allowToContainReferenceId:!0});return n.addContacts(r),n.getClosestContacts(t).map((e=>e.getPeerDescriptor()))}isPeerCloserToIdThanSelf(e,t){const r=Yj(t);return Qj(e.nodeId,r)<Qj(this.options.localPeerDescriptor.nodeId,r)}stop(){this.stopped=!0,this.ongoingSessions.forEach(((e,t)=>{e.stop()})),this.ongoingSessions.clear()}}const WG=(e,t)=>e+(t??""),JG={max:1e3,maxAge:15e3};class QG{tables=new Mj(JG);get(e,t){return this.tables.get(WG(e,t))}set(e,t,r){this.tables.set(WG(e,r),t)}has(e,t){return this.tables.has(WG(e,t))}onNodeDisconnected(e){this.tables.forEach((t=>t.removeContact(e)))}onNodeConnected(e){this.tables.forEach((t=>t.addContact(e)))}reset(){this.tables.forEach((e=>e.stop())),this.tables.clear()}}const ZG=new Bv("Router");class YG{forwardingTable=new Map;routingTablesCache=new QG;ongoingRoutingSessions=new Map;duplicateRequestDetector=new nq(1e4);stopped=!1;options;messagesRouted=0;messagesSent=0;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new KG({doRouteMessage:(e,t)=>this.doRouteMessage(e,t),setForwardingEntries:e=>this.setForwardingEntries(e),duplicateRequestDetector:this.duplicateRequestDetector,localPeerDescriptor:this.options.localPeerDescriptor,handleMessage:this.options.handleMessage});this.options.rpcCommunicator.registerRpcMethod(jq,qq,"routeMessage",(async t=>this.stopped?zG(t,vq.STOPPED):e.routeMessage(t))),this.options.rpcCommunicator.registerRpcMethod(jq,qq,"forwardMessage",(async t=>this.stopped?zG(t,vq.STOPPED):e.forwardMessage(t)))}send(e,t){e.sourceDescriptor=this.options.localPeerDescriptor;const r=e.targetDescriptor,n=this.forwardingTable.get(Xj(r));if(n&&n.peerDescriptors.length>0){const r={message:e,requestId:xF(),target:n.peerDescriptors[0].nodeId,sourcePeer:this.options.localPeerDescriptor,reachableThrough:t,routingPath:[],parallelRootNodeIds:[]},i=this.doRouteMessage(r,xG.FORWARD);if(void 0!==i.error){const e="Could not forward message with error "+i.error;throw ZG.debug(e),new Error(e)}}else{const n={message:e,requestId:xF(),target:r.nodeId,sourcePeer:this.options.localPeerDescriptor,reachableThrough:t,routingPath:[],parallelRootNodeIds:[]},i=this.doRouteMessage(n,xG.ROUTE);if(void 0!==i.error){const e="Could not route message with error "+i.error;throw ZG.debug(e),new Error(e)}}this.messagesSent+=1}doRouteMessage(e,t=xG.ROUTE,r){if(this.stopped)return zG(e,vq.STOPPED);ZG.trace(`Routing message ${e.requestId} from ${Xj(e.sourcePeer)} to ${Zj(e.target)}`);const n=this.createRoutingSession(e,t,r),i=n.updateAndGetRoutablePeers();if(i.length>0){this.addRoutingSession(n),ZG.trace("starting to raceForEvent from routingSession: "+n.sessionId);const t=tE(n,["routingSucceeded","partialSuccess","routingFailed","stopped"],1e4);return setImmediate((async()=>{try{await t,ZG.trace("raceForEvent ended from routingSession: "+n.sessionId)}catch{ZG.trace("raceForEvent timed out for routingSession "+n.sessionId)}n.stop(),this.removeRoutingSession(n.sessionId)})),n.sendMoreRequests(i),this.messagesRouted+=1,zG(e)}return ZG.trace("no targets",{sessionId:n.sessionId}),zG(e,vq.NO_TARGETS)}createRoutingSession(e,t,r){const n=new Set(e.routingPath.map((e=>Xj(e))));return r&&n.add(r),e.parallelRootNodeIds.forEach((e=>{n.add(e)})),new OG({rpcCommunicator:this.options.rpcCommunicator,localPeerDescriptor:this.options.localPeerDescriptor,routedMessage:e,parallelism:eq(this.options.localPeerDescriptor,e.sourcePeer)?2:1,mode:t,excludedNodeIds:n,routingTablesCache:this.routingTablesCache,getConnections:this.options.getConnections})}isMostLikelyDuplicate(e){return this.duplicateRequestDetector.isMostLikelyDuplicate(e)}addToDuplicateDetector(e){this.duplicateRequestDetector.add(e)}addRoutingSession(e){this.ongoingRoutingSessions.set(e.sessionId,e)}removeRoutingSession(e){this.ongoingRoutingSessions.delete(e)}onNodeConnected(e){const t=new MG(e,this.options.localPeerDescriptor,this.options.rpcCommunicator);this.routingTablesCache.onNodeConnected(t)}onNodeDisconnected(e){this.routingTablesCache.onNodeDisconnected(Xj(e))}resetCache(){this.routingTablesCache.reset()}stop(){this.stopped=!0,this.ongoingRoutingSessions.forEach(((e,t)=>{e.stop()})),this.ongoingRoutingSessions.clear(),this.forwardingTable.forEach((e=>{clearTimeout(e.timeout)})),this.forwardingTable.clear(),this.duplicateRequestDetector.clear(),this.routingTablesCache.reset()}getDiagnosticInfo(){return{messagesRouted:this.messagesRouted,messagesSent:this.messagesSent}}setForwardingEntries(e){const t=e.reachableThrough.filter((e=>!eq(e,this.options.localPeerDescriptor)));if(t.length>0){const r=Xj(e.sourcePeer);if(this.forwardingTable.has(r)){const e=this.forwardingTable.get(r);clearTimeout(e.timeout),this.forwardingTable.delete(r)}const n={peerDescriptors:t,timeout:setTimeout((()=>{this.forwardingTable.delete(r)}),1e4)};this.forwardingTable.set(r,n)}}}class XG{maxTtl;constructor(e){this.maxTtl=e}store=new Map;storeEntry(e){const t=Zj(e.key),r=Zj(e.creator);if(this.store.has(t)||this.store.set(t,new yE((e=>Math.min(e.ttl,this.maxTtl)))),this.store.get(t).has(r)){const n=1e3*e.createdAt.seconds+e.createdAt.nanos/1e6,i=this.store.get(t).get(r);if(1e3*i.createdAt.seconds+i.createdAt.nanos/1e6>=n)return!1}return this.store.get(t).set(r,e),!0}markAsDeleted(e,t){const r=this.store.get(e);if(!r?.has(t))return!1;return r.get(t).deleted=!0,!0}*values(e){if(void 0!==e){const t=this.store.get(e);void 0!==t&&(yield*t.values())}else for(const e of this.store.values())yield*e.values()}keys(){return this.store.keys()}setAllEntriesAsStale(e){this.store.get(e)?.forEach((e=>{e.stale=!0}))}deleteEntry(e,t){const r=this.store.get(e)?.get(t);r&&(this.store.get(e)?.delete(t),0===this.store.get(e)?.size()&&this.store.delete(e))}clear(){this.store.forEach((e=>e.clear())),this.store.clear()}}const eV=new Bv("StoreRpcLocal");class tV{options;constructor(e){this.options=e}async storeData(e){eV.trace("storeData()");const t=Zj(e.key),r=this.isLocalNodeStorer(t);return this.options.localDataStore.storeEntry({key:e.key,data:e.data,creator:e.creator,createdAt:e.createdAt,storedAt:mq.now(),ttl:e.ttl,stale:!r,deleted:!1}),r||this.options.localDataStore.setAllEntriesAsStale(t),{}}async replicateData(e,t){eV.trace("server-side replicateData()");const r=e.entry;this.options.localDataStore.storeEntry(r)&&this.replicateDataToNeighbors(t.incomingSourceDescriptor,e.entry);const n=Zj(r.key);return this.isLocalNodeStorer(n)||this.options.localDataStore.setAllEntriesAsStale(n),eV.trace("server-side replicateData() at end"),{}}isLocalNodeStorer(e){return this.options.getStorers(e).some((e=>eq(e,this.options.localPeerDescriptor)))}replicateDataToNeighbors(e,t){const r=Zj(t.key),n=this.options.getStorers(r);(eq(n[0],this.options.localPeerDescriptor)?n:[n[0]]).filter((t=>!eq(t,e)&&!eq(t,this.options.localPeerDescriptor))).forEach((e=>{setImmediate((()=>{pE((()=>this.options.replicateDataToContact(t,e)))}))}))}}const rV=new Bv("StoreManager");class nV{options;constructor(e){this.options=e,this.registerLocalRpcMethods()}registerLocalRpcMethods(){const e=new tV({localPeerDescriptor:this.options.localPeerDescriptor,localDataStore:this.options.localDataStore,replicateDataToContact:(e,t)=>this.replicateDataToContact(e,t),getStorers:e=>this.getStorers(e)});this.options.rpcCommunicator.registerRpcMethod(Sq,kq,"storeData",(t=>e.storeData(t))),this.options.rpcCommunicator.registerRpcNotification(Iq,"replicateData",((t,r)=>e.replicateData(t,r)))}onContactAdded(e){for(const t of this.options.localDataStore.keys())this.replicateAndUpdateStaleState(t,e)}replicateAndUpdateStaleState(e,t){const r=this.getStorers(e),n=r.filter((e=>!eq(e,t)));eq(n[0],this.options.localPeerDescriptor)?r.some((e=>eq(e,t)))&&setImmediate((async()=>{const r=Array.from(this.options.localDataStore.values(e));await Promise.all(r.map((async e=>this.replicateDataToContact(e,t))))})):r.some((e=>eq(e,this.options.localPeerDescriptor)))||this.options.localDataStore.setAllEntriesAsStale(e)}async replicateDataToContact(e,t){const r=this.options.createRpcRemote(t);try{await r.replicateData({entry:e},!0)}catch(e){rV.trace("replicateData() threw an exception "+e)}}async storeDataToDht(e,t,r){rV.debug(`Storing data to DHT ${this.options.serviceId}`);const n=(await this.options.recursiveOperationManager.execute(e,yq.FIND_CLOSEST_NODES)).closestNodes,i=[],s=this.options.highestTtl,o=mq.now();for(let a=0;a<n.length&&i.length<this.options.redundancyFactor;a++){const c=Yj(e),u=Yj(r);if(eq(this.options.localPeerDescriptor,n[a])){this.options.localDataStore.storeEntry({key:c,data:t,creator:u,createdAt:o,storedAt:mq.now(),ttl:s,stale:!1,deleted:!1}),i.push(n[a]);continue}const l=this.options.createRpcRemote(n[a]);try{await l.storeData({key:c,data:t,creator:u,createdAt:o,ttl:s}),i.push(n[a]),rV.trace("remote.storeData() success")}catch(e){rV.trace("remote.storeData() threw an exception "+e)}}return i}async replicateDataToClosestNodes(){const e=Array.from(this.options.localDataStore.values());await Promise.all(e.map((async e=>{const t=Zj(e.key),r=XK(t,this.options.getNeighbors(),{maxCount:this.options.redundancyFactor});await Promise.all(r.map((async t=>{const r=this.options.createRpcRemote(t);try{await r.replicateData({entry:e},!1)}catch(e){rV.trace("Failed to replicate data in replicateDataToClosestNodes",{err:e})}})))})))}getStorers(e,t){return XK(e,[...this.options.getNeighbors(),this.options.localPeerDescriptor],{maxCount:this.options.redundancyFactor,excludedNodeIds:void 0!==t?new Set([Xj(t)]):void 0})}async destroy(){await this.replicateDataToClosestNodes()}}class iV extends jz{async storeData(e){const t=this.formDhtRpcOptions();try{await this.getClient().storeData(e,t)}catch(e){const t=Xj(this.getPeerDescriptor()),r=Xj(this.getLocalPeerDescriptor());throw new Error(`Could not store data to ${t} from ${r} ${e}`)}}async replicateData(e,t){const r=this.formDhtRpcOptions({timeout:Fz,notification:!0,connect:t});return this.getClient().replicateData(e,r)}}const sV=new Bv("DhtNode");class oV extends Sl{options;rpcCommunicator;transport;localPeerDescriptor;router;storeManager;localDataStore;recursiveOperationManager;peerDiscovery;peerManager;connectionsView;connectionLocker;started=!1;abortController=new AbortController;constructor(e){super(),this.options=aE({serviceId:SG,joinParallelism:3,maxContactCount:200,numberOfNodesPerKBucket:8,joinNoProgressLimit:5,dhtJoinTimeout:6e4,peerDiscoveryQueryBatchSize:5,maxConnections:80,storeHighestTtl:6e4,storeMaxTtl:6e4,networkConnectivityTimeout:1e4,storageRedundancyFactor:5,metricsContext:new $v},e),this.validateOptions(),this.localDataStore=new XG(this.options.storeMaxTtl),this.send=this.send.bind(this)}validateOptions(){if(void 0!==this.options.nodeId){if(!/^[0-9a-fA-F]+$/.test(this.options.nodeId))throw new Error("Invalid nodeId, the nodeId should be a hex string");if(40!==this.options.nodeId.length)throw new Error("Invalid nodeId, the length of the nodeId should be 40")}if(void 0!==this.options.peerDescriptor&&20!==this.options.peerDescriptor.nodeId.length)throw new Error("Invalid peerDescriptor, the length of the nodeId should be 20 bytes");if(void 0!==this.options.transport&&void 0===this.options.connectionsView)throw new Error("connectionsView is required when transport is given")}async start(){if(this.started||this.abortController.signal.aborted)return;if(sV.trace(`Starting new Streamr Network DHT Node with serviceId ${this.options.serviceId}`),this.started=!0,this.options.websocketPortRange=void 0,this.options.peerDescriptor&&(this.options.peerDescriptor.websocket=void 0),this.options.transport)this.transport=this.options.transport,this.connectionsView=this.options.connectionsView,this.connectionLocker=this.options.connectionLocker,this.localPeerDescriptor=this.transport.getLocalPeerDescriptor();else{const e={transport:this,entryPoints:this.options.entryPoints,iceServers:this.options.iceServers,webrtcAllowPrivateAddresses:this.options.webrtcAllowPrivateAddresses,webrtcDatachannelBufferThresholdLow:this.options.webrtcDatachannelBufferThresholdLow,webrtcDatachannelBufferThresholdHigh:this.options.webrtcDatachannelBufferThresholdHigh,webrtcPortRange:this.options.webrtcPortRange,maxMessageSize:this.options.maxMessageSize,websocketServerEnableTls:this.options.websocketServerEnableTls,tlsCertificate:this.options.tlsCertificate,externalIp:this.options.externalIp,autoCertifierUrl:this.options.autoCertifierUrl,autoCertifierConfigFile:this.options.autoCertifierConfigFile,geoIpDatabaseFolder:this.options.geoIpDatabaseFolder,createLocalPeerDescriptor:e=>this.generatePeerDescriptorCallBack(e)};this.options.peerDescriptor?.websocket?(e.websocketHost=this.options.peerDescriptor.websocket.host,e.websocketPortRange={min:this.options.peerDescriptor.websocket.port,max:this.options.peerDescriptor.websocket.port}):this.options.websocketPortRange&&(e.websocketHost=this.options.websocketHost,e.websocketPortRange=this.options.websocketPortRange);const t=new Yz({createConnectorFacade:()=>new WK(e),maxConnections:this.options.maxConnections,metricsContext:this.options.metricsContext,allowIncomingPrivateConnections:this.options.allowIncomingPrivateConnections??!1});await t.start(),this.connectionsView=t,this.connectionLocker=t,this.transport=t}this.rpcCommunicator=new Iz(this.options.serviceId,((e,t)=>this.transport.send(e,t)),{rpcRequestTimeout:this.options.rpcRequestTimeout}),oE(this.transport,"message",(e=>this.handleMessageFromTransport(e)),this.abortController.signal),this.initPeerManager(),this.peerDiscovery=new RG({localPeerDescriptor:this.localPeerDescriptor,joinNoProgressLimit:this.options.joinNoProgressLimit,joinTimeout:this.options.dhtJoinTimeout,serviceId:this.options.serviceId,parallelism:this.options.joinParallelism,connectionLocker:this.connectionLocker,peerManager:this.peerManager,abortSignal:this.abortController.signal,createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e)}),this.router=new YG({rpcCommunicator:this.rpcCommunicator,localPeerDescriptor:this.localPeerDescriptor,handleMessage:e=>this.handleMessageFromRouter(e),getConnections:()=>this.connectionsView.getConnections()}),this.recursiveOperationManager=new $G({rpcCommunicator:this.rpcCommunicator,router:this.router,sessionTransport:this,connectionsView:this.connectionsView,localPeerDescriptor:this.localPeerDescriptor,serviceId:this.options.serviceId,localDataStore:this.localDataStore,addContact:e=>this.peerManager.addContact(e),createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e)}),this.storeManager=new nV({rpcCommunicator:this.rpcCommunicator,recursiveOperationManager:this.recursiveOperationManager,localPeerDescriptor:this.localPeerDescriptor,serviceId:this.options.serviceId,highestTtl:this.options.storeHighestTtl,redundancyFactor:this.options.storageRedundancyFactor,localDataStore:this.localDataStore,getNeighbors:()=>this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),createRpcRemote:e=>new iV(this.localPeerDescriptor,e,this.rpcCommunicator,wz,this.options.rpcRequestTimeout)}),this.on("nearbyContactAdded",(e=>{this.storeManager.onContactAdded(e)})),this.bindRpcLocalMethods();const e=[];!0===this.options.periodicallyPingNeighbors&&e.push((()=>this.peerManager.getNeighbors().map((e=>this.createDhtNodeRpcRemote(e.getPeerDescriptor()))))),!0===this.options.periodicallyPingRingContacts&&e.push((()=>this.peerManager.getRingContacts().getAllContacts()));for(const t of e)await Jv((async()=>{const e=t();await this.peerManager.pruneOfflineNodes(e)}),6e4,!1,this.abortController.signal)}initPeerManager(){this.peerManager=new bG({numberOfNodesPerKBucket:this.options.numberOfNodesPerKBucket,maxContactCount:this.options.maxContactCount,localNodeId:this.getNodeId(),localPeerDescriptor:this.localPeerDescriptor,connectionLocker:this.connectionLocker,lockId:this.options.serviceId,createDhtNodeRpcRemote:e=>this.createDhtNodeRpcRemote(e),hasConnection:e=>this.connectionsView.hasConnection(e),neighborPingLimit:this.options.neighborPingLimit}),this.peerManager.on("nearbyContactRemoved",(e=>{this.emit("nearbyContactRemoved",e)})),this.peerManager.on("nearbyContactAdded",(e=>this.emit("nearbyContactAdded",e))),this.peerManager.on("randomContactRemoved",(e=>this.emit("randomContactRemoved",e))),this.peerManager.on("randomContactAdded",(e=>this.emit("randomContactAdded",e))),this.peerManager.on("ringContactRemoved",(e=>{this.emit("ringContactRemoved",e)})),this.peerManager.on("ringContactAdded",(e=>{this.emit("ringContactAdded",e)})),this.peerManager.on("kBucketEmpty",(()=>{this.peerDiscovery.isJoinOngoing()||(this.options.entryPoints&&this.options.entryPoints.length>0?setImmediate((async()=>{const e=new Set,t=new Set;await Promise.all(this.options.entryPoints.map((r=>this.peerDiscovery.rejoinDht(r,e,t))))})):this.emit("manualRejoinRequired"))})),oE(this.transport,"connected",(e=>{this.router.onNodeConnected(e),this.emit("connected",e)}),this.abortController.signal),oE(this.transport,"disconnected",((e,t)=>{if(void 0!==this.connectionLocker){const r=Xj(e);t?this.peerManager.removeContact(r):this.peerManager.removeNeighbor(r)}this.router.onNodeDisconnected(e),this.emit("disconnected",e,t)}),this.abortController.signal)}bindRpcLocalMethods(){if(!this.started||this.abortController.signal.aborted)return;const e=new tG({peerDiscoveryQueryBatchSize:this.options.peerDiscoveryQueryBatchSize,getNeighbors:()=>this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())),getClosestRingContactsTo:(e,t)=>this.getClosestRingContactsTo(e,t),addContact:e=>this.peerManager.addContact(e),removeContact:e=>this.removeContact(e)});this.rpcCommunicator.registerRpcMethod(Tq,_q,"getClosestPeers",((t,r)=>e.getClosestPeers(t,r))),this.rpcCommunicator.registerRpcMethod(Nq,Mq,"getClosestRingPeers",((t,r)=>e.getClosestRingPeers(t,r))),this.rpcCommunicator.registerRpcMethod(Dq,Bq,"ping",((t,r)=>e.ping(t,r))),this.rpcCommunicator.registerRpcNotification(Lq,"leaveNotice",((t,r)=>e.leaveNotice(r)));const t=new iG({executeRecursiveOperation:(e,t,r)=>this.recursiveOperationManager.execute(e,t,r),storeDataToDht:(e,t,r)=>this.storeDataToDht(e,t,r)});this.rpcCommunicator.registerRpcMethod(nz,iz,"externalFetchData",((e,r)=>t.externalFetchData(e,r)),{timeout:1e4}),this.rpcCommunicator.registerRpcMethod(Rq,Cq,"externalStoreData",((e,r)=>t.externalStoreData(e,r)),{timeout:1e4})}handleMessageFromTransport(e){e.serviceId===this.options.serviceId&&this.rpcCommunicator?.handleMessageFromPeer(e)}handleMessageFromRouter(e){e.serviceId===this.options.serviceId?this.rpcCommunicator?.handleMessageFromPeer(e):this.emit("message",e)}async generatePeerDescriptorCallBack(e){if(void 0!==this.options.peerDescriptor)this.localPeerDescriptor=this.options.peerDescriptor;else{let t;void 0!==this.options.region?(t=this.options.region,sV.debug(`Using region ${t} from options when generating local PeerDescriptor`)):void 0!==e.latitude&&void 0!==e.longitude?(t=((e,t)=>{const r=[];return Object.keys(Lj).forEach((n=>{const i=Lj[n],s=Bj({latitude:e,longitude:t},{latitude:i[1],longitude:i[2]});r.push([i[0],s])})),r.sort(((e,t)=>e[1]-t[1])),r[0][0]})(e.latitude,e.longitude),sV.debug(`Using region ${t} from GeoIP when generating local PeerDescriptor`)):(t=await(async(e=36e5)=>{if(void 0===zj||void 0===Kj||Date.now()-Kj>e){const e=await Gj();return zj=e,Kj=Date.now(),e}return zj})(),sV.debug(`Using region ${t} from CDN when generating local PeerDescriptor`)),this.localPeerDescriptor=await ZK(e,t,this.options.nodeId)}return this.localPeerDescriptor}getClosestContacts(e){return this.peerManager.getNearbyContacts().getClosestContacts(e).map((e=>e.getPeerDescriptor()))}getRandomContacts(e){return this.peerManager.getRandomContacts().getContacts(e).map((e=>e.getPeerDescriptor()))}getRingContacts(){const e=this.peerManager.getRingContacts().getClosestContacts();return{left:e.left.map((e=>e.getPeerDescriptor())),right:e.right.map((e=>e.getPeerDescriptor()))}}getClosestRingContactsTo(e,t){const r=this.peerManager.getClosestRingContactsTo(e,t);return{left:r.left.map((e=>e.getPeerDescriptor())),right:r.right.map((e=>e.getPeerDescriptor()))}}getNodeId(){return Xj(this.localPeerDescriptor)}getNeighborCount(){return this.peerManager.getNeighborCount()}removeContact(e){this.started&&this.peerManager.removeContact(e)}async send(e){if(!this.started||this.abortController.signal.aborted)return;const t=this.peerDiscovery.isJoinOngoing()?this.getConnectedEntryPoints():[];this.router.send(e,t)}getConnectedEntryPoints(){return void 0!==this.options.entryPoints?this.options.entryPoints.filter((e=>this.connectionsView.hasConnection(Xj(e)))):[]}async joinDht(e,t,r){if(!this.started)throw new Error("Cannot join DHT before calling start() on DhtNode");await this.peerDiscovery.joinDht(e,t,r)}async joinRing(){if(!this.started)throw new Error("Cannot join ring before calling start() on DhtNode");await this.peerDiscovery.joinRing()}async storeDataToDht(e,t,r){return this.executeRecursiveOperation((()=>this.storeManager.storeDataToDht(e,t,r??this.getNodeId())),(r=>this.storeDataToDhtViaPeer(e,t,r)))}async storeDataToDhtViaPeer(e,t,r){const n=new oG(this.localPeerDescriptor,r,this.rpcCommunicator,kz);return await n.storeData(e,t)}async fetchDataFromDht(e){return this.executeRecursiveOperation((async()=>(await this.recursiveOperationManager.execute(e,yq.FETCH_DATA)).dataEntries??[]),(t=>this.fetchDataFromDhtViaPeer(e,t)))}async fetchDataFromDhtViaPeer(e,t){const r=new oG(this.localPeerDescriptor,t,this.rpcCommunicator,kz);return await r.externalFetchData(e)}async executeRecursiveOperation(e,t){const r=this.getConnectedEntryPoints();return this.peerDiscovery.isJoinOngoing()&&r.length>0?t(oA(r)):e()}async deleteDataFromDht(e,t){this.abortController.signal.aborted||await this.recursiveOperationManager.execute(e,yq.DELETE_DATA,void 0,t)}async findClosestNodesFromDht(e){return this.executeRecursiveOperation((async()=>(await this.recursiveOperationManager.execute(e,yq.FIND_CLOSEST_NODES)).closestNodes),(t=>this.findClosestNodesViaPeer(e,t)))}async findClosestNodesViaPeer(e,t){const r=new oG(this.localPeerDescriptor,t,this.rpcCommunicator,kz);return await r.externalFindClosestNode(e)}getTransport(){return this.transport}getLocalPeerDescriptor(){return this.localPeerDescriptor}getNeighbors(){return this.started?this.peerManager.getNeighbors().map((e=>e.getPeerDescriptor())):[]}getConnectionsView(){return this.connectionsView}getLocalLockedConnectionCount(){return this.connectionLocker.getLocalLockedConnectionCount()}getRemoteLockedConnectionCount(){return this.connectionLocker.getRemoteLockedConnectionCount()}getWeakLockedConnectionCount(){return this.connectionLocker.getWeakLockedConnectionCount()}async waitForNetworkConnectivity(){await iE((()=>this.connectionsView.getConnectionCount()>0),this.options.networkConnectivityTimeout,100,this.abortController.signal)}hasJoined(){return this.peerDiscovery.isJoinCalled()}getDiagnosticInfo(){return{localPeerDescriptor:this.localPeerDescriptor,transport:this.transport.getDiagnosticInfo(),router:this.router.getDiagnosticInfo(),neighborCount:this.getNeighborCount(),nearbyContactCount:Array.from(this.peerManager.getNearbyContacts().getAllContactsInUndefinedOrder()).length,randomContactCount:this.peerManager.getRandomContacts().getSize()}}async stop(){!this.abortController.signal.aborted&&this.started&&(sV.trace("stop()"),this.abortController.abort(),await this.storeManager.destroy(),this.localDataStore.clear(),this.peerManager?.stop(),this.rpcCommunicator.stop(),this.router.stop(),this.recursiveOperationManager.stop(),void 0===this.options.transport&&await this.transport.stop(),this.transport=void 0,this.connectionLocker=void 0,this.removeAllListeners())}createDhtNodeRpcRemote(e){return new nG(this.localPeerDescriptor,e,this.options.serviceId,this.rpcCommunicator,this.options.rpcRequestTimeout)}}var aV,cV,uV,lV,hV,dV,fV,pV,gV,mV;function yV(){if(lV)return uV;return lV=1,uV=function(e,t,r){return e==e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e},uV}!function(e){e[e.eu_central_1=0]="eu_central_1",e[e.eu_west_1=1]="eu_west_1",e[e.eu_west_2=2]="eu_west_2",e[e.eu_west_3=3]="eu_west_3",e[e.eu_north_1=4]="eu_north_1",e[e.us_east_1=5]="us_east_1",e[e.us_east_2=6]="us_east_2",e[e.us_west_1=7]="us_west_1",e[e.us_west_2=8]="us_west_2",e[e.ca_central_1=9]="ca_central_1",e[e.ap_south_1=10]="ap_south_1",e[e.ap_northeast_2=11]="ap_northeast_2",e[e.ap_southeast_1=12]="ap_southeast_1",e[e.ap_southeast_2=13]="ap_southeast_2",e[e.ap_northeast_1=14]="ap_northeast_1",e[e.sa_east_1=15]="sa_east_1"}(aV||(aV={})),new Bv("Simulator"),function(e){e.NONE="NONE",e.RANDOM="RANDOM",e.REAL="REAL",e.FIXED="FIXED"}(cV||(cV={}));var bV=function(){if(mV)return gV;mV=1;var e=function(){if(dV)return hV;dV=1;var e=yV(),t=Th(),r=$U();return hV=function(n,i){return r(t(n),e(i,0,n.length))},hV}(),t=function(){if(pV)return fV;pV=1;var e=yV(),t=$U(),r=nA();return fV=function(n,i){var s=r(n);return t(s,e(i,0,s.length))},fV}(),r=qu(),n=_d(),i=Ue();return gV=function(s,o,a){return o=(a?n(s,o,a):void 0===o)?1:i(o),(r(s)?e:t)(s,o)},gV}(),wV=n(bV);class vV{tail;head;length=0;static create(e=[]){return new vV(e)}constructor(e=[]){for(const t of e)this.push(t)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");const t=e.next,r=e.prev;return t&&(t.prev=r),r&&(r.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=r),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,t}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);const t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);const t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let t=0,r=e.length;t<r;t++)AV(this,e[t]);return this.length}unshift(...e){for(var t=0,r=e.length;t<r;t++)SV(this,e[t]);return this.length}pop(){if(!this.tail)return;const e=this.tail.value,t=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,t.list=void 0,this.length--,e}shift(){if(!this.head)return;const e=this.head.value,t=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,t.list=void 0,this.length--,e}forEach(e,t){t=t||this;for(let r=this.head,n=0;r;n++)e.call(t,r.value,n,this),r=r.next}forEachReverse(e,t){t=t||this;for(let r=this.tail,n=this.length-1;r;n--)e.call(t,r.value,n,this),r=r.prev}get(e){let t=0,r=this.head;for(;r&&t<e;t++)r=r.next;if(t===e&&r)return r.value}getReverse(e){let t=0,r=this.tail;for(;r&&t<e;t++)r=r.prev;if(t===e&&r)return r.value}map(e,t){t=t||this;const r=new vV;for(let n=this.head;n;)r.push(e.call(t,n.value,this)),n=n.next;return r}mapReverse(e,t){t=t||this;var r=new vV;for(let n=this.tail;n;)r.push(e.call(t,n.value,this)),n=n.prev;return r}reduce(e,t){let r,n=this.head;if(arguments.length>1)r=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;n;i++)r=e(r,n.value,i),n=n.next;return r}reduceReverse(e,t){let r,n=this.tail;if(arguments.length>1)r=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(let t=this.length-1;n;t--)r=e(r,n.value,t),n=n.prev;return r}toArray(){const e=new Array(this.length);for(let t=0,r=this.head;r;t++)e[t]=r.value,r=r.next;return e}toArrayReverse(){const e=new Array(this.length);for(let t=0,r=this.tail;r;t++)e[t]=r.value,r=r.prev;return e}slice(e=0,t=this.length){t<0&&(t+=this.length),e<0&&(e+=this.length);const r=new vV;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);let n=this.head,i=0;for(i=0;n&&i<e;i++)n=n.next;for(;n&&i<t;i++,n=n.next)r.push(n.value);return r}sliceReverse(e=0,t=this.length){t<0&&(t+=this.length),e<0&&(e+=this.length);const r=new vV;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);let n=this.length,i=this.tail;for(;i&&n>t;n--)i=i.prev;for(;i&&n>e;n--,i=i.prev)r.push(i.value);return r}splice(e,t=0,...r){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let n=this.head;for(let t=0;n&&t<e;t++)n=n.next;const i=[];for(let e=0;n&&e<t;e++)i.push(n.value),n=this.removeNode(n);n?n!==this.tail&&(n=n.prev):n=this.tail;for(const e of r)n=EV(this,n,e);return i}reverse(){const e=this.head,t=this.tail;for(let t=e;t;t=t.prev){const e=t.prev;t.prev=t.next,t.next=e}return this.head=t,this.tail=e,this}}function EV(e,t,r){const n=t,i=t?t.next:e.head,s=new kV(r,n,i,e);return void 0===s.next&&(e.tail=s),void 0===s.prev&&(e.head=s),e.length++,s}function AV(e,t){e.tail=new kV(t,e.tail,void 0,e),e.head||(e.head=e.tail),e.length++}function SV(e,t){e.head=new kV(t,void 0,e.head,e),e.tail||(e.tail=e.head),e.length++}class kV{list;next;prev;value;constructor(e,t,r,n){this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}}class RV{rpcCommunicator;constructor(e){this.rpcCommunicator=new lK("external-network-service",e)}registerRpcMethod(e,t,r,n){this.rpcCommunicator.registerRpcMethod(e,t,r,n)}createRpcClient(e){return iU(new e(this.rpcCommunicator.getRpcClientTransport()))}destroy(){this.rpcCommunicator.destroy()}}const CV=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}},IV=new Bv("PeerDescriptorStoreManager");class PV{abortController;options;isLocalNodeStored_=!1;constructor(e){this.options=e,this.abortController=new AbortController}async fetchNodes(){IV.trace("Fetch data",{key:this.options.key});try{const e=await this.options.fetchDataFromDht(this.options.key);return e.filter((e=>!e.deleted)).map((e=>CV.unpack(e.data,Fq)))}catch{return[]}}async storeAndKeepLocalNode(){this.abortController.signal.aborted||(this.isLocalNodeStored_=!0,await this.storeLocalNode(),await this.keepLocalNode())}async storeLocalNode(){const e=this.options.localPeerDescriptor,t=CV.pack(e,Fq);try{await this.options.storeDataToDht(this.options.key,t)}catch{IV.warn("Failed to store local node",{key:this.options.key})}}async keepLocalNode(){await Jv((async()=>{IV.trace("Attempting to keep local node",{key:this.options.key});try{const e=await this.fetchNodes();(e.length<8||e.some((e=>eq(e,this.options.localPeerDescriptor))))&&await this.storeLocalNode()}catch{IV.debug("Failed to keep local node",{key:this.options.key})}}),this.options.storeInterval??6e4,!1,this.abortController.signal)}isLocalNodeStored(){return this.isLocalNodeStored_}async destroy(){this.abortController.abort(),await this.options.deleteDataFromDht(this.options.key,!1)}}const TV=new Bv("StreamPartNetworkSplitAvoidance");class _V{abortController;options;excludedNodes=new Set;running=!1;constructor(e){this.options=e,this.abortController=new AbortController}async avoidNetworkSplit(){this.running=!0,await(async(e,t,r,n=500,i=6)=>{for(let s=1;s<=i;s++){if(r.aborted)return;const i=n*2**s;try{await e()}catch{TV.trace(`${t} failed, retrying in ${i} ms`)}try{await Qv(i,r)}catch(e){TV.trace(`${e}`)}}})((async()=>{const e=(await this.options.discoverEntryPoints()).filter((e=>!this.excludedNodes.has(Xj(e))));if(await this.options.discoveryLayerNode.joinDht(e,!1,!1),this.options.discoveryLayerNode.getNeighborCount()<4){throw e.filter((e=>!this.options.discoveryLayerNode.getNeighbors().some((t=>eq(t,e))))).map((e=>Xj(e))).forEach((e=>this.excludedNodes.add(e))),new Error("Network split is still possible")}}),"avoid network split",this.abortController.signal,this.options.exponentialRunOfBaseDelay),this.running=!1,this.excludedNodes.clear(),TV.trace("Network split avoided")}isRunning(){return this.running}destroy(){this.abortController.abort()}}class NV{abortController;discoveryLayerNode;peerDescriptorStoreManager;constructor(e,t){this.discoveryLayerNode=e,this.peerDescriptorStoreManager=t}async reconnect(e=3e4){this.abortController=new AbortController,await Jv((async()=>{const e=await this.peerDescriptorStoreManager.fetchNodes();await this.discoveryLayerNode.joinDht(e),!this.peerDescriptorStoreManager.isLocalNodeStored()&&e.length<8&&await this.peerDescriptorStoreManager.storeAndKeepLocalNode(),this.discoveryLayerNode.getNeighborCount()>0&&this.abortController.abort()}),e,!0,this.abortController.signal)}isRunning(){return!!this.abortController&&!this.abortController.signal.aborted}destroy(){this.abortController?.abort()}}const MV=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var xV;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(xV||(xV={}));const OV=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>CV},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",xV]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>MV}])}};const DV=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var BV,LV,FV,UV,jV,qV;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(BV||(BV={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(LV||(LV={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}(FV||(FV={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(UV||(UV={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(jV||(jV={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(qV||(qV={}));const zV=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>CV},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>DV},{no:5,name:"ttl",kind:"scalar",T:13}])}};const KV=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const GV=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>CV}])}};const VV=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>nH}])}};const HV=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>$V}])}};const $V=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>CV},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>DV},{no:5,name:"storedAt",kind:"message",T:()=>DV},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const WV=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const JV=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>nH},{no:2,name:"requestId",kind:"scalar",T:9}])}};const QV=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const ZV=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>nH},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>nH},{no:3,name:"requestId",kind:"scalar",T:9}])}};const YV=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",BV]}])}};const XV=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>nH},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>$V},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>nH}])}};const eH=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const tH=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const rH=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const nH=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",LV]},{no:3,name:"udp",kind:"message",T:()=>iH},{no:4,name:"tcp",kind:"message",T:()=>iH},{no:5,name:"websocket",kind:"message",T:()=>iH},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const iH=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const sH=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>nH},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>hH},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>nH},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>nH},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const oH=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",UV]}])}};const aH=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const cH=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>iH},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const uH=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>nH},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>nH},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const lH=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>nH},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",jV]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const hH=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>nH},{no:3,name:"targetDescriptor",kind:"message",T:()=>nH},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>OV},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>aH},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>cH},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>uH},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>lH},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>YV}])}};const dH=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const fH=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const pH=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const gH=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const mH=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const yH=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const bH=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const wH=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const vH=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",qV]}])}};const EH=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const AH=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const SH=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>$V}])}};const kH=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const RH=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>nH}])}};var CH,IH,PH,TH,_H;new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:WV,O:JV},{name:"getClosestRingPeers",options:{},I:QV,O:ZV},{name:"ping",options:{},I:eH,O:tH},{name:"leaveNotice",options:{},I:rH,O:MV}]),new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:sH,O:oH},{name:"forwardMessage",options:{},I:sH,O:oH}]),new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:sH,O:oH}]),new vF("dht.StoreRpc",[{name:"storeData",options:{},I:zV,O:KV},{name:"replicateData",options:{},I:HV,O:MV}]),new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:XV,O:MV}]),new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:dH,O:MV}]),new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:fH,O:MV},{name:"rtcOffer",options:{},I:pH,O:MV},{name:"rtcAnswer",options:{},I:gH,O:MV},{name:"iceCandidate",options:{},I:mH,O:MV}]),new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:yH,O:wH},{name:"unlockRequest",options:{},I:bH,O:MV},{name:"gracefulDisconnect",options:{},I:vH,O:MV},{name:"setPrivate",options:{},I:EH,O:MV}]),new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:AH,O:SH},{name:"externalStoreData",options:{},I:GV,O:VV},{name:"externalFindClosestNodes",options:{},I:kH,O:RH}]),e.ContentType=void 0,(CH=e.ContentType||(e.ContentType={}))[CH.JSON=0]="JSON",CH[CH.BINARY=1]="BINARY",e.EncryptionType=void 0,(IH=e.EncryptionType||(e.EncryptionType={}))[IH.NONE=0]="NONE",IH[IH.AES=1]="AES",function(e){e[e.RSA=0]="RSA",e[e.ML_KEM=1]="ML_KEM"}(PH||(PH={})),e.SignatureType=void 0,(TH=e.SignatureType||(e.SignatureType={}))[TH.ECDSA_SECP256K1_LEGACY=0]="ECDSA_SECP256K1_LEGACY",TH[TH.ECDSA_SECP256K1_EVM=1]="ECDSA_SECP256K1_EVM",TH[TH.ERC_1271=2]="ERC_1271",TH[TH.ML_DSA_87=3]="ML_DSA_87",TH[TH.ECDSA_SECP256R1=4]="ECDSA_SECP256R1",e.ProxyDirection=void 0,(_H=e.ProxyDirection||(e.ProxyDirection={}))[_H.PUBLISH=0]="PUBLISH",_H[_H.SUBSCRIBE=1]="SUBSCRIBE";const NH=new class extends wF{constructor(){super("MessageID",[{no:1,name:"streamId",kind:"scalar",T:9},{no:2,name:"streamPartition",kind:"scalar",T:5},{no:3,name:"timestamp",kind:"scalar",T:3,L:2},{no:4,name:"sequenceNumber",kind:"scalar",T:5},{no:5,name:"publisherId",kind:"scalar",T:12},{no:6,name:"messageChainId",kind:"scalar",T:9}])}};const MH=new class extends wF{constructor(){super("MessageRef",[{no:1,name:"timestamp",kind:"scalar",T:3,L:2},{no:2,name:"sequenceNumber",kind:"scalar",T:5}])}};const xH=new class extends wF{constructor(){super("StreamMessage",[{no:1,name:"messageId",kind:"message",T:()=>NH},{no:2,name:"previousMessageRef",kind:"message",T:()=>MH},{no:3,name:"signature",kind:"scalar",T:12},{no:4,name:"signatureType",kind:"enum",T:()=>["SignatureType",e.SignatureType]},{no:5,name:"contentMessage",kind:"message",oneof:"body",T:()=>OH},{no:6,name:"groupKeyRequest",kind:"message",oneof:"body",T:()=>DH},{no:7,name:"groupKeyResponse",kind:"message",oneof:"body",T:()=>BH}])}};const OH=new class extends wF{constructor(){super("ContentMessage",[{no:1,name:"content",kind:"scalar",T:12},{no:2,name:"contentType",kind:"enum",T:()=>["ContentType",e.ContentType]},{no:3,name:"encryptionType",kind:"enum",T:()=>["EncryptionType",e.EncryptionType]},{no:4,name:"groupKeyId",kind:"scalar",opt:!0,T:9},{no:5,name:"newGroupKey",kind:"message",T:()=>LH}])}};const DH=new class extends wF{constructor(){super("GroupKeyRequest",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"recipientId",kind:"scalar",T:12},{no:3,name:"publicKey",kind:"scalar",T:12},{no:4,name:"groupKeyIds",kind:"scalar",repeat:2,T:9},{no:5,name:"encryptionType",kind:"enum",T:()=>["AsymmetricEncryptionType",PH]}])}};const BH=new class extends wF{constructor(){super("GroupKeyResponse",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"recipientId",kind:"scalar",T:12},{no:3,name:"groupKeys",kind:"message",repeat:2,T:()=>LH},{no:4,name:"encryptionType",kind:"enum",T:()=>["AsymmetricEncryptionType",PH]}])}};const LH=new class extends wF{constructor(){super("EncryptedGroupKey",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:12}])}};const FH=new class extends wF{constructor(){super("StreamPartHandshakeRequest",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"requestId",kind:"scalar",T:9},{no:3,name:"concurrentHandshakeNodeId",kind:"scalar",opt:!0,T:12},{no:4,name:"neighborNodeIds",kind:"scalar",repeat:2,T:12},{no:5,name:"interleaveNodeId",kind:"scalar",opt:!0,T:12}])}};const UH=new class extends wF{constructor(){super("StreamPartHandshakeResponse",[{no:1,name:"accepted",kind:"scalar",T:8},{no:2,name:"requestId",kind:"scalar",T:9},{no:3,name:"interleaveTargetDescriptor",kind:"message",T:()=>nH}])}};const jH=new class extends wF{constructor(){super("InterleaveRequest",[{no:1,name:"interleaveTargetDescriptor",kind:"message",T:()=>nH}])}};const qH=new class extends wF{constructor(){super("InterleaveResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const zH=new class extends wF{constructor(){super("LeaveStreamPartNotice",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"isEntryPoint",kind:"scalar",T:8}])}};const KH=new class extends wF{constructor(){super("NeighborUpdate",[{no:1,name:"streamPartId",kind:"scalar",T:9},{no:2,name:"removeMe",kind:"scalar",T:8},{no:3,name:"neighborDescriptors",kind:"message",repeat:2,T:()=>nH}])}};const GH=new class extends wF{constructor(){super("ProxyConnectionRequest",[{no:1,name:"direction",kind:"enum",opt:!0,T:()=>["ProxyDirection",e.ProxyDirection]},{no:2,name:"userId",kind:"scalar",T:12}])}};const VH=new class extends wF{constructor(){super("ProxyConnectionResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const HH=new class extends wF{constructor(){super("TemporaryConnectionRequest",[])}};const $H=new class extends wF{constructor(){super("TemporaryConnectionResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const WH=new class extends wF{constructor(){super("CloseTemporaryConnection",[])}};const JH=new class extends wF{constructor(){super("StreamPartitionInfo",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"controlLayerNeighbors",kind:"message",repeat:2,T:()=>nH},{no:3,name:"deprecatedContentDeliveryLayerNeighbors",kind:"message",repeat:2,T:()=>nH},{no:4,name:"contentDeliveryLayerNeighbors",kind:"message",repeat:2,T:()=>QH}])}};const QH=new class extends wF{constructor(){super("ContentDeliveryLayerNeighborInfo",[{no:1,name:"peerDescriptor",kind:"message",T:()=>nH},{no:2,name:"rtt",kind:"scalar",opt:!0,T:5}])}};const ZH=new class extends wF{constructor(){super("ControlLayerInfo",[{no:1,name:"neighbors",kind:"message",repeat:2,T:()=>nH},{no:2,name:"connections",kind:"message",repeat:2,T:()=>nH}])}};const YH=new class extends wF{constructor(){super("NodeInfoRequest",[])}};const XH=new class extends wF{constructor(){super("NodeInfoResponse",[{no:1,name:"peerDescriptor",kind:"message",T:()=>nH},{no:2,name:"streamPartitions",kind:"message",repeat:2,T:()=>JH},{no:3,name:"controlLayer",kind:"message",T:()=>ZH},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const e$=new class extends wF{constructor(){super("PauseNeighborRequest",[{no:1,name:"messageChainId",kind:"scalar",T:9}])}};const t$=new class extends wF{constructor(){super("PauseNeighborResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const r$=new class extends wF{constructor(){super("ResumeNeighborRequest",[{no:1,name:"messageChainId",kind:"scalar",T:9},{no:2,name:"fromTimestamp",kind:"scalar",T:3,L:2}])}},n$=new vF("ContentDeliveryRpc",[{name:"sendStreamMessage",options:{},I:xH,O:MV},{name:"leaveStreamPartNotice",options:{},I:zH,O:MV}]),i$=new vF("ProxyConnectionRpc",[{name:"requestConnection",options:{},I:GH,O:VH}]),s$=new vF("HandshakeRpc",[{name:"handshake",options:{},I:FH,O:UH},{name:"interleaveRequest",options:{},I:jH,O:qH}]),o$=new vF("NeighborUpdateRpc",[{name:"neighborUpdate",options:{},I:KH,O:KH}]),a$=new vF("TemporaryConnectionRpc",[{name:"openConnection",options:{},I:HH,O:$H},{name:"closeConnection",options:{},I:WH,O:MV}]),c$=new vF("NodeInfoRpc",[{name:"getInfo",options:{},I:YH,O:XH}]),u$=new vF("PlumtreeRpc",[{name:"pauseNeighbor",options:{},I:e$,O:t$},{name:"resumeNeighbor",options:{},I:r$,O:MV},{name:"sendMetadata",options:{},I:NH,O:MV}]);class l${_transport;typeName=n$.typeName;methods=n$.methods;options=n$.options;constructor(e){this._transport=e}sendStreamMessage(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}leaveStreamPartNotice(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class h${_transport;typeName=i$.typeName;methods=i$.methods;options=i$.options;constructor(e){this._transport=e}requestConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class d${_transport;typeName=s$.typeName;methods=s$.methods;options=s$.options;constructor(e){this._transport=e}handshake(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}interleaveRequest(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class f${_transport;typeName=o$.typeName;methods=o$.methods;options=o$.options;constructor(e){this._transport=e}neighborUpdate(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class p${_transport;typeName=a$.typeName;methods=a$.methods;options=a$.options;constructor(e){this._transport=e}openConnection(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}closeConnection(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class g${_transport;typeName=c$.typeName;methods=c$.methods;options=c$.options;constructor(e){this._transport=e}getInfo(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}class m${_transport;typeName=u$.typeName;methods=u$.methods;options=u$.options;constructor(e){this._transport=e}pauseNeighbor(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}resumeNeighbor(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}sendMetadata(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}const y$=new Bv("ContentDeliveryRpcRemote");class b$ extends jz{rtt;async sendStreamMessage(e,t){const r=this.formDhtRpcOptions({notification:!0,bufferWhileConnecting:t});this.getClient().sendStreamMessage(e,r).catch((()=>{y$.trace("Failed to sendStreamMessage")}))}leaveStreamPartNotice(e,t){const r={streamPartId:e,isEntryPoint:t},n=this.formDhtRpcOptions({notification:!0});this.getClient().leaveStreamPartNotice(r,n).catch((()=>{y$.debug("Failed to send leaveStreamPartNotice")}))}setRtt(e){this.rtt=e}getRtt(){return this.rtt}}const w$=new Bv("HandshakeRpcLocal");class v${options;constructor(e){this.options=e}async handshake(e,t){return this.handleRequest(e,t)}handleRequest(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.ongoingInterleaves.has(n)?this.rejectHandshake(e):this.options.neighbors.has(n)||this.options.ongoingHandshakes.has(n)||this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount?this.acceptHandshake(e,r):this.options.neighbors.size(void 0!==e.interleaveNodeId?[Zj(e.interleaveNodeId)]:[])-this.options.ongoingInterleaves.size>=2&&this.options.neighbors.size()<=this.options.maxNeighborCount?this.acceptHandshakeWithInterleaving(e,r):this.rejectHandshake(e)}acceptHandshake(e,t){const r={requestId:e.requestId,accepted:!0};return this.options.neighbors.add(this.options.createContentDeliveryRpcRemote(t)),r}rejectHandshake(e){return{requestId:e.requestId,accepted:!1}}acceptHandshakeWithInterleaving(e,t){const r=[];e.neighborNodeIds.forEach((e=>r.push(Zj(e)))),this.options.ongoingInterleaves.forEach((e=>r.push(e))),r.push(Xj(t)),void 0!==e.interleaveNodeId&&r.push(Zj(e.interleaveNodeId));const n=this.options.neighbors.getLast(r),i=n?n.getPeerDescriptor():void 0;if(n){const e=Xj(n.getPeerDescriptor()),r=this.options.createRpcRemote(n.getPeerDescriptor());this.options.ongoingInterleaves.add(e),r.interleaveRequest(t).then((e=>{e.accepted&&this.options.neighbors.remove(Xj(i))})).catch((()=>{})).finally((()=>{this.options.ongoingInterleaves.delete(e)}))}return this.options.neighbors.add(this.options.createContentDeliveryRpcRemote(t)),{requestId:e.requestId,accepted:!0,interleaveTargetDescriptor:i}}async interleaveRequest(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);try{return await this.options.handshakeWithInterleaving(e.interleaveTargetDescriptor,n),this.options.neighbors.remove(n),{accepted:!0}}catch(t){return w$.debug(`interleaveRequest to ${Xj(e.interleaveTargetDescriptor)} failed`,{err:t}),{accepted:!1}}}}const E$=new Bv("HandshakeRpcRemote");class A$ extends jz{async handshake(e,t,r,n){const i={streamPartId:e,requestId:xF(),neighborNodeIds:t.map((e=>Yj(e))),concurrentHandshakeNodeId:void 0!==r?Yj(r):void 0,interleaveNodeId:void 0!==n?Yj(n):void 0};try{const e=await this.getClient().handshake(i,this.formDhtRpcOptions());return{accepted:e.accepted,interleaveTargetDescriptor:e.interleaveTargetDescriptor}}catch(e){return E$.debug(`handshake to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),{accepted:!1}}}async interleaveRequest(e){const t={interleaveTargetDescriptor:e},r=this.formDhtRpcOptions({connect:!1,timeout:1e4});try{return{accepted:(await this.getClient().interleaveRequest(t,r)).accepted}}catch(e){return E$.debug(`interleaveRequest to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),{accepted:!1}}}}const S$=new Bv("Handshaker");class k${options;rpcLocal;constructor(e){this.options=e,this.rpcLocal=new v$({streamPartId:this.options.streamPartId,neighbors:this.options.neighbors,ongoingHandshakes:this.options.ongoingHandshakes,ongoingInterleaves:new Set,maxNeighborCount:this.options.maxNeighborCount,handshakeWithInterleaving:(e,t)=>this.handshakeWithInterleaving(e,t),createRpcRemote:e=>this.createRpcRemote(e),createContentDeliveryRpcRemote:e=>this.createContentDeliveryRpcRemote(e)}),this.options.rpcCommunicator.registerRpcMethod(jH,qH,"interleaveRequest",((e,t)=>this.rpcLocal.interleaveRequest(e,t)),{timeout:1e4}),this.options.rpcCommunicator.registerRpcMethod(FH,UH,"handshake",((e,t)=>this.rpcLocal.handshake(e,t)))}async attemptHandshakesOnContacts(e){return this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount-2?(S$.trace("Attempting parallel handshakes with 2 targets"),this.selectParallelTargetsAndHandshake(e)):this.options.neighbors.size()+this.options.ongoingHandshakes.size<this.options.maxNeighborCount?(S$.trace("Attempting handshake with new target"),this.selectNewTargetAndHandshake(e)):e}async selectParallelTargetsAndHandshake(e){const t=e.concat(this.options.neighbors.getIds()),r=this.selectParallelTargets(t);return r.forEach((e=>this.options.ongoingHandshakes.add(Xj(e.getPeerDescriptor())))),this.doParallelHandshakes(r,t)}selectParallelTargets(e){const t=new Map,r=()=>[...e,...Array.from(t.keys())];if(0===this.options.neighbors.size()){const e=this.options.nearbyNodeView.getFirst(r(),!0);if(e){const r=Xj(e.getPeerDescriptor());t.set(r,e)}}const n=this.options.leftNodeView.getFirst(r()),i=this.options.rightNodeView.getFirst(r());if(n&&t.set(Xj(n.getPeerDescriptor()),n),i&&t.set(Xj(i.getPeerDescriptor()),i),t.size<2){const e=this.options.nearbyNodeView.getFirst(r());e&&t.set(Xj(e.getPeerDescriptor()),e)}for(;t.size<2;){const e=this.options.randomNodeView.getRandom(r());if(!e)break;t.set(Xj(e.getPeerDescriptor()),e)}return Array.from(t.values()).map((e=>this.createRpcRemote(e.getPeerDescriptor())))}async doParallelHandshakes(e,t){return(await Promise.allSettled(Array.from(e.values()).map((async(t,r)=>{const n=0===r?e[1]:e[0],i=n?Xj(n.getPeerDescriptor()):void 0;return this.handshakeWithTarget(t,i)})))).forEach(((r,n)=>{"fulfilled"===r.status&&r.value||t.push(Xj(e[n].getPeerDescriptor()))})),t}async selectNewTargetAndHandshake(e){const t=e.concat(this.options.neighbors.getIds()),r=this.options.leftNodeView.getFirst(t)??this.options.rightNodeView.getFirst(t)??this.options.nearbyNodeView.getFirst(t)??this.options.randomNodeView.getRandom(t);if(r){await this.handshakeWithTarget(this.createRpcRemote(r.getPeerDescriptor()))||e.push(Xj(r.getPeerDescriptor()))}return e}async handshakeWithTarget(e,t){const r=Xj(e.getPeerDescriptor());this.options.ongoingHandshakes.add(r);const n=await e.handshake(this.options.streamPartId,this.options.neighbors.getIds(),t);return n.accepted&&this.options.neighbors.add(this.createContentDeliveryRpcRemote(e.getPeerDescriptor())),n.interleaveTargetDescriptor&&await this.handshakeWithInterleaving(n.interleaveTargetDescriptor,r),this.options.ongoingHandshakes.delete(r),n.accepted}async handshakeWithInterleaving(e,t){const r=this.createRpcRemote(e),n=Xj(r.getPeerDescriptor());this.options.ongoingHandshakes.add(n);const i=await r.handshake(this.options.streamPartId,this.options.neighbors.getIds(),void 0,t);return i.accepted&&this.options.neighbors.add(this.createContentDeliveryRpcRemote(r.getPeerDescriptor())),this.options.ongoingHandshakes.delete(n),i.accepted}createRpcRemote(e){return new A$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,d$,this.options.rpcRequestTimeout)}createContentDeliveryRpcRemote(e){return new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout)}getOngoingHandshakes(){return this.options.ongoingHandshakes}}const R$=new Bv("NeighborFinder");class C${abortController;options;running=!1;constructor(e){this.options=e,this.abortController=new AbortController}async findNeighbors(e){if(!this.running)return;const t=await this.options.doFindNeighbors(e),r=new Set([...this.options.nearbyNodeView.getIds(),...this.options.leftNodeView.getIds(),...this.options.rightNodeView.getIds(),...this.options.randomNodeView.getIds()]).size;this.options.neighbors.size()<this.options.minCount&&t.length<r?Yy((()=>this.findNeighbors(t)),250,this.abortController.signal):0===this.options.neighbors.size()&&r>0?(R$.debug("No neighbors found yet contacts are available, restarting handshaking process"),Yy((()=>this.findNeighbors([])),250,this.abortController.signal)):this.running=!1}isRunning(){return this.running}start(e=[]){this.running||(this.running=!0,Yy((async()=>{await Promise.all([this.findNeighbors(e),this.findNeighbors(e)])}),100,this.abortController.signal))}stop(){this.running&&(this.running=!1,this.abortController.abort())}}class I${options;constructor(e){this.options=e}updateContacts(e){const t=Xj(this.options.localPeerDescriptor);e.filter((e=>{const r=Xj(e);return r!==t&&!this.options.neighbors.getIds().includes(r)})).forEach((e=>this.options.nearbyNodeView.add(new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$))))}createResponse(e){return{streamPartId:this.options.streamPartId,neighborDescriptors:this.options.neighbors.getAll().map((e=>e.getPeerDescriptor())),removeMe:e}}async neighborUpdate(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);if(this.updateContacts(e.neighborDescriptors),this.options.neighbors.has(n)||this.options.ongoingHandshakes.has(n)){const t=this.options.neighbors.size()>this.options.neighborTargetCount&&e.neighborDescriptors.length>this.options.neighborTargetCount;return t?this.options.neighbors.remove(n):this.options.neighborFinder.start(),this.createResponse(t)}return this.createResponse(!0)}}const P$=new Bv("NeighborUpdateRpcRemote");class T$ extends jz{async updateNeighbors(e,t){const r={streamPartId:e,neighborDescriptors:t,removeMe:!1};try{const e=await this.getClient().neighborUpdate(r,this.formDhtRpcOptions());return{peerDescriptors:e.neighborDescriptors,removeMe:e.removeMe}}catch(e){return P$.debug(`updateNeighbors to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),{peerDescriptors:[],removeMe:!0}}}}const _$=new Bv("NeighborUpdateManager");class N${abortController;options;rpcLocal;constructor(e){this.abortController=new AbortController,this.rpcLocal=new I$(e),this.options=e,this.options.rpcCommunicator.registerRpcMethod(KH,KH,"neighborUpdate",((e,t)=>this.rpcLocal.neighborUpdate(e,t)))}async start(){await Jv((()=>this.updateNeighborInfo()),this.options.neighborUpdateInterval,!1,this.abortController.signal)}stop(){this.abortController.abort()}async updateNeighborInfo(){_$.trace("Updating neighbor info to nodes");const e=this.options.neighbors.getAll().map((e=>e.getPeerDescriptor())),t=Date.now();await Promise.allSettled(this.options.neighbors.getAll().map((async r=>{const n=await this.createRemote(r.getPeerDescriptor()).updateNeighbors(this.options.streamPartId,e),i=Xj(r.getPeerDescriptor());this.options.neighbors.get(i).setRtt(Date.now()-t),n.removeMe&&(this.options.neighbors.remove(i),this.options.neighborFinder.start([i]))})))}createRemote(e){return new T$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,f$)}}class M${options;constructor(e){this.options=e}async sendStreamMessage(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);return this.options.markForInspection(n,e.messageId),void 0===this.options.plumtreeManager?this.options.markAndCheckDuplicate(e.messageId,e.previousMessageRef)&&this.options.broadcast(e,n):this.options.markAndCheckDuplicate(e.messageId,e.previousMessageRef)?this.options.plumtreeManager.broadcast(e,n):await this.options.plumtreeManager.pauseNeighbor(r,e.messageId.messageChainId),MV}async leaveStreamPartNotice(e,t){if(e.streamPartId===this.options.streamPartId){const r=t.incomingSourceDescriptor,n=Xj(r);this.options.onLeaveNotice(n,e.isEntryPoint)}return MV}}class x${a;b;constructor(e,t){this.a=e,this.b=t}greaterThanOrEqual(e){return this.greaterThan(e)||this.equalTo(e)}greaterThan(e){return 1===this.compareTo(e)}equalTo(e){return 0===this.compareTo(e)}compareTo(e){return this.a>e.a?1:this.a<e.a?-1:this.b>e.b?1:this.b<e.b?-1:0}toString(){return`${this.a}|${this.b}`}}class O$ extends Error{constructor(){super("pre-condition: previousNumber < number")}}class D$ extends Error{constructor(e,t,r){super(`pre-condition: gap overlap in given numbers: previousNumber=${t.toString()}, number=${r.toString()}, state=${e}`)}}class B${maxGapCount;gaps;constructor(e=1e4){this.maxGapCount=e,this.gaps=[]}markAndCheck(e,t){if(e?.greaterThanOrEqual(t))throw new O$;if(0===this.gaps.length)return this.gaps.push([t,new x$(1/0,1/0)]),!0;if(null===e)return!!t.greaterThan(this.gaps[this.gaps.length-1][0])&&(this.gaps[this.gaps.length-1][0]=t,!0);for(let r=this.gaps.length-1;r>=0;--r){const[n,i]=this.gaps[r];if(e.greaterThanOrEqual(i))return!1;if(e.greaterThanOrEqual(n)){if(t.greaterThan(i))throw new D$(this.toString(),e,t);return e.equalTo(n)?t.equalTo(i)?this.gaps.splice(r,1):this.gaps[r]=[t,i]:t.equalTo(i)?this.gaps[r]=[n,e]:this.gaps.splice(r,1,[n,e],[t,i]),this.dropLowestGapIfOverMaxGapCount(),!0}if(t.greaterThan(n))throw new D$(this.toString(),e,t)}return!1}dropLowestGapIfOverMaxGapCount(){this.gaps.length>this.maxGapCount&&this.gaps.shift()}toString(){return this.gaps.map((([e,t])=>`(${e.toString()}, ${t.toString()}]`)).join(", ")}}const L$=(e,t,r)=>{const n=`${kE(t.publisherId)}-${t.messageChainId}`,i=r?new x$(Number(r.timestamp),r.sequenceNumber):null,s=new x$(Number(t.timestamp),t.sequenceNumber);return e.has(n)||e.set(n,new B$),e.get(n).markAndCheck(i,s)},F$=new Bv("ContentDeliveryLayerNode");class U$ extends Sl{started=!1;duplicateDetectors;options;contentDeliveryRpcLocal;abortController=new AbortController;messagesPropagated=0;constructor(e){super(),this.options=e,this.duplicateDetectors=new Map,this.contentDeliveryRpcLocal=new M$({localPeerDescriptor:this.options.localPeerDescriptor,streamPartId:this.options.streamPartId,rpcCommunicator:this.options.rpcCommunicator,markAndCheckDuplicate:(e,t)=>L$(this.duplicateDetectors,e,t),broadcast:(e,t)=>this.broadcast(e,t),onLeaveNotice:(e,t)=>{if(this.abortController.signal.aborted)return;(this.options.nearbyNodeView.get(e)??this.options.randomNodeView.get(e)??this.options.neighbors.get(e)??this.options.proxyConnectionRpcLocal?.getConnection(e)?.remote)&&(this.options.discoveryLayerNode.removeContact(e),this.options.neighbors.remove(e),this.options.nearbyNodeView.remove(e),this.options.randomNodeView.remove(e),this.options.leftNodeView.remove(e),this.options.rightNodeView.remove(e),this.options.neighborFinder.start([e]),this.options.proxyConnectionRpcLocal?.removeConnection(e)),t&&this.emit("entryPointLeaveDetected")},markForInspection:(e,t)=>this.options.inspector.markMessage(e,t),plumtreeManager:this.options.plumtreeManager})}async start(){this.started=!0,this.registerDefaultServerMethods(),oE(this.options.discoveryLayerNode,"nearbyContactAdded",(()=>this.onNearbyContactAdded()),this.abortController.signal),oE(this.options.discoveryLayerNode,"nearbyContactRemoved",(()=>this.onNearbyContactRemoved()),this.abortController.signal),oE(this.options.discoveryLayerNode,"randomContactAdded",(()=>this.onRandomContactAdded()),this.abortController.signal),oE(this.options.discoveryLayerNode,"randomContactRemoved",(()=>this.onRandomContactRemoved()),this.abortController.signal),oE(this.options.discoveryLayerNode,"ringContactAdded",(()=>this.onRingContactsUpdated()),this.abortController.signal),oE(this.options.discoveryLayerNode,"ringContactRemoved",(()=>this.onRingContactsUpdated()),this.abortController.signal),oE(this.options.transport,"disconnected",(e=>this.onNodeDisconnected(e)),this.abortController.signal),oE(this.options.neighbors,"nodeAdded",((e,t)=>{this.options.propagation.onNeighborJoined(e),this.options.connectionLocker.weakLockConnection(Xj(t.getPeerDescriptor()),this.options.streamPartId),this.emit("neighborConnected",e)}),this.abortController.signal),oE(this.options.neighbors,"nodeRemoved",((e,t)=>{this.options.connectionLocker.weakUnlockConnection(Xj(t.getPeerDescriptor()),this.options.streamPartId)}),this.abortController.signal),void 0!==this.options.proxyConnectionRpcLocal&&oE(this.options.proxyConnectionRpcLocal,"newConnection",(e=>this.options.propagation.onNeighborJoined(e)),this.abortController.signal),this.options.plumtreeManager&&oE(this.options.plumtreeManager,"message",(e=>this.emit("message",e)),this.abortController.signal),this.options.neighborFinder.start(),await this.options.neighborUpdateManager.start()}registerDefaultServerMethods(){this.options.rpcCommunicator.registerRpcNotification(xH,"sendStreamMessage",((e,t)=>this.contentDeliveryRpcLocal.sendStreamMessage(e,t))),this.options.rpcCommunicator.registerRpcNotification(zH,"leaveStreamPartNotice",((e,t)=>this.contentDeliveryRpcLocal.leaveStreamPartNotice(e,t))),this.options.rpcCommunicator.registerRpcMethod(HH,$H,"openConnection",((e,t)=>this.options.temporaryConnectionRpcLocal.openConnection(e,t))),this.options.rpcCommunicator.registerRpcNotification(WH,"closeConnection",((e,t)=>this.options.temporaryConnectionRpcLocal.closeConnection(e,t)))}onRingContactsUpdated(){if(F$.trace("onRingContactsUpdated"),this.isStopped())return;const e=this.options.discoveryLayerNode.getRingContacts();this.options.leftNodeView.replaceAll(e.left.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout)))),this.options.rightNodeView.replaceAll(e.right.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))))}onNearbyContactAdded(){if(F$.trace("New nearby contact found"),this.isStopped())return;const e=this.options.discoveryLayerNode.getClosestContacts();this.updateNearbyNodeView(e),this.options.neighbors.size()<this.options.neighborTargetCount&&this.options.neighborFinder.start()}onNearbyContactRemoved(){if(F$.trace("Nearby contact removed"),this.isStopped())return;const e=this.options.discoveryLayerNode.getClosestContacts();this.updateNearbyNodeView(e)}updateNearbyNodeView(e){this.options.nearbyNodeView.replaceAll(Array.from(e).map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))));for(const e of this.options.discoveryLayerNode.getNeighbors()){if(this.options.nearbyNodeView.size()>=this.options.nodeViewSize)break;this.options.nearbyNodeView.add(new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))}}onRandomContactAdded(){if(this.isStopped())return;const e=this.options.discoveryLayerNode.getRandomContacts(this.options.nodeViewSize);this.options.randomNodeView.replaceAll(e.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout)))),this.options.neighbors.size()<this.options.neighborTargetCount&&this.options.neighborFinder.start()}onRandomContactRemoved(){if(F$.trace("New random contact removed"),this.isStopped())return;const e=this.options.discoveryLayerNode.getRandomContacts(this.options.nodeViewSize);this.options.randomNodeView.replaceAll(e.map((e=>new b$(this.options.localPeerDescriptor,e,this.options.rpcCommunicator,l$,this.options.rpcRequestTimeout))))}onNodeDisconnected(e){const t=Xj(e);this.options.neighbors.has(t)&&(this.options.neighbors.remove(t),this.options.neighborFinder.start([t]),this.options.temporaryConnectionRpcLocal.removeNode(t))}hasProxyConnection(e){return!!this.options.proxyConnectionRpcLocal&&this.options.proxyConnectionRpcLocal.hasConnection(e)}stop(){this.started&&(this.abortController.abort(),this.options.proxyConnectionRpcLocal?.stop(),this.options.neighbors.getAll().map((e=>{e.leaveStreamPartNotice(this.options.streamPartId,this.options.isLocalNodeEntryPoint()),this.options.connectionLocker.weakUnlockConnection(Xj(e.getPeerDescriptor()),this.options.streamPartId)})),this.options.rpcCommunicator.destroy(),this.removeAllListeners(),this.options.plumtreeManager?.stop(),this.options.nearbyNodeView.stop(),this.options.neighbors.stop(),this.options.randomNodeView.stop(),this.options.neighborFinder.stop(),this.options.neighborUpdateManager.stop(),this.options.inspector.stop())}broadcast(e,t){t||L$(this.duplicateDetectors,e.messageId,e.previousMessageRef),this.emit("message",e);const r=void 0!==t&&!this.options.temporaryConnectionRpcLocal.hasNode(t);this.options.propagation.feedUnseenMessage(e,this.getPropagationTargets(e),r?t:null),this.messagesPropagated+=1}inspect(e){return this.options.inspector.inspect(e)}getPropagationTargets(e){let t=this.options.neighbors.getIds();return this.options.proxyConnectionRpcLocal&&(t=t.concat(this.options.proxyConnectionRpcLocal.getPropagationTargets(e))),t=t.concat(this.options.temporaryConnectionRpcLocal.getNodes().getIds()),t}getOwnNodeId(){return Xj(this.options.localPeerDescriptor)}getOutgoingHandshakeCount(){return this.options.handshaker.getOngoingHandshakes().size}getNeighbors(){return!this.started&&this.isStopped()?[]:this.options.neighbors.getAll().map((e=>e.getPeerDescriptor()))}getInfos(){return this.options.neighbors.getAll().map((e=>({peerDescriptor:e.getPeerDescriptor(),rtt:e.getRtt()})))}getNearbyNodeView(){return this.options.nearbyNodeView}getDiagnosticInfo(){return{neighborCount:this.options.neighbors.size(),nearbyNodeViewCount:this.options.nearbyNodeView.size(),randomNodeViewCount:this.options.randomNodeView.size(),leftNodeViewCount:this.options.leftNodeView.size(),rightNodeViewCount:this.options.rightNodeView.size(),messagesPropagated:this.messagesPropagated}}isStopped(){return this.abortController.signal.aborted}}const j$=(e,t,r=!1)=>{const n=r?Array.from(e.entries()).filter((([e,t])=>void 0!==t.getPeerDescriptor().websocket)):Array.from(e.entries());return n.filter((([e])=>!t.includes(e))).map((([e,t])=>t))};class q$ extends Sl{nodes;limit;ownId;constructor(e,t){super(),this.nodes=new Map,this.limit=t,this.ownId=e}add(e){const t=Xj(e.getPeerDescriptor());if(this.ownId!==t&&this.nodes.size<this.limit){const r=this.nodes.has(t);this.nodes.set(t,e),r||this.emit("nodeAdded",t,e)}}remove(e){if(this.nodes.has(e)){const t=this.nodes.get(e);this.nodes.delete(e),this.emit("nodeRemoved",e,t)}}has(e){return this.nodes.has(e)}replaceAll(e){this.nodes.clear();e.splice(0,this.limit).forEach((e=>{this.add(e)}))}getIds(){return Array.from(this.nodes.keys())}get(e){return this.nodes.get(e)}size(e=[]){return Array.from(this.nodes.keys()).filter((t=>!e.includes(t))).length}getRandom(e){return oA(j$(this.nodes,e))}getFirst(e,t=!1){return j$(this.nodes,e,t)[0]}getFirstAndLast(e){const t=j$(this.nodes,e);return 0===t.length?[]:t.length>1?[this.getFirst(e),this.getLast(e)]:[this.getFirst(e)]}getLast(e){const t=j$(this.nodes,e);return t[t.length-1]}getAll(){return Array.from(this.nodes.values())}stop(){this.nodes.forEach((e=>this.remove(Xj(e.getPeerDescriptor())))),this.removeAllListeners()}}class z${items=new Map;dropQueue=vV.create();ttlInMs;maxSize;onItemDropped;timeProvider;constructor({ttlInMs:e,maxSize:t,onItemDropped:r=()=>{},timeProvider:n=Date.now}){if(e<0)throw new Error(`ttlInMs (${e}) cannot be < 0`);if(t<0)throw new Error(`maxSize (${t}) cannot be < 0`);this.ttlInMs=e,this.maxSize=t,this.onItemDropped=r,this.timeProvider=n}set(e,t){if(0===this.maxSize)return;if(this.items.size>this.maxSize)throw new Error("assertion error: maximum size exceeded");if(this.delete(e),this.items.size===this.maxSize){const e=this.dropQueue.shift();if(void 0===e)throw new Error("assertion error: queue empty but still have items");this.items.delete(e),this.onItemDropped(e)}const r=new kV(e);this.dropQueue.pushNode(r),this.items.set(e,{value:t,dropQueueNode:r,expiresAt:this.timeProvider()+this.ttlInMs})}delete(e){const t=this.items.get(e);void 0!==t&&(this.items.delete(e),this.dropQueue.removeNode(t.dropQueueNode),this.onItemDropped(e))}get(e){const t=this.items.get(e);if(void 0!==t){if(!(t.expiresAt<=this.timeProvider()))return t.value;this.delete(e)}}values(){const e=[...this.items.keys()],t=[];for(const r of e){const e=this.get(r);void 0!==e&&t.push(e)}return t}}class K${tasks;constructor(e,t){this.tasks=new z$({ttlInMs:e,maxSize:t})}get(){return this.tasks.values()}add(e){const t=e.message.messageId;this.tasks.set(t,e)}delete(e){this.tasks.delete(e)}}class G${sendToNeighbor;minPropagationTargets;activeTaskStore;constructor({sendToNeighbor:e,minPropagationTargets:t,maxMessages:r,ttl:n}){this.sendToNeighbor=e,this.minPropagationTargets=t,this.activeTaskStore=new K$(n,r)}feedUnseenMessage(e,t,r){const n={message:e,source:r,handledNeighbors:new Set};this.activeTaskStore.add(n);for(const e of t)this.sendAndAwaitThenMark(n,e)}onNeighborJoined(e){const t=this.activeTaskStore.get();for(const r of t)this.sendAndAwaitThenMark(r,e)}sendAndAwaitThenMark({message:e,source:t,handledNeighbors:r},n){r.has(n)||n===t||(async()=>{try{await this.sendToNeighbor(n,e)}catch{return}r.add(n),r.size>=this.minPropagationTargets&&this.activeTaskStore.delete(e.messageId)})()}}const V$=new Bv("ProxyConnectionRpcLocal");class H$ extends Sl{options;connections=new Map;constructor(e){super(),this.options=e,this.options.rpcCommunicator.registerRpcMethod(GH,VH,"requestConnection",((e,t)=>this.requestConnection(e,t)))}getConnection(e){return this.connections.get(e)}hasConnection(e){return this.connections.has(e)}removeConnection(e){this.connections.delete(e)}stop(){this.connections.forEach((e=>e.remote.leaveStreamPartNotice(this.options.streamPartId,!1))),this.connections.clear(),this.removeAllListeners()}getPropagationTargets(e){if("groupKeyRequest"!==e.body.oneofKind)return this.getSubscribers();try{const t=e.body.groupKeyRequest.recipientId;return this.getNodeIdsForUserId(kE(t))}catch(e){return V$.trace("Could not parse GroupKeyRequest",{err:e}),[]}}getNodeIdsForUserId(e){return Array.from(this.connections.keys()).filter((t=>this.connections.get(t).userId===e))}getSubscribers(){return Array.from(this.connections.keys()).filter((t=>{const r=this.connections.get(t).direction;return void 0===r||r===e.ProxyDirection.SUBSCRIBE}))}async requestConnection(e,t){const r=t.incomingSourceDescriptor,n=Xj(r);this.connections.set(n,{direction:e.direction,userId:kE(e.userId),remote:new b$(this.options.localPeerDescriptor,r,this.options.rpcCommunicator,l$)});return V$.trace(`Accepted connection request from ${n} to ${this.options.streamPartId}`),this.emit("newConnection",n),{accepted:!0}}}const $$=new Bv("TemporaryConnectionRpcRemote");class W$ extends jz{async openConnection(){try{return(await this.getClient().openConnection({},this.formDhtRpcOptions())).accepted}catch(e){return $$.debug(`temporaryConnection to ${Xj(this.getPeerDescriptor())} failed`,{err:e}),!1}}async closeConnection(){try{await this.getClient().closeConnection({},this.formDhtRpcOptions({connect:!1,notification:!0}))}catch(e){$$.trace(`closeConnection to ${Xj(this.getPeerDescriptor())} failed`,{err:e})}}}class J$ extends Sl{inspectionMessages=new Map;inspectedNode;constructor(e){super(),this.inspectedNode=e.inspectedNode}markMessage(e,t){const r=(e=>`${kE(e.publisherId)}:${e.messageChainId}:${e.timestamp}:${e.sequenceNumber}`)(t);this.inspectionMessages.has(r)?(this.inspectionMessages.has(r)&&!1===this.inspectionMessages.get(r)&&e===this.inspectedNode||this.inspectionMessages.has(r)&&!0===this.inspectionMessages.get(r))&&this.emit("done"):this.inspectionMessages.set(r,e===this.inspectedNode)}getInspectedMessageCount(){return this.inspectionMessages.size}onlyMarkedByInspectedNode(){return Array.from(this.inspectionMessages.values()).every((e=>!0===e))}stop(){this.emit("done")}}const Q$=new Bv("Inspector");class Z${sessions=new Map;streamPartId;localPeerDescriptor;rpcCommunicator;connectionLocker;inspectionTimeout;openInspectConnection;closeInspectConnection;constructor(e){this.streamPartId=e.streamPartId,this.localPeerDescriptor=e.localPeerDescriptor,this.rpcCommunicator=e.rpcCommunicator,this.connectionLocker=e.connectionLocker,this.inspectionTimeout=e.inspectionTimeout??6e4,this.openInspectConnection=e.openInspectConnection??this.defaultOpenInspectConnection,this.closeInspectConnection=e.closeInspectConnection??this.defaultCloseInspectConnection}async defaultOpenInspectConnection(e,t){const r=new W$(this.localPeerDescriptor,e,this.rpcCommunicator,p$);await r.openConnection(),this.connectionLocker.weakLockConnection(Xj(e),t)}async defaultCloseInspectConnection(e,t){const r=new W$(this.localPeerDescriptor,e,this.rpcCommunicator,p$);await r.closeConnection(),this.connectionLocker.weakUnlockConnection(Xj(e),t)}async inspect(e){const t=Xj(e),r=new J$({inspectedNode:t}),n=`inspector-${this.streamPartId}`;this.sessions.set(t,r),await this.openInspectConnection(e,n);let i=!1;try{await eE(r,"done",this.inspectionTimeout),i=!0}catch{Q$.trace("Inspect session timed out, removing")}finally{await this.closeInspectConnection(e,n),this.sessions.delete(t)}return i||r.getInspectedMessageCount()<1||r.onlyMarkedByInspectedNode()}markMessage(e,t){this.sessions.forEach((r=>r.markMessage(e,t)))}isInspected(e){return this.sessions.has(e)}stop(){this.sessions.forEach((e=>{e.stop()})),this.sessions.clear()}}class Y${options;temporaryNodes;lockId;constructor(e){this.options=e,this.temporaryNodes=new q$(Xj(e.localPeerDescriptor),10),this.lockId="system/content-delivery/temporary-connection/"+e.streamPartId}getNodes(){return this.temporaryNodes}hasNode(e){return this.temporaryNodes.has(e)}removeNode(e){this.temporaryNodes.remove(e),this.options.connectionLocker.weakUnlockConnection(e,this.lockId)}async openConnection(e,t){const r=t.incomingSourceDescriptor,n=new b$(this.options.localPeerDescriptor,r,this.options.rpcCommunicator,l$);return this.temporaryNodes.add(n),this.options.connectionLocker.weakLockConnection(Xj(r),this.lockId),{accepted:!0}}async closeConnection(e,t){const r=Xj(t.incomingSourceDescriptor);return this.removeNode(r),{}}}const X$=e=>`stream-part-delivery-${e}`;class eW{neighbors;pausedNodes;onMetadataCb;sendBuffer;constructor(e,t,r,n){this.neighbors=e,this.pausedNodes=t,this.onMetadataCb=r,this.sendBuffer=n}async sendMetadata(e,t){const r=t.incomingSourceDescriptor;return await this.onMetadataCb(e,r),MV}async pauseNeighbor(e,t){const r=Xj(t.incomingSourceDescriptor);if(this.neighbors.has(r)){return{accepted:this.pausedNodes.add(r,e.messageChainId)}}return{accepted:!1}}async resumeNeighbor(e,t){const r=t.incomingSourceDescriptor;return this.neighbors.has(Xj(r))&&(this.pausedNodes.delete(Xj(r),e.messageChainId),await this.sendBuffer(e.fromTimestamp,e.messageChainId,r)),MV}}class tW extends jz{async sendMetadata(e){const t=this.formDhtRpcOptions({notification:!0});await this.getClient().sendMetadata(e,t)}async pauseNeighbor(e){const t=this.formDhtRpcOptions();return(await this.getClient().pauseNeighbor({messageChainId:e},t)).accepted}async resumeNeighbor(e,t){const r=this.formDhtRpcOptions({notification:!0});await this.getClient().resumeNeighbor({fromTimestamp:e,messageChainId:t},r)}}class rW{pausedNeighbors;limit;constructor(e){this.pausedNeighbors=new Map,this.limit=e}add(e,t){return this.pausedNeighbors.has(t)||this.pausedNeighbors.set(t,new Set),!(this.pausedNeighbors.get(t).size>=this.limit)&&(this.pausedNeighbors.get(t).add(e),!0)}delete(e,t){this.pausedNeighbors.get(t)?.delete(e),0===this.pausedNeighbors.get(t)?.size&&this.pausedNeighbors.delete(t)}deleteAll(e){this.pausedNeighbors.forEach(((t,r)=>{t.delete(e),0===t.size&&this.pausedNeighbors.delete(r)}))}isPaused(e,t){return!!this.pausedNeighbors.has(t)&&this.pausedNeighbors.get(t).has(e)}forEach(e){this.pausedNeighbors.forEach(((t,r)=>{e(t,r)}))}size(e){return this.pausedNeighbors.get(e)?.size??0}}const nW=new Bv("PlumtreeManager");class iW extends Sl{neighbors;localPeerDescriptor;localPausedNeighbors;remotePausedNeighbors;rpcLocal;latestMessages=new Map;rpcCommunicator;maxPausedNeighbors;recoveryState=new Map;recoveryCooldownUntil=new Map;recoveryTimeout;recoveryCooldown;abortController=new AbortController;constructor(e){super(),this.neighbors=e.neighbors,this.maxPausedNeighbors=e.maxPausedNeighbors??3,this.localPeerDescriptor=e.localPeerDescriptor,this.localPausedNeighbors=new rW(e.maxPausedNeighbors??3),this.remotePausedNeighbors=new rW(e.maxPausedNeighbors??3),this.recoveryTimeout=e.recoveryTimeout??500,this.recoveryCooldown=e.recoveryCooldown??2500,this.rpcLocal=new eW(this.neighbors,this.localPausedNeighbors,((e,t)=>this.onMetadata(e,t)),((e,t,r)=>this.sendBuffer(e,t,r))),this.neighbors.on("nodeRemoved",this.onNeighborRemoved),this.rpcCommunicator=e.rpcCommunicator,this.rpcCommunicator.registerRpcNotification(NH,"sendMetadata",((e,t)=>this.rpcLocal.sendMetadata(e,t))),this.rpcCommunicator.registerRpcMethod(e$,t$,"pauseNeighbor",((e,t)=>this.rpcLocal.pauseNeighbor(e,t))),this.rpcCommunicator.registerRpcNotification(r$,"resumeNeighbor",((e,t)=>this.rpcLocal.resumeNeighbor(e,t))),((e,t,r)=>{if(r.aborted)return;r.addEventListener("abort",(()=>{clearInterval(n)}),{once:!0});const n=setInterval((()=>{e()}),t)})((()=>{const e=performance.now();for(const[t,r]of this.recoveryState)e-r.metadataAheadSince>=this.recoveryTimeout&&!r.resumeInProgress&&this.attemptRecovery(t,r,this.getLatestMessageTimestamp(t))}),e.recoveryCheckInterval??200,this.abortController.signal)}async pauseNeighbor(e,t){if(this.neighbors.has(Xj(e))&&!this.remotePausedNeighbors.isPaused(Xj(e),t)&&this.remotePausedNeighbors.size(t)<this.maxPausedNeighbors){nW.debug(`Pausing neighbor ${Xj(e)}`),this.remotePausedNeighbors.add(Xj(e),t);try{const r=this.createRemote(e);await r.pauseNeighbor(t)||this.remotePausedNeighbors.delete(Xj(e),t)}catch(r){this.remotePausedNeighbors.delete(Xj(e),t)}}}async resumeNeighbor(e,t,r){if(this.remotePausedNeighbors.isPaused(Xj(e),t)){nW.debug(`Resuming neighbor ${Xj(e)}`),this.remotePausedNeighbors.delete(Xj(e),t);const n=this.createRemote(e);await n.resumeNeighbor(r,t)}}onNeighborRemoved=e=>{this.localPausedNeighbors.deleteAll(e),this.remotePausedNeighbors.deleteAll(e);for(const[t,r]of this.recoveryState)r.candidates=r.candidates.filter((t=>Xj(t)!==e)),null!==r.lastAttemptedNode&&Xj(r.lastAttemptedNode)===e&&(r.lastAttemptedNode=null);this.neighbors.size()>0&&this.remotePausedNeighbors.forEach(((e,t)=>{if(e.size>=this.neighbors.size()){nW.debug("All neighbors are paused, resuming first neighbor");const e=this.neighbors.getFirst([]).getPeerDescriptor();setImmediate((()=>this.resumeNeighbor(e,t,this.getLatestMessageTimestamp(t))))}}))};getLatestMessageTimestamp(e){return this.latestMessages.has(e)&&0!==this.latestMessages.get(e).length?this.latestMessages.get(e)[this.latestMessages.get(e).length-1].messageId.timestamp:0}async sendBuffer(e,t,r){const n=new b$(this.localPeerDescriptor,r,this.rpcCommunicator,l$),i=this.latestMessages.get(t)?.filter((t=>t.messageId.timestamp>e))??[];for(const e of i)await n.sendStreamMessage(e)}async onMetadata(e,t){const r=this.getLatestMessageTimestamp(e.messageChainId);if(r>=e.timestamp)return;const n=e.messageChainId,i=this.recoveryCooldownUntil.get(n);if(void 0!==i&&performance.now()<i)return;let s=this.recoveryState.get(n);s||(s={timestampsAhead:new Set,metadataAheadSince:performance.now(),candidates:[],lastAttemptedNode:null,resumeInProgress:!1},this.recoveryState.set(n,s)),s.timestampsAhead.add(e.timestamp);const o=Xj(t);null!==s.lastAttemptedNode&&Xj(s.lastAttemptedNode)===o||s.candidates.some((e=>Xj(e)===o))||s.candidates.push(t),s.timestampsAhead.size>1&&!s.resumeInProgress&&await this.attemptRecovery(n,s,r)}async attemptRecovery(e,t,r){const n=t.candidates.shift();if(n){t.resumeInProgress=!0,t.lastAttemptedNode=n,t.candidates=[],t.timestampsAhead.clear(),t.metadataAheadSince=performance.now();try{const t=this.createRemote(n);await t.resumeNeighbor(r,e)}catch(e){nW.debug("Recovery resume failed, will retry with next candidate")}finally{t.resumeInProgress=!1}}else t.metadataAheadSince=performance.now()}createRemote(e){return new tW(this.localPeerDescriptor,e,this.rpcCommunicator,m$)}broadcast(e,t){const r=e.messageId.messageChainId;this.latestMessages.has(r)||this.latestMessages.set(r,[]),this.latestMessages.get(r).length<20||this.latestMessages.get(r).shift(),this.latestMessages.get(r).push(e);const n=this.recoveryState.get(r);n&&(n.lastAttemptedNode&&this.remotePausedNeighbors.delete(Xj(n.lastAttemptedNode),r),this.recoveryState.delete(r),this.recoveryCooldownUntil.set(r,performance.now()+this.recoveryCooldown)),this.emit("message",e);const i=this.neighbors.getAll().filter((e=>Xj(e.getPeerDescriptor())!==t));for(const t of i)if(this.localPausedNeighbors.isPaused(Xj(t.getPeerDescriptor()),e.messageId.messageChainId)){const r=this.createRemote(t.getPeerDescriptor());setImmediate((()=>r.sendMetadata(e.messageId)))}else setImmediate((()=>t.sendStreamMessage(e)))}isNeighborPaused(e,t){return this.localPausedNeighbors.isPaused(Xj(e),t)||this.remotePausedNeighbors.isPaused(Xj(e),t)}getLocalPausedNeighbors(){return this.localPausedNeighbors}getRemotePausedNeighbors(){return this.remotePausedNeighbors}stop(){this.abortController.abort(),this.neighbors.off("nodeRemoved",this.onNeighborRemoved)}}const sW=e=>new U$((e=>{const t=Xj(e.localPeerDescriptor),r=e.rpcCommunicator??new lK(X$(e.streamPartId),e.transport),n=e.neighborTargetCount??4,i=e.maxContactCount??20,s=e.acceptProxyConnections??!1,o=e.neighborUpdateInterval??1e4,a=e.minPropagationTargets??2,c=e.maxPropagationBufferSize??150,u=e.neighbors??new q$(t,i),l=e.leftNodeView??new q$(t,i),h=e.rightNodeView??new q$(t,i),d=e.nearbyNodeView??new q$(t,i),f=e.randomNodeView??new q$(t,i),p=new Set,g=new Y$({rpcCommunicator:r,localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,connectionLocker:e.connectionLocker}),m=s?new H$({localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,rpcCommunicator:r}):void 0,y=e.plumtreeOptimization?new iW({neighbors:u,localPeerDescriptor:e.localPeerDescriptor,rpcCommunicator:r,maxPausedNeighbors:e.plumtreeMaxPausedNeighbors}):void 0,b=e.propagation??new G$({minPropagationTargets:a,maxMessages:c,ttl:1e4,sendToNeighbor:async(t,r)=>{const n=u.get(t)??g.getNodes().get(t),i=m?.getConnection(t);if(n)await n.sendStreamMessage(r,e.bufferWhileConnecting);else{if(!i)throw new Error("Propagation target not found");await i.remote.sendStreamMessage(r)}}}),w=e.handshaker??new k$({localPeerDescriptor:e.localPeerDescriptor,streamPartId:e.streamPartId,rpcCommunicator:r,neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,maxNeighborCount:n,rpcRequestTimeout:e.rpcRequestTimeout,ongoingHandshakes:p}),v=e.neighborFinder??new C$({neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,doFindNeighbors:e=>w.attemptHandshakesOnContacts(e),minCount:n}),E=e.neighborUpdateManager??new N$({neighbors:u,nearbyNodeView:d,localPeerDescriptor:e.localPeerDescriptor,neighborFinder:v,streamPartId:e.streamPartId,rpcCommunicator:r,neighborUpdateInterval:o,neighborTargetCount:n,ongoingHandshakes:p}),A=e.inspector??new Z$({localPeerDescriptor:e.localPeerDescriptor,rpcCommunicator:r,streamPartId:e.streamPartId,connectionLocker:e.connectionLocker});return{...e,neighbors:u,leftNodeView:l,rightNodeView:h,nearbyNodeView:d,randomNodeView:f,rpcCommunicator:r,handshaker:w,neighborFinder:v,neighborUpdateManager:E,propagation:b,neighborTargetCount:n,nodeViewSize:i,proxyConnectionRpcLocal:m,inspector:A,temporaryConnectionRpcLocal:g,plumtreeManager:y}})(e)),oW=new Bv("ProxyConnectionRpcRemote");class aW extends jz{async requestConnection(e,t){const r={direction:t,userId:RE(e)},n=this.formDhtRpcOptions({timeout:Fz});try{return(await this.getClient().requestConnection(r,n)).accepted}catch(e){return oW.debug("ProxyConnectionRequest failed with error",{err:e}),!1}}}const cW=new Bv("ProxyClient"),uW="system/proxy-client";class lW extends Sl{rpcCommunicator;contentDeliveryRpcLocal;options;duplicateDetectors=new Map;definition;connections=new Map;propagation;neighbors;abortController;constructor(e){super(),this.options=e,this.rpcCommunicator=new lK(X$(e.streamPartId),e.transport),this.neighbors=new q$(Xj(this.options.localPeerDescriptor),1e3),this.contentDeliveryRpcLocal=new M$({localPeerDescriptor:this.options.localPeerDescriptor,streamPartId:this.options.streamPartId,markAndCheckDuplicate:(e,t)=>L$(this.duplicateDetectors,e,t),broadcast:(e,t)=>this.broadcast(e,t),onLeaveNotice:e=>{const t=this.neighbors.get(e);t&&setImmediate((()=>this.onNodeDisconnected(t.getPeerDescriptor())))},rpcCommunicator:this.rpcCommunicator,markForInspection:()=>{}}),this.propagation=new G$({minPropagationTargets:e.minPropagationTargets,maxMessages:e.maxPropagationBufferSize,ttl:e.propagationBufferTtl,sendToNeighbor:async(e,t)=>{const r=this.neighbors.get(e);if(!r)throw new Error("Propagation target not found");await r.sendStreamMessage(t)}}),this.abortController=new AbortController}registerDefaultServerMethods(){this.rpcCommunicator.registerRpcNotification(xH,"sendStreamMessage",((e,t)=>this.contentDeliveryRpcLocal.sendStreamMessage(e,t))),this.rpcCommunicator.registerRpcNotification(zH,"leaveStreamPartNotice",((e,t)=>this.contentDeliveryRpcLocal.leaveStreamPartNotice(e,t)))}async setProxies(e,t,r,n){if(cW.trace("Setting proxies",{streamPartId:this.options.streamPartId,peerDescriptors:e,direction:r,userId:t,connectionCount:n}),void 0!==n&&n>e.length)throw new Error("Cannot set connectionCount above the size of the configured array of nodes");const i=new Map;e.forEach((e=>{i.set(Xj(e),e)})),this.definition={nodes:i,userId:t,direction:r,connectionCount:n??e.length},await this.updateConnections()}async updateConnections(){await Promise.all(this.getInvalidConnections().map((async e=>{await this.closeConnection(e)})));const e=this.definition.connectionCount-this.connections.size;e>0?await this.openRandomConnections(e):e<0&&await this.closeRandomConnections(-e)}getInvalidConnections(){return Array.from(this.connections.keys()).filter((e=>!this.definition.nodes.has(e)||this.definition.direction!==this.connections.get(e).direction))}async openRandomConnections(e){const t=wV(Array.from(this.definition.nodes.keys()).filter((e=>!this.connections.has(e))),e);await Promise.all(t.map((e=>this.attemptConnection(e,this.definition.userId,this.definition.direction))))}async attemptConnection(e,t,r){const n=this.definition.nodes.get(e),i=new aW(this.options.localPeerDescriptor,n,this.rpcCommunicator,h$);if(await i.requestConnection(t,r)){this.options.connectionLocker.lockConnection(n,uW),this.connections.set(e,{peerDescriptor:n,direction:r});const t=new b$(this.options.localPeerDescriptor,n,this.rpcCommunicator,l$);this.neighbors.add(t),this.propagation.onNeighborJoined(e),cW.info("Open proxy connection",{nodeId:e,streamPartId:this.options.streamPartId})}else cW.warn("Unable to open proxy connection",{nodeId:e,streamPartId:this.options.streamPartId})}async closeRandomConnections(e){const t=wV(Array.from(this.connections.keys()),e);await Promise.allSettled(t.map((e=>this.closeConnection(e))))}async closeConnection(e){if(this.connections.has(e)){cW.info("Close proxy connection",{nodeId:e});const t=this.neighbors.get(e);t?.leaveStreamPartNotice(this.options.streamPartId,!1),this.removeConnection(this.connections.get(e).peerDescriptor)}}removeConnection(e){const t=Xj(e);this.connections.delete(t),this.neighbors.remove(t),this.options.connectionLocker.unlockConnection(e,uW)}broadcast(e,t){t||L$(this.duplicateDetectors,e.messageId,e.previousMessageRef),this.emit("message",e),this.propagation.feedUnseenMessage(e,this.neighbors.getIds(),t??null)}hasConnection(e,t){return this.connections.has(e)&&this.connections.get(e).direction===t}getDirection(){return this.definition.direction}async onNodeDisconnected(e){const t=Xj(e);this.connections.has(t)&&(this.options.connectionLocker.unlockConnection(e,uW),this.removeConnection(e),await(async(e,t,r,n=1e4)=>{for(;;){try{return await e()}catch{cW.warn(`Failed ${t} (retrying after delay)`,{delayInMs:n})}await Qv(n,r)}})((()=>this.updateConnections()),"updating proxy connections",this.abortController.signal))}async start(){this.registerDefaultServerMethods(),oE(this.options.transport,"disconnected",(e=>this.onNodeDisconnected(e)),this.abortController.signal)}getDiagnosticInfo(){return{neighbors:this.neighbors.getAll().map((e=>e.getPeerDescriptor()))}}stop(){this.neighbors.getAll().forEach((e=>{this.options.connectionLocker.unlockConnection(e.getPeerDescriptor(),uW),e.leaveStreamPartNotice(this.options.streamPartId,!1)})),this.neighbors.stop(),this.rpcCommunicator.destroy(),this.connections.clear(),this.abortController.abort()}}const hW=new Bv("ContentDeliveryManager"),dW=e=>{return Zj((t=e,Buffer.from(Zr(pw(t)))));var t};class fW extends Sl{transport;connectionLocker;controlLayerNode;metricsContext;metrics;options;streamParts;knownStreamPartEntryPoints=new Map;started=!1;destroyed=!1;constructor(e){super(),this.options=e,this.streamParts=new Map,this.metricsContext=e.metricsContext??new $v,this.metrics={broadcastMessagesPerSecond:new Hv,broadcastBytesPerSecond:new Hv},this.metricsContext.addMetrics("node",this.metrics)}async start(e,t,r){this.started||this.destroyed||(this.started=!0,this.controlLayerNode=e,this.transport=t,this.connectionLocker=r)}async destroy(){this.started&&!this.destroyed&&(hW.trace("Destroying ContentDeliveryManager"),this.destroyed=!0,await Promise.all(Array.from(this.streamParts.values()).map((e=>e.stop()))),this.streamParts.clear(),this.removeAllListeners(),this.controlLayerNode=void 0,this.transport=void 0,this.connectionLocker=void 0)}broadcast(e,t){const r=EE(e.messageId.streamId,e.messageId.streamPartition);hW.debug(`Broadcasting to stream part ${r}`),this.joinStreamPart(r,t),this.streamParts.get(r).broadcast(e),"contentMessage"===e.body.oneofKind&&(this.metrics.broadcastMessagesPerSecond.record(1),this.metrics.broadcastBytesPerSecond.record(e.body.contentMessage.content.length))}async leaveStreamPart(e){const t=this.streamParts.get(e);t&&(await t.stop(),this.streamParts.delete(e))}joinStreamPart(e,t){let r=this.streamParts.get(e);if(void 0!==r)return;hW.debug(`Join stream part ${e}`);const n=this.createDiscoveryLayerNode(e,this.knownStreamPartEntryPoints.get(e)??[]),i=new PV({key:dW(e),localPeerDescriptor:this.getPeerDescriptor(),fetchDataFromDht:e=>this.controlLayerNode.fetchDataFromDht(e),storeDataToDht:(e,t)=>this.controlLayerNode.storeDataToDht(e,t),deleteDataFromDht:async(e,t)=>this.controlLayerNode.deleteDataFromDht(e,t)}),s=new _V({discoveryLayerNode:n,discoverEntryPoints:async()=>i.fetchNodes()}),o=this.createContentDeliveryLayerNode(e,n,(()=>i.isLocalNodeStored()),t),a=new NV(n,i);r={proxied:!1,discoveryLayerNode:n,node:o,networkSplitAvoidance:s,broadcast:e=>o.broadcast(e),stop:async()=>{a.destroy(),s.destroy(),await i.destroy(),o.stop(),await n.stop()},getDiagnosticInfo:()=>o.getDiagnosticInfo()},this.streamParts.set(e,r),o.on("message",(e=>{this.emit("newMessage",e)}));const c=async()=>{if(this.destroyed||i.isLocalNodeStored()||this.knownStreamPartEntryPoints.has(e))return;(await i.fetchNodes()).length<8&&await i.storeAndKeepLocalNode()};n.on("manualRejoinRequired",(async()=>{a.isRunning()||s.isRunning()||(hW.debug("Manual rejoin required for stream part",{streamPartId:e}),await a.reconnect())})),o.on("entryPointLeaveDetected",(()=>c())),setImmediate((async()=>{try{await this.startLayersAndJoinDht(e,i)}catch(t){hW.warn(`Failed to join to stream part ${e}`,{err:t})}}))}async startLayersAndJoinDht(e,t){hW.debug(`Start layers and join DHT for stream part ${e}`);const r=this.streamParts.get(e);if(void 0===r||r.proxied)return;this.transport.isPrivateClientMode()&&await this.transport.disablePrivateClientMode(),await r.discoveryLayerNode.start(),await r.node.start();const n=this.knownStreamPartEntryPoints.get(e);if(void 0!==n)await Promise.all([r.discoveryLayerNode.joinDht(n),r.discoveryLayerNode.joinRing()]);else{const e=await t.fetchNodes();await Promise.all([r.discoveryLayerNode.joinDht(wV(e,4)),r.discoveryLayerNode.joinRing()]),e.length<8&&(await t.storeAndKeepLocalNode(),r.discoveryLayerNode.getNeighborCount()<4&&setImmediate((()=>r.networkSplitAvoidance.avoidNetworkSplit())))}}createDiscoveryLayerNode(e,t){return new oV({transport:this.controlLayerNode,connectionsView:this.controlLayerNode.getConnectionsView(),serviceId:"layer1::"+e,peerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),entryPoints:t,numberOfNodesPerKBucket:4,rpcRequestTimeout:Fz,dhtJoinTimeout:2e4,periodicallyPingNeighbors:!0,periodicallyPingRingContacts:!0,neighborPingLimit:16})}createContentDeliveryLayerNode(e,t,r,n){return sW({streamPartId:e,transport:this.transport,discoveryLayerNode:t,connectionLocker:this.connectionLocker,localPeerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),minPropagationTargets:this.options.streamPartitionMinPropagationTargets,neighborTargetCount:this.options.streamPartitionNeighborTargetCount,maxPropagationBufferSize:this.options.streamPartitionMaxPropagationBufferSize,acceptProxyConnections:this.options.acceptProxyConnections,rpcRequestTimeout:this.options.rpcRequestTimeout,neighborUpdateInterval:this.options.neighborUpdateInterval,isLocalNodeEntryPoint:r,bufferWhileConnecting:this.options.bufferWhileConnecting,plumtreeOptimization:n?.plumtreeOptimization?.enabled,plumtreeMaxPausedNeighbors:!0===n?.plumtreeOptimization?.enabled?n?.plumtreeOptimization?.maxPausedNeighbors:void 0})}async setProxies(e,t,r,n,i){if(this.options.acceptProxyConnections)throw new Error("cannot set proxies when acceptProxyConnections=true");if(t.length>0&&(void 0===i||i>0)){let s;this.isProxiedStreamPart(e)?s=this.streamParts.get(e).client:(s=this.createProxyClient(e),this.streamParts.set(e,{proxied:!0,client:s,broadcast:e=>s.broadcast(e),stop:async()=>s.stop(),getDiagnosticInfo:()=>s.getDiagnosticInfo()}),s.on("message",(e=>{this.emit("newMessage",e)})),Array.from(this.streamParts.values()).every((e=>e.proxied))&&await this.transport.enablePrivateClientMode(),await s.start()),await s.setProxies(t,r,n,i)}else await(this.streamParts.get(e)?.stop()),this.streamParts.delete(e)}createProxyClient(e){return new lW({transport:this.transport,localPeerDescriptor:this.controlLayerNode.getLocalPeerDescriptor(),streamPartId:e,connectionLocker:this.connectionLocker,minPropagationTargets:this.options.streamPartitionMinPropagationTargets??2,maxPropagationBufferSize:this.options.streamPartitionMaxPropagationBufferSize??150,propagationBufferTtl:1e4})}async inspect(e,t){const r=this.streamParts.get(t);return void 0!==r&&!r.proxied&&r.node.inspect(e)}getNodeInfo(){const e=Array.from(this.streamParts.entries()).filter((([e,t])=>!1===t.proxied));return e.map((([e])=>{const t=this.streamParts.get(e);return{id:e,controlLayerNeighbors:t.discoveryLayerNode.getNeighbors(),deprecatedContentDeliveryLayerNeighbors:[],contentDeliveryLayerNeighbors:t.node.getInfos()}}))}setStreamPartEntryPoints(e,t){this.knownStreamPartEntryPoints.set(e,t)}isProxiedStreamPart(e,t){const r=this.streamParts.get(e);return void 0!==r&&r.proxied&&(void 0===t||r.client.getDirection()===t)}getStreamPartDelivery(e){return this.streamParts.get(e)}hasStreamPart(e){return this.streamParts.has(e)}getPeerDescriptor(){return this.controlLayerNode.getLocalPeerDescriptor()}getNodeId(){return Xj(this.controlLayerNode.getLocalPeerDescriptor())}getNeighbors(e){const t=this.streamParts.get(e);return!1===t?.proxied?t.node.getNeighbors().map((e=>Xj(e))):[]}getStreamParts(){return Array.from(this.streamParts.keys()).map((e=>AE.parse(e)))}getDiagnosticInfo(){return{streamParts:this.getStreamParts().map((e=>({id:e,info:this.getStreamPartDelivery(e).getDiagnosticInfo()})))}}}class pW extends jz{async getInfo(){return this.getClient().getInfo({},this.formDhtRpcOptions())}}class gW{ownPeerDescriptor;rpcCommunicator;constructor(e,t){this.ownPeerDescriptor=e,this.rpcCommunicator=t}async getInfo(e){return new pW(this.ownPeerDescriptor,e,this.rpcCommunicator,g$).getInfo()}}class mW{stack;rpcCommunicator;constructor(e,t){this.stack=e,this.rpcCommunicator=t,this.registerDefaultServerMethods()}registerDefaultServerMethods(){this.rpcCommunicator.registerRpcMethod(YH,XH,"getInfo",(()=>this.getInfo()))}async getInfo(){return this.stack.createNodeInfo()}}const yW=new Bv("NetworkStack"),bW=[],wW=async()=>{const e=[...bW];await Promise.all(e.map((e=>e.stop())))};if("object"==typeof process&&"function"==typeof process?.on){["exit","SIGINT","SIGUSR1","SIGUSR2","uncaughtException","unhandledRejection","SIGTERM"].forEach((e=>{process.on(e,(async t=>{const r="uncaughtException"===e||"unhandledRejection"===e;r&&yW.error(`exit event: ${e}`,t),await wW(),process.exit(r?1:0)}))}))}"object"==typeof window&&window.addEventListener("unload",(async()=>{await wW()}));class vW{controlLayerNode;contentDeliveryManager;stopped=!1;metricsContext;options;nodeInfoRpcLocal;nodeInfoClient;constructor(e){this.options=e,this.metricsContext=e.metricsContext??new $v,this.controlLayerNode=new oV({...e.layer0,metricsContext:this.metricsContext,allowIncomingPrivateConnections:e.networkNode?.acceptProxyConnections}),this.contentDeliveryManager=new fW({...e.networkNode,metricsContext:this.metricsContext}),bW.push(this)}async joinStreamPart(e,t,r){if(this.getContentDeliveryManager().isProxiedStreamPart(e))throw new Error(`Cannot join to ${e} as proxy connections have been set`);await this.ensureConnectedToControlLayer(),this.getContentDeliveryManager().joinStreamPart(e,r),void 0!==t&&await iE((()=>this.getContentDeliveryManager().getNeighbors(e).length>=t.minCount),t.timeout)}async broadcast(t,r){const n=EE(t.messageId.streamId,t.messageId.streamPartition);if(this.getContentDeliveryManager().isProxiedStreamPart(n,e.ProxyDirection.SUBSCRIBE)&&"contentMessage"===t.body.oneofKind)throw new Error(`Cannot broadcast to ${n} as proxy subscribe connections have been set`);this.contentDeliveryManager.isProxiedStreamPart(n)||await this.ensureConnectedToControlLayer(),this.getContentDeliveryManager().broadcast(t,r)}async start(e=!0){yW.info("Starting a Streamr Network Node"),await this.controlLayerNode.start(),yW.info(`Node id is ${Xj(this.controlLayerNode.getLocalPeerDescriptor())}`);const t=this.controlLayerNode.getTransport();if(this.options.layer0?.entryPoints?.some((e=>eq(e,this.controlLayerNode.getLocalPeerDescriptor())))?await(this.controlLayerNode?.joinDht(this.options.layer0.entryPoints)):e&&await this.ensureConnectedToControlLayer(),await(this.contentDeliveryManager?.start(this.controlLayerNode,t,t)),this.contentDeliveryManager){const e=new lK("system/node-info-rpc",this.getConnectionManager());this.nodeInfoRpcLocal=new mW(this,e),this.nodeInfoClient=new gW(this.controlLayerNode.getLocalPeerDescriptor(),e)}}async ensureConnectedToControlLayer(){this.controlLayerNode.hasJoined()||(setImmediate((async()=>{void 0!==this.options.layer0?.entryPoints&&await(this.controlLayerNode?.joinDht(this.options.layer0.entryPoints))})),await this.controlLayerNode.waitForNetworkConnectivity())}getContentDeliveryManager(){return this.contentDeliveryManager}getControlLayerNode(){return this.controlLayerNode}getMetricsContext(){return this.metricsContext}async fetchNodeInfo(e){return eq(e,this.getControlLayerNode().getLocalPeerDescriptor())?this.createNodeInfo():this.nodeInfoClient.getInfo(e)}createNodeInfo(){return{peerDescriptor:this.getControlLayerNode().getLocalPeerDescriptor(),controlLayer:{connections:this.getControlLayerNode().getConnectionsView().getConnections(),neighbors:this.getControlLayerNode().getNeighbors()},streamPartitions:this.getContentDeliveryManager().getNodeInfo(),applicationVersion:"103.6.0-rc.0"}}getOptions(){return this.options}getConnectionManager(){return this.controlLayerNode.getTransport()}async stop(){this.stopped||(this.stopped=!0,Ej(bW,this),await this.contentDeliveryManager.destroy(),await this.controlLayerNode.stop(),this.contentDeliveryManager=void 0,this.controlLayerNode=void 0)}}class EW{stack;stopped=!1;externalNetworkRpc;constructor(e){this.stack=e}async start(e){await this.stack.start(e),this.externalNetworkRpc=new RV(this.stack.getControlLayerNode().getTransport())}async inspect(e,t){return this.stack.getContentDeliveryManager().inspect(e,t)}async broadcast(e,t){await this.stack.broadcast(e,t)}async join(e,t,r){await this.stack.joinStreamPart(e,t,r)}async setProxies(e,t,r,n,i){await this.stack.getContentDeliveryManager().setProxies(e,t,r,n,i)}isProxiedStreamPart(e){return this.stack.getContentDeliveryManager().isProxiedStreamPart(e)}addMessageListener(e){this.stack.getContentDeliveryManager().on("newMessage",e)}setStreamPartEntryPoints(e,t){this.stack.getContentDeliveryManager().setStreamPartEntryPoints(e,t)}removeMessageListener(e){this.stack.getContentDeliveryManager().off("newMessage",e)}async leave(e){this.stopped||await this.stack.getContentDeliveryManager().leaveStreamPart(e)}getNeighbors(e){return this.stack.getContentDeliveryManager().getNeighbors(e)}hasStreamPart(e){return this.stack.getContentDeliveryManager().hasStreamPart(e)}async stop(){this.stopped=!0,this.externalNetworkRpc.destroy(),await this.stack.stop()}getPeerDescriptor(){return this.stack.getControlLayerNode().getLocalPeerDescriptor()}getMetricsContext(){return this.stack.getMetricsContext()}getNodeId(){return this.stack.getContentDeliveryManager().getNodeId()}getOptions(){return this.stack.getOptions()}getStreamParts(){return this.stack.getContentDeliveryManager().getStreamParts()}async fetchNodeInfo(e){return this.stack.fetchNodeInfo(e)}getDiagnosticInfo(){return{controlLayer:this.stack.getControlLayerNode().getDiagnosticInfo(),contentLayer:this.stack.getContentDeliveryManager().getDiagnosticInfo()}}registerExternalNetworkRpcMethod(e,t,r,n){this.externalNetworkRpc.registerRpcMethod(e,t,r,n)}createExternalRpcClient(e){return this.externalNetworkRpc.createRpcClient(e)}}class AW extends Error{code;constructor(e,t){super(e),this.code=t}}function SW(e,t){if(void 0===t)throw new AW(`Expected ${e} to not be undefined.`)}function kW(e,t,r=!1){if(!r||void 0!==t){if(SW(e,t),!Number.isInteger(t))throw new AW(`Expected ${e} to be an integer but was a ${typeof t} (${t}).`);if(t<0)throw new AW(`Expected ${e} to not be negative (${t}).`)}}class RW{timestamp;sequenceNumber;constructor(e,t){kW("timestamp",e),kW("sequenceNumber",t,!0),this.timestamp=e,this.sequenceNumber=t}compareTo(e){return this.timestamp<e.timestamp?-1:this.timestamp>e.timestamp?1:this.sequenceNumber<e.sequenceNumber?-1:this.sequenceNumber>e.sequenceNumber?1:0}}class CW{streamId;streamPartition;timestamp;sequenceNumber;publisherId;msgChainId;constructor(e,t,r,n,i,s){kW("streamPartition",t),kW("timestamp",r),kW("sequenceNumber",n),this.streamId=e,this.streamPartition=t,this.timestamp=r,this.sequenceNumber=n,this.publisherId=i,this.msgChainId=s}getStreamPartID(){return EE(this.streamId,this.streamPartition)}toMessageRef(){return new RW(this.timestamp,this.sequenceNumber)}}var IW;e.StreamMessageType=void 0,(IW=e.StreamMessageType||(e.StreamMessageType={}))[IW.MESSAGE=0]="MESSAGE",IW[IW.GROUP_KEY_REQUEST=1]="GROUP_KEY_REQUEST",IW[IW.GROUP_KEY_RESPONSE=2]="GROUP_KEY_RESPONSE";class PW{messageId;prevMsgRef;messageType;content;contentType;signature;signatureType;encryptionType;groupKeyId;newGroupKey;constructor({messageId:t,prevMsgRef:r,messageType:n=e.StreamMessageType.MESSAGE,content:i,contentType:s,signature:o,signatureType:a,encryptionType:c,groupKeyId:u,newGroupKey:l}){!function(e,t){if(void 0===t)return;const r=e.toMessageRef().compareTo(t);if(0===r)throw new AW(`prevMessageRef cannot be identical to current. Current: ${JSON.stringify(e.toMessageRef())} Previous: ${JSON.stringify(t)}`);if(r<0)throw new AW(`prevMessageRef must come before current. Current: ${JSON.stringify(e.toMessageRef())} Previous: ${JSON.stringify(t)}`)}(t,r),c===e.EncryptionType.AES&&SW("groupKeyId",u),this.messageId=t,this.prevMsgRef=r,this.messageType=n,this.contentType=s,this.encryptionType=c,this.groupKeyId=u,this.newGroupKey=l,this.signature=o,this.signatureType=a,this.content=i}getStreamId(){return this.messageId.streamId}getStreamPartition(){return this.messageId.streamPartition}getStreamPartID(){return this.messageId.getStreamPartID()}getTimestamp(){return this.messageId.timestamp}getSequenceNumber(){return this.messageId.sequenceNumber}getPublisherId(){return this.messageId.publisherId}getMsgChainId(){return this.messageId.msgChainId}getMessageRef(){return new RW(this.getTimestamp(),this.getSequenceNumber())}getParsedContent(){if(this.encryptionType!==e.EncryptionType.NONE||this.contentType===e.ContentType.BINARY)return this.content;if(this.contentType!==e.ContentType.JSON)throw new uA(`Unknown content type: ${this.contentType}`,"ASSERTION_FAILED",this);try{return JSON.parse(fw(this.content))}catch(e){throw new uA(`Unable to parse JSON: ${e}`,"INVALID_MESSAGE_CONTENT",this)}}static isAESEncrypted(t){return t.encryptionType===e.EncryptionType.AES}}class TW{static toProtobuf(t){const r={timestamp:t.getTimestamp(),sequenceNumber:t.getSequenceNumber(),streamId:t.getStreamId(),streamPartition:t.getStreamPartition(),publisherId:RE(t.getPublisherId()),messageChainId:t.getMsgChainId()};let n,i;if(t.prevMsgRef&&(n={timestamp:t.prevMsgRef.timestamp,sequenceNumber:t.prevMsgRef.sequenceNumber}),t.messageType===e.StreamMessageType.MESSAGE){let e;t.newGroupKey&&(e={id:t.newGroupKey.id,data:t.newGroupKey.data}),i={oneofKind:"contentMessage",contentMessage:{content:t.content,contentType:t.contentType,encryptionType:t.encryptionType,groupKeyId:t.groupKeyId??void 0,newGroupKey:e}}}else if(t.messageType===e.StreamMessageType.GROUP_KEY_REQUEST)i={oneofKind:"groupKeyRequest",groupKeyRequest:DH.fromBinary(t.content)};else{if(t.messageType!==e.StreamMessageType.GROUP_KEY_RESPONSE)throw new Error("invalid message type");i={oneofKind:"groupKeyResponse",groupKeyResponse:BH.fromBinary(t.content)}}return{messageId:r,previousMessageRef:n,signature:t.signature,signatureType:t.signatureType,body:i}}static toClientProtocol(t){let r,n,i,s,o=e.ContentType.BINARY,a=e.EncryptionType.NONE;if("contentMessage"===t.body.oneofKind)r=e.StreamMessageType.MESSAGE,n=t.body.contentMessage.content,o=t.body.contentMessage.contentType,a=t.body.contentMessage.encryptionType,i=t.body.contentMessage.newGroupKey,s=t.body.contentMessage.groupKeyId;else if("groupKeyRequest"===t.body.oneofKind){r=e.StreamMessageType.GROUP_KEY_REQUEST;try{n=DH.toBinary(t.body.groupKeyRequest)}catch(e){throw new Error(`invalid group key request: ${e}`)}}else{if("groupKeyResponse"!==t.body.oneofKind)throw new Error("invalid message type");r=e.StreamMessageType.GROUP_KEY_RESPONSE;try{n=BH.toBinary(t.body.groupKeyResponse)}catch(e){throw new Error(`invalid group key response: ${e}`)}}const c=new CW(t.messageId.streamId,t.messageId.streamPartition,Number(t.messageId.timestamp),t.messageId.sequenceNumber,kE(t.messageId.publisherId),t.messageId.messageChainId);let u;t.previousMessageRef&&(u=new RW(Number(t.previousMessageRef.timestamp),t.previousMessageRef.sequenceNumber));return new PW({messageId:c,prevMsgRef:u,messageType:r,content:n,contentType:o,signature:t.signature,signatureType:t.signatureType,encryptionType:a,groupKeyId:s,newGroupKey:i})}}function _W(e){return TW.toClientProtocol(xH.fromBinary(e))}async function*NW(e,t,r){let n=0;for await(const r of e){try{await t(r,n,e)}catch(e){throw e}finally{n+=1}yield r}}async function*MW(e,t,r){let n=0;for await(const r of e)try{yield await t(r,n,e)}catch(e){throw e}finally{n+=1}}async function*xW(e,t,r){let n=0;for await(const i of e){let s;try{s=await t(i,n,e)}catch(e){if(r){await r(e,i);continue}throw e}finally{n+=1}s&&(yield i)}}class OW{isLocked=!1;pending;open(){this.isLocked||this.clearPending()}lock(){this.isLocked||(this.isLocked=!0,this.clearPending())}error(e){this.isLocked||this.clearPending(e)}close(){this.isLocked||(this.pending??=new eb)}setOpenState(e){e?this.open():this.close()}isOpen(){return!this.isLocked&&!this.pending}clearPending(e){const{pending:t}=this;t&&(this.pending=void 0,e?t.reject(e):t.resolve(void 0))}async check(){return this.pending&&await this.pending,!this.isLocked}}class DW{buffer=[];bufferSize;writeGate;readGate;error;iterator;isIterating=!1;constructor(e=256){if(!(e>0&&Number.isSafeInteger(e)))throw new uA(`bufferSize must be a safe positive integer, got: ${e}`,"INVALID_ARGUMENT");this.bufferSize=e,this.writeGate=new OW,this.readGate=new OW,this.writeGate.close(),this.readGate.close(),this.iterator=this.iterate()}async push(e){return!!this.isWritable()&&(this.buffer.push(e),this.updateWriteGate(),this.readGate.open(),this.writeGate.check())}updateWriteGate(){this.writeGate.setOpenState(!this.isFull())}end(e){e&&(this.error=e),this.lock()}lock(){this.writeGate.lock(),this.readGate.lock()}endWrite(e){e&&!this.error&&(this.error=e),this.readGate.open(),this.writeGate.lock()}isFull(){return this.buffer.length>=this.bufferSize}isDone(){return this.writeGate.isLocked&&this.readGate.isLocked}isWritable(){return!this.writeGate.isLocked&&!this.readGate.isLocked}async*iterate(){this.isIterating=!0;try{for(;!this.readGate.isLocked;){for(;this.buffer.length&&!this.readGate.isLocked;){const t=this.buffer.shift();if(this.updateWriteGate(),(e=t)&&(e instanceof Error||e?.stack&&e.message&&"string"==typeof e.stack&&"string"==typeof e.message))throw t;yield t}if(0===this.buffer.length&&this.writeGate.isLocked)break;if(this.isDone())break;this.readGate.close();if(!await this.readGate.check())break}const{error:t}=this;if(t)throw this.error=void 0,t}finally{this.buffer=[],this.lock()}var e}get length(){return this.buffer.length}clear(){this.buffer=[]}async throw(e){return this.endWrite(e),this.iterator.throw(e)}async return(e){return this.end(),this.iterator.return(e)}next(){return this.iterator.next()}[Symbol.asyncIterator](){if(this.isIterating)throw new this.constructor.Error(this,"already iterating");return this}async[Symbol.asyncDispose](){this.end()}}var BW,LW,FW=pt();function UW(e,t){if("pipe"in e)return e;const r=new Tr.PassThrough(t);return async function(e,t){const r=e.getReader(),n=new AbortController;try{for(;;){const{value:e,done:i}=await r.read();if(i)break;if(!t.writable)break;if(!t.write(e))try{await FW.once(t,"drain",n)}catch(e){if("AbortError"===e.name)break;throw e}}}catch(e){t.destroy(e),n.abort()}finally{t.end();try{await r.cancel()}catch(e){}r.releaseLock()}}(e,r),r}var jW=function(){if(LW)return BW;LW=1;var e=Ju(),t=0;return BW=function(r){var n=++t;return e(r)+n},BW}(),qW=n(jW);let zW;function KW(e=""){return void 0===zW&&(zW=xF()),qW(`${zW}${e?`-${e}`:""}`)}const GW=new Bv("sdk-utils"),VW=((e,{maxPrefixes:t=256}={})=>{let r={},n=!1;const i=(i="ID",s="-")=>{if(r[i]=(r[i]+1||0)%Number.MAX_SAFE_INTEGER,!n){const e=Object.keys(r).length;e>t&&(n=!0,console.warn(`counterId should not be used for a large number of unique prefixes: ${e} > ${t}`))}return[e,i,r[i]].filter((e=>null!=e)).join(s)};return i.clear=(...e)=>{if(e.length){const[t]=e;delete r[t]}else r={}},i})();function HW(e){return bE("/assignments",nb(e))}class $W{delegate;constructor(e){this.delegate=new Mj({maxSize:e,sizeCalculation:()=>1})}add(e){this.delegate.set(e,!0)}has(e){return this.delegate.has(e)}delete(e){this.delegate.delete(e)}}function WW(t){const r=t.type===e.NetworkNodeType.BROWSER?bq.BROWSER:bq.NODEJS,n={...t,nodeId:Yj(t.nodeId??t.id),type:r,websocket:t.websocket};return void 0!==n.id&&delete n.id,n}function JW(t){return{nodeId:Zj(t.nodeId),type:t.type===bq.NODEJS?e.NetworkNodeType.NODEJS:e.NetworkNodeType.BROWSER,websocket:t.websocket,region:t.region}}const QW=e=>Array.isArray(e)?e.map((e=>e.toString())).join("|"):e.toString();class ZW extends Error{response;constructor(e){super(`Fetch error, url=${e.url}`),this.response=e}}var YW,XW={exports:{}};var eJ=function(){if(YW)return XW.exports;YW=1;class e extends Error{constructor(){super("Throttled function aborted"),this.name="AbortError"}}return XW.exports=({limit:t,interval:r,strict:n})=>{if(!Number.isFinite(t))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(r))throw new TypeError("Expected `interval` to be a finite number");const i=new Map;let s=0,o=0;const a=[];const c=n?function(){const e=Date.now();if(a.length<t)return a.push(e),0;const n=a.shift()+r;return e>=n?(a.push(e),0):(a.push(n),n-e)}:function(){const e=Date.now();return e-s>r?(o=1,s=e,0):(o<t?o++:(s+=r,o=1),s-e)};return t=>{const r=function(...e){if(!r.isEnabled)return(async()=>t.apply(this,e))();let n;return new Promise(((r,s)=>{n=setTimeout((()=>{r(t.apply(this,e)),i.delete(n)}),c()),i.set(n,s)}))};return r.abort=()=>{for(const t of i.keys())clearTimeout(t),i.get(t)(new e);i.clear(),a.splice(0,a.length)},r.isEnabled=!0,r}},XW.exports.AbortError=e,XW.exports}(),tJ=n(eJ);function rJ(e,t=1){const r=gD(t);return Object.assign(((...t)=>r((()=>e(...t)))),{clear(){r.clearQueue()}})}function nJ(e){let t={status:"init"};return Object.assign((async function(...r){const n=t;if("pending"===n.status)return n.promise;if("fulfilled"===n.status)return n.value;if("rejected"===n.status)throw n.reason;t=n;const i=(async()=>{try{const t=await e(...r);return Object.assign(n,{promise:void 0,status:"fulfilled",value:t}),t}catch(e){throw Object.assign(n,{promise:void 0,status:"rejected",reason:e}),e}})();return i.catch((()=>{})),Object.assign(n,{status:"pending",promise:i}),i}),{isStarted:()=>"init"!==t.status,reset(){t={status:"init"}}})}var iJ;!function(e){e.ONCE="ONCE",e.ONE="ONE",e.QUEUE="QUEUE",e.PARALLEL="PARALLEL"}(iJ||(iJ={}));class sJ{static TRIGGER_TYPE=iJ;static create(e=iJ.PARALLEL){return new this(e)}static once(){return this.create(iJ.ONCE)}static one(){return this.create(iJ.ONE)}static queue(){return this.create(iJ.QUEUE)}static parallel(){return this.create(iJ.PARALLEL)}listeners=[];isEnded=!1;triggerCountValue=0;triggerType;constructor(e=iJ.PARALLEL){switch(this.triggerType=e,this.trigger=Function.prototype.bind.call(this.trigger,this),e){case iJ.ONCE:this.trigger=nJ(this.trigger);break;case iJ.QUEUE:this.trigger=rJ(this.trigger);break;case iJ.ONE:this.trigger=function(e){const t=nJ(e);return async(...e)=>{try{return await t(...e)}finally{t.reset()}}}(this.trigger);break;case iJ.PARALLEL:break;default:throw new Error(`unknown trigger type: ${e}`)}}triggerCount(){return this.triggerCountValue}lastValue;end=(...e)=>{this.lastValue=e,this.isEnded=!0};wait(){return new Promise((e=>{this.once(((...t)=>e(t[0])))}))}async getLastValue(){if(this.currentTask&&await this.currentTask,!this.lastValue)throw new Error("Signal ended with no value");return this.lastValue}listen(e){return e?this.isEnded?(this.getLastValue().then((t=>e(...t))).catch((()=>{})),this):(this.listeners.push(e),this):new Promise((e=>{this.once(((...t)=>{e(t[0])}))}))}once(e){if(!e)return this.listen();const t=Object.assign(((...t)=>(this.unlisten(e),e(...t))),{listener:e});return this.listen(t)}countListeners(){return this.listeners.length}unlisten(e){const t=this.listeners.findIndex((t=>t===e||"listener"in t&&t.listener===e));return this.listeners.splice(t,1),this}async execTrigger(...e){if(this.isEnded)return;this.triggerCountValue+=1;const t=this.listeners.slice();this.triggerType===iJ.ONCE&&(this.listeners=[],this.end(...e)),t.length&&await t.reduce((async(t,r)=>{await t,await r(...e)}),Promise.resolve())}currentTask;async trigger(...e){const t=this.execTrigger(...e);this.currentTask=t;try{await this.currentTask}finally{this.currentTask===t&&(this.currentTask=void 0)}}async*[Symbol.asyncIterator](){for(;!this.isEnded;)yield await this.listen()}}class oJ extends sJ{seenErrors=new WeakSet;ignoredErrors=new WeakSet;minListeners=1;async execTrigger(...e){if(this.isEnded)return;this.triggerCountValue+=1;const t=this.listeners.slice();this.triggerType===iJ.ONCE&&(this.listeners=[],this.end(...e)),t.length&&await t.reduce((async(t,r)=>{try{await t}catch(e){return void await r(e)}await r(...e)}),Promise.resolve())}async trigger(...e){const t=e[0];if(this.ignoredErrors.has(t))return;if(this.seenErrors.has(t))throw t;this.seenErrors.add(t);const r=!!(this.countListeners()>=this.minListeners);try{if(await super.trigger(...e),!r)throw t;this.ignoredErrors.add(t)}catch(e){throw this.seenErrors.add(e),e}}}class aJ{source;transforms;constructor(e,t=[]){this.source=this.setSource(e),this.transforms=t}pipe(e){return this.transforms.push(e),this}clearTransforms(){this.transforms=[]}setSource(e){const t="id"in e?e.id:function(e,t=""){return VW(e.constructor.name)+t}(e,"Source");return this.source=Object.assign(e,{id:t}),this.source}getTransforms(){return this.transforms}}class cJ{source;iterator;isIterating=!1;isCleaningUp=!1;definition;constructor(e,t){this.source=e,this.definition=t??new aJ(e),this.cleanup=nJ(this.cleanup.bind(this)),this.iterator=function(e,t){if(!t)return async function*(){yield*e}();let r,n,i=!1,s=!1,o=e=>(n??=Promise.resolve(t(e)).finally((()=>{o=()=>{}})),n);function a(e){return async(...t)=>{if(s=!0,i)return e(...t);try{return await e(...t)}catch(e){throw r??=e,e}finally{await o(r)}}}const c=async function*(){i=!0;try{yield*e}catch(e){throw r??=e,e}finally{await o(r)}}(),u=c[Symbol.asyncIterator].bind(c);let l;return l="cancel"in e?Object.assign(c,{cancel:t=>e.cancel(t),isCancelled:()=>e.isCancelled()}):c,Object.assign(l,{return:a(l.return.bind(l)),throw:a(l.throw.bind(l)),[Symbol.asyncIterator]:()=>s&&!i?async function*(){try{"return"in e&&await e.return(void 0)}finally{await o()}}():u()})}(this.iterate(),this.cleanup),this.handleError=this.handleError.bind(this)}pipe(e){if(this.isIterating)throw new uA(`cannot pipe after already iterating: ${this.isIterating}`,"PIPELINE_ERROR");return this.definition.pipe(e),this}onFinally=sJ.once();onBeforeFinally=sJ.once();onMessage=sJ.create();onError=oJ.create();filter(e){return this.pipe((t=>xW(t,e,this.onError.trigger)))}flow(){return setImmediate((()=>{this.isIterating||async function(e,t=e=>e){(async e=>{for await(const t of e);})(NW(e,t))}(this)})),this}async cleanup(e){this.isCleaningUp=!0;try{try{e&&await this.onError.trigger(e)}finally{await this.definition.source.return(void 0)}}finally{await this.onBeforeFinally.trigger(),await this.onFinally.trigger(e),this.definition.clearTransforms()}}async handleError(e){await this.onError.trigger(e)}async*iterate(){if(this.isIterating=!0,!this.definition.source)throw new uA("no source","PIPELINE_ERROR");const e=this.definition.getTransforms().reduce(((e,t)=>t(e)),this.definition.source);try{for await(const t of e)await this.onMessage.trigger(t),yield t;this.isCleaningUp=!0}catch(e){this.isCleaningUp=!0,await this.handleError(e)}finally{this.isCleaningUp=!0,this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger()}}async throw(e){if(this.isCleaningUp)throw e;return this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger(),await this.definition.source.throw(e).catch((()=>{})),this.iterator.throw(e)}async return(e){return this.isCleaningUp?Promise.resolve({done:!0,value:e}):(this.onBeforeFinally.triggerCount||await this.onBeforeFinally.trigger(),await this.definition.source.return(void 0),this.iterator.return(e))}async next(){return this.iterator.next()}[Symbol.asyncIterator](){if(this.isIterating)throw new uA("already iterating","PIPELINE_ERROR");return this}[Symbol.asyncDispose](){return this.cleanup()}}class uJ extends cJ{source;constructor(e=256){const t=new DW(e);super(t),this.source=t}pipe(e){return super.pipe(e),this}filter(e){return super.filter(e)}async push(e){return this.source.push(e)}async handleError(e){try{await this.onError.trigger(e)}catch(e){if(this.isCleaningUp)throw e;await this.push(e)}}end(e){this.source.end(e)}endWrite(e){this.source.endWrite(e)}isDone(){return this.source.isDone()}get length(){return this.source.length||0}clear(){this.source.clear()}}var lJ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},hJ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let dJ=class{onDestroy=sJ.once();trigger=this.destroy;abortSignal;constructor(){const e=new AbortController;this.abortSignal=e.signal,this.onDestroy.listen((()=>{e.abort()}))}destroy(){return this.onDestroy.trigger()}assertNotDestroyed(){if(this.isDestroyed())throw new uA("Client is destroyed. Create a new instance","CLIENT_DESTROYED")}isDestroyed(){return this.onDestroy.triggerCount()>0}};var fJ,pJ,gJ,mJ,yJ,bJ;dJ=lJ([q(d.ContainerScoped),hJ("design:paramtypes",[])],dJ);var wJ=function(){if(bJ)return yJ;bJ=1;var e=Jc(),t=function(){if(pJ)return fJ;pJ=1;var e=Vc(),t=$c(),r=Wc(),n=Jc(),i=Qc(),s=Zc(),o=Math.min;return fJ=function(a,c,u){for(var l=u?r:t,h=a[0].length,d=a.length,f=d,p=Array(d),g=1/0,m=[];f--;){var y=a[f];f&&c&&(y=n(y,i(c))),g=o(y.length,g),p[f]=!u&&(c||h>=120&&y.length>=120)?new e(f&&y):void 0}y=a[0];var b=-1,w=p[0];e:for(;++b<h&&m.length<g;){var v=y[b],E=c?c(v):v;if(v=u||0!==v?v:0,!(w?s(w,E):l(m,E,u))){for(f=d;--f;){var A=p[f];if(!(A?s(A,E):l(a[f],E,u)))continue e}w&&w.push(E),m.push(v)}}return m},fJ}(),r=nu(),n=function(){if(mJ)return gJ;mJ=1;var e=ou();return gJ=function(t){return e(t)?t:[]}}(),i=r((function(r){var i=e(r,n);return i.length&&i[0]===r[0]?t(i):[]}));return yJ=i}(),vJ=n(wJ),EJ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},AJ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},SJ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};function kJ(e){const t=e;if(void 0!==t.id)return t.id;if(void 0!==t.stream)return t.stream;if(void 0!==t.streamId)return t.streamId;throw new Error('streamDefinition: object must have property: "id", "stream", or "streamId"')}let RJ=class{identity;constructor(e){this.identity=e}async toStreamID(e){let t;return wE.isPathOnlyFormat(e)&&(t=nb(await this.identity.getUserId())),bE(e,t)}async toStreamPartID(e){const[t,r]=await this.toStreamPartElements(e);return EE(t,r??0)}async toStreamPartElements(e){const[t,r]=function(e){if("string"==typeof e)return AE.parseRawElements(e);if("object"==typeof e)return[kJ(e),e.partition];throw new Error("streamDefinition: must be of type string or object")}(e);return[await this.toStreamID(t),r]}async getMatcher(e){const[t,r]=await this.toStreamPartElements(e);return e=>t===AE.getStreamID(e)&&(void 0===r||r===AE.getStreamPartition(e))}};RJ=EJ([q(d.ContainerScoped),SJ(0,U(kA)),AJ("design:paramtypes",[RA])],RJ);const CJ=e=>{try{return JSON.parse(e)}catch(e){return{}}},IJ=e=>{const t=e.partitions;if(void 0!==t)try{!function(e){if(!Number.isSafeInteger(e)||e<0||e>100)throw new Error(`invalid streamPartition value: ${e}`)}(t)}catch{throw new uA(`Invalid partition count: ${t}`,"INVALID_STREAM_METADATA")}return t??1};var PJ;e.StreamPermission=void 0,(PJ=e.StreamPermission||(e.StreamPermission={})).EDIT="edit",PJ.DELETE="delete",PJ.PUBLISH="publish",PJ.SUBSCRIBE="subscribe",PJ.GRANT="grant";const TJ="0x0000000000000000000000000000000000000000",_J=e=>!0===e.public,NJ=e=>"userId"in e?{...e,userId:kE(e.userId)}:e,MJ=t=>{switch(t){case e.StreamPermission.EDIT:return 0n;case e.StreamPermission.DELETE:return 1n;case e.StreamPermission.PUBLISH:return 2n;case e.StreamPermission.SUBSCRIBE:return 3n;case e.StreamPermission.GRANT:return 4n}return 0n},xJ=t=>{const r=Math.round(Date.now()/1e3),n=[];return t.canEdit&&n.push(e.StreamPermission.EDIT),t.canDelete&&n.push(e.StreamPermission.DELETE),t.publishExpiration>r&&n.push(e.StreamPermission.PUBLISH),t.subscribeExpiration>r&&n.push(e.StreamPermission.SUBSCRIBE),t.canGrant&&n.push(e.StreamPermission.GRANT),n};class OJ{delegate;pendingPromises=new Map;opts;constructor(e){this.delegate="maxSize"in e?new Mj({maxSize:e.maxSize,sizeCalculation:()=>1,ttl:e.maxAge}):new Map,this.opts={isCacheableValue:()=>!0,...e}}async get(e){const t=QW(e),r=this.pendingPromises.get(t);if(void 0!==r)return await r;{let r=this.delegate.get(t);if(void 0===r){const n=this.opts.valueFactory(e);let i;this.pendingPromises.set(t,n);try{i=await n}finally{this.pendingPromises.delete(t)}r={key:e,value:i},this.opts.isCacheableValue(i)&&this.delegate.set(t,r)}return r.value}}set(e,t){this.delegate.set(QW(e),{key:e,value:t})}invalidate(e){for(const[t,r]of this.delegate.entries())e(r.key)&&this.delegate.delete(t)}*values(){for(const e of this.delegate.values())yield e.value}}const DJ=e=>new OJ(e),BJ=e=>new OJ(e);var LJ,FJ,UJ,jJ,qJ,zJ,KJ,GJ;function VJ(){if(jJ)return UJ;jJ=1;var e=Pl(),t=uj(),r=function(){if(FJ)return LJ;FJ=1;var e=sL(),t=Ku();return LJ=function(r,n){return n.length<2?r:e(r,t(n,0,-1))},LJ}(),n=_l();return UJ=function(i,s){return s=e(s,i),null==(i=r(i,s))||delete i[n(t(s))]},UJ}var HJ,$J,WJ,JJ,QJ,ZJ,YJ,XJ,eQ=function(){if(GJ)return KJ;GJ=1;var e=uL(),t=function(){if(zJ)return qJ;zJ=1;var e=VJ(),t=Tl(),r=Array.prototype.splice;return qJ=function(n,i){for(var s=n?i.length:0,o=s-1;s--;){var a=i[s];if(s==o||a!==c){var c=a;t(a)?r.call(n,a,1):e(n,a)}}return n},qJ}();return KJ=function(r,n){var i=[];if(!r||!r.length)return i;var s=-1,o=[],a=r.length;for(n=e(n,3);++s<a;){var c=r[s];n(c,s,r)&&(i.push(c),o.push(s))}return t(r,o),i},KJ}(),tQ=n(eQ);function rQ(){if(JJ)return WJ;JJ=1;var e=YB(),t=$J?HJ:($J=1,HJ=function(){}),r=VB(),n=e&&1/r(new e([,-0]))[1]==1/0?function(t){return new e(t)}:t;return WJ=n}var nQ=function(){if(XJ)return YJ;XJ=1;var e=function(){if(ZJ)return QJ;ZJ=1;var e=Vc(),t=$c(),r=Wc(),n=Zc(),i=rQ(),s=VB();return QJ=function(o,a,c){var u=-1,l=t,h=o.length,d=!0,f=[],p=f;if(c)d=!1,l=r;else if(h>=200){var g=a?null:i(o);if(g)return s(g);d=!1,l=n,p=new e}else p=a?[]:f;e:for(;++u<h;){var m=o[u],y=a?a(m):m;if(m=c||0!==m?m:0,d&&y==y){for(var b=p.length;b--;)if(p[b]===y)continue e;a&&p.push(y),f.push(m)}else l(p,y,c)||(p!==f&&p.push(y),f.push(m))}return f},QJ}();return YJ=function(t){return t&&t.length?e(t):[]},YJ}(),iQ=n(nQ),sQ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},oQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},aQ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let cQ=class{listeners=[];providers;pollInterval;abortController;constructor(e,t){this.providers=e.getSubProviders(),this.pollInterval=t.contracts.pollInterval}on(e){const t=this.listeners.length>0;this.listeners.push(e),t||this.start()}off(e){const t=this.listeners.length>0;tQ(this.listeners,(t=>t.contractAddress===e.contractAddress&&t.contractInterfaceFragment.topicHash===e.contractInterfaceFragment.topicHash&&t.onEvent==e.onEvent)),t&&0===this.listeners.length&&this.abortController.abort()}start(){const e=new AbortController;this.abortController=e,setImmediate((async()=>{const t=new Bv("ChainEventPoller",{sessionId:Wv(6)});let r;t.debug("Start polling",{pollInterval:this.pollInterval});do{try{r=await oA(this.providers).getBlockNumber()}catch(e){t.debug("Failed to query block number",{err:e}),await Qv(1e3)}}while(void 0===r);let n=0;await Jv((async()=>{const i=oA(this.providers),s=this.listeners.map((e=>e.contractInterfaceFragment.name));let o,a=0;try{if(n>=30&&(a=await i.getBlockNumber()+1,t.debug("Fetch next block number explicitly",{newFromBlock:a}),e.signal.aborted))return;t.debug("Polling",{fromBlock:r,eventNames:s});const c={address:iQ(this.listeners.map((e=>e.contractAddress))),topics:[iQ(this.listeners.map((e=>e.contractInterfaceFragment.topicHash)))],fromBlock:r},u=await i.getLogs(c);o=[];for(const e of u){const t=this.listeners.find((t=>t.contractAddress===nb(e.address)&&t.contractInterfaceFragment.topicHash===e.topics[0]));if(void 0!==t){const r=new uN([t.contractInterfaceFragment.format("minimal")]).decodeEventLog(t.contractInterfaceFragment.name,e.data,e.topics);o.push({contractAddress:t.contractAddress,name:t.contractInterfaceFragment.name,args:r,blockNumber:e.blockNumber})}}t.debug("Polled",{fromBlock:r,events:o.length})}catch(e){t.debug("Failed to poll",{reason:e?.reason,eventNames:s,fromBlock:r})}if(!e.signal.aborted){if(void 0!==o&&o.length>0){for(const e of o){const t=this.listeners.filter((t=>t.contractAddress===e.contractAddress&&t.contractInterfaceFragment.name===e.name));for(const r of t)r.onEvent(e.args,e.blockNumber)}a=Math.max(...o.map((e=>e.blockNumber)))+1}void 0!==o&&a>r?(t.debug("Forward fromBlock",{before:r,after:a}),r=a,n=0):n+=1}}),this.pollInterval,!0,e.signal)}))}};cQ=sQ([q(d.ContainerScoped),aQ(1,U(cA)),oQ("design:paramtypes",[e.RpcProviderSource,Object])],cQ);const uQ=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),lQ=e=>`"${e}"`,hQ=e=>`{ ${e} }`,dQ=(t,r,n)=>{const i=[];return t.includes(e.StreamPermission.EDIT)&&i.push("canEdit: true"),t.includes(e.StreamPermission.DELETE)&&i.push("canDelete: true"),t.includes(e.StreamPermission.PUBLISH)&&i.push(`publishExpiration_gt: "${n}"`),t.includes(e.StreamPermission.SUBSCRIBE)&&i.push(`subscribeExpiration_gt: "${n}"`),t.includes(e.StreamPermission.GRANT)&&i.push("canGrant: true"),`${r}: [${i.map(hQ).join(", ")}]`},fQ=(t,r,n,i)=>{const s=[];if(s.push(`id_gt: "${uQ(n)}"`),void 0!==t&&s.push(`idAsString_contains: "${uQ(t)}"`),void 0!==r){const t=[],n=[r.userId];r.allowPublic&&n.push(TJ),t.push(`userId_in: [${n.map(lQ).join(",")}]`);const i=Math.round(Date.now()/1e3);void 0!==r.allOf&&t.push(dQ(r.allOf,"and",i));const o=r.anyOf??(void 0===r.allOf||0===r.allOf.length?Object.values(e.StreamPermission):void 0);void 0!==o&&t.push(dQ(o,"or",i)),s.push(`permissions_: { and: [${t.map(hQ).join(", ")}] }`)}return{query:`\n query {\n streams (\n first: ${i}\n orderBy: "id"\n where: {\n ${s.join(", ")}\n }\n ) {\n id\n metadata\n }\n }`}};var pQ,gQ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},mQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},yQ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const bQ=t=>{for(const r of t){const t=[e.StreamPermission.EDIT,e.StreamPermission.DELETE,e.StreamPermission.GRANT],n=vJ(r.permissions,t);if(n.length>0){const e=e=>new uA(`${e} is not supported for permission types: ${n.map((e=>e.toUpperCase())).join(", ")}`,"UNSUPPORTED_OPERATION");if(_J(r))throw e("Public permission");if(42!==r.userId.length)throw e("Non-Ethereum user id")}}},wQ=(e,t,r)=>{throw"CALL_EXCEPTION"===e.reason?.code?new uA("Stream not found: id="+t,"STREAM_NOT_FOUND"):new Error(`Could not reach the ${r} Smart Contract: ${e.message}`)},vQ=(e,t)=>{e.invalidate((e=>(Array.isArray(e)?e[0]:e)===t))};let EQ=pQ=class{streamRegistryContract;streamRegistryContractReadonly;contractFactory;rpcProviderSource;theGraphClient;streamIdBuilder;config;identity;logger;metadataCache;publisherCache;subscriberCache;publicSubscribePermissionCache;constructor(t,r,n,i,s,o,a,c,u){this.contractFactory=t,this.rpcProviderSource=r,this.theGraphClient=i,this.streamIdBuilder=s,this.config=o,this.identity=a,this.logger=u.createLogger("StreamRegistry"),this.streamRegistryContractReadonly=this.contractFactory.createReadContract(nb(this.config.contracts.streamRegistryChainAddress),SA.StreamRegistryABI,this.rpcProviderSource.getProvider(),"streamRegistry"),wD({sourceDefinition:{contractInterfaceFragment:new uN(SA.StreamRegistryABI).getEvent("StreamCreated"),contractAddress:nb(this.config.contracts.streamRegistryChainAddress)},sourceEmitter:n,targetName:"streamCreated",targetEmitter:c,transformation:([e,t],r)=>({streamId:bE(e),metadata:CJ(t),blockNumber:r}),loggerFactory:u}),this.metadataCache=DJ({valueFactory:e=>this.getStreamMetadata_nonCached(e),...o.cache}),this.publisherCache=DJ({valueFactory:([t,r])=>this.isStreamPublisherOrSubscriber_nonCached(t,r,e.StreamPermission.PUBLISH),...o.cache}),this.subscriberCache=DJ({valueFactory:([t,r])=>this.isStreamPublisherOrSubscriber_nonCached(t,r,e.StreamPermission.SUBSCRIBE),...o.cache}),this.publicSubscribePermissionCache=DJ({valueFactory:t=>this.hasPermission({streamId:t,public:!0,permission:e.StreamPermission.SUBSCRIBE}),...o.cache})}async connectToContract(){if(void 0===this.streamRegistryContract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.streamRegistryContract=this.contractFactory.createWriteContract(nb(this.config.contracts.streamRegistryChainAddress),SA.StreamRegistryABI,e,"streamRegistry")}}async createStream(e,t){const r=await nD(this.rpcProviderSource,this.config),n=wE.getDomainAndPath(e);if(void 0===n)throw new Error(`stream id "${e}" not valid`);const[i,s]=n;if(await this.connectToContract(),function(e){return tb(e)}(i)){await mD(this.streamRegistryContract.createStreamWithENS(i,s,JSON.stringify(t),r));try{await iE((async()=>this.streamExistsOnChain(e)),this.config._timeouts.ensStreamCreation.timeout,this.config._timeouts.ensStreamCreation.retryInterval)}catch{throw new Error(`unable to create stream "${e}"`)}}else await this.ensureStreamIdInNamespaceOfAuthenticatedUser(i,e),await mD(this.streamRegistryContract.createStream(s,JSON.stringify(t),r));this.populateMetadataCache(e,t)}async ensureStreamIdInNamespaceOfAuthenticatedUser(e,t){const r=nb(await this.identity.getUserId());if(e!==r)throw new Error(`stream id "${t}" not in namespace of authenticated user "${r}"`)}async setStreamMetadata(e,t){await this.connectToContract();const r=await nD(this.rpcProviderSource,this.config);await mD(this.streamRegistryContract.updateStreamMetadata(e,JSON.stringify(t),r)),this.populateMetadataCache(e,t)}async deleteStream(e){const t=await this.streamIdBuilder.toStreamID(e);await this.connectToContract();const r=await nD(this.rpcProviderSource,this.config);await mD(this.streamRegistryContract.deleteStream(t,r)),vQ(this.metadataCache,t),this.invalidatePermissionCaches(t)}async streamExistsOnChain(e){const t=await this.streamIdBuilder.toStreamID(e);return this.logger.debug("Check if stream exists on chain",{streamId:t}),this.streamRegistryContractReadonly.exists(t)}async getStreamMetadata_nonCached(e){let t;try{t=await this.streamRegistryContractReadonly.getStreamMetadata(e)}catch(t){return wQ(t,e,"StreamRegistry")}return CJ(t)}async*searchStreams(e,t){const r=async function*(e,t,r){yield*r.queryEntities(((r,n)=>fQ(e,t,r,n)))}(e,t,this.theGraphClient);for await(const e of r){const t=bE(e.id);this.populateMetadataCache(t,CJ(e.metadata)),yield t}}getStreamPublishers(e){return this.getStreamPublishersOrSubscribersList(e,"publishExpiration")}getStreamSubscribers(e){return this.getStreamPublishersOrSubscribersList(e,"subscribeExpiration")}async*getStreamPublishersOrSubscribersList(e,t){const r=await this.streamIdBuilder.toStreamID(e),n=xW(this.theGraphClient.queryEntities(((e,n)=>pQ.buildStreamPublishersOrSubscribersQuery(r,t,e,n))),(e=>null!==e.stream));yield*MW(n,(e=>kE(e.userId)))}static buildStreamPublishersOrSubscribersQuery(e,t,r,n){return{query:`\n {\n streamPermissions (\n first: ${n}\n orderBy: "id"\n where: {\n id_gt: "${r}"\n stream: "${e}"\n ${t}_gt: "${Math.round(Date.now()/1e3)}"\n }\n ) {\n id\n userId\n stream {\n id\n }\n }\n }`}}async hasPermission(e){if((e=>!0===e.public)(e)){const t=MJ(e.permission);return this.streamRegistryContractReadonly.hasPublicPermission(e.streamId,t)}{const t=e.allowPublic?await this.streamRegistryContractReadonly.getPermissionsForUserId(e.streamId,e.userId):await this.streamRegistryContractReadonly.getDirectPermissionsForUserId(e.streamId,e.userId);return xJ(t).includes(e.permission)}}async getPermissions(e){const t=await this.streamIdBuilder.toStreamID(e),r=await cE(this.theGraphClient.queryEntities(((e,r)=>({query:`{\n stream (id: "${t}") {\n id\n metadata\n permissions(first: ${r} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n userId\n canEdit\n canDelete\n publishExpiration\n subscribeExpiration\n canGrant\n }\n }\n }`})),(e=>{if(null!==e.stream)return e.stream.permissions;throw new uA("Stream not found: id="+t,"STREAM_NOT_FOUND")}))),n=[];return r.forEach((e=>{const t=xJ(e);t.length>0&&(e.userId===TJ?n.push({public:!0,permissions:t}):n.push({userId:kE(e.userId),permissions:t}))})),n}async grantPermissions(e,...t){bQ(t);const r=await nD(this.rpcProviderSource,this.config);return this.updatePermissions(e,((e,t,n)=>void 0===t?this.streamRegistryContract.grantPublicPermission(e,n,r):this.streamRegistryContract.grantPermissionForUserId(e,t,n,r)),...t)}async revokePermissions(e,...t){bQ(t);const r=await nD(this.rpcProviderSource,this.config);return this.updatePermissions(e,((e,t,n)=>void 0===t?this.streamRegistryContract.revokePublicPermission(e,n,r):this.streamRegistryContract.revokePermissionForUserId(e,t,n,r)),...t)}async updatePermissions(e,t,...r){const n=await this.streamIdBuilder.toStreamID(e);this.invalidatePermissionCaches(n),await this.connectToContract();for(const e of r)for(const r of e.permissions){const i=MJ(r),s=t(n,_J(e)?void 0:e.userId,i);await mD(s)}}async setPermissions(...t){const r=[],n=[],i=[];for(const s of t){bQ(s.assignments);const t=await this.streamIdBuilder.toStreamID(s.streamId);this.invalidatePermissionCaches(t),r.push(t),n.push(s.assignments.map((e=>_J(e)?TJ:e.userId))),i.push(s.assignments.map((t=>{return{canEdit:(r=t.permissions).includes(e.StreamPermission.EDIT),canDelete:r.includes(e.StreamPermission.DELETE),publishExpiration:r.includes(e.StreamPermission.PUBLISH)?PI:0n,subscribeExpiration:r.includes(e.StreamPermission.SUBSCRIBE)?PI:0n,canGrant:r.includes(e.StreamPermission.GRANT)};var r})))}await this.connectToContract();const s=await nD(this.rpcProviderSource,this.config),o=this.streamRegistryContract.setMultipleStreamPermissionsForUserIds(r,n,i,s);await mD(o)}async isStreamPublisherOrSubscriber_nonCached(e,t,r){try{return await this.hasPermission({streamId:e,userId:t,permission:r,allowPublic:!0})}catch(t){return wQ(t,e,"StreamPermission")}}getStreamMetadata(e){return this.metadataCache.get(e)}isStreamPublisher(e,t){return this.publisherCache.get([e,t])}isStreamSubscriber(e,t){return this.subscriberCache.get([e,t])}hasPublicSubscribePermission(e){return this.publicSubscribePermissionCache.get(e)}populateMetadataCache(e,t){this.metadataCache.set(e,t)}invalidatePermissionCaches(e){this.logger.trace("Clear permission caches for stream",{streamId:e}),vQ(this.publisherCache,e),vQ(this.subscriberCache,e)}};var AQ,SQ,kQ,RQ,CQ,IQ;EQ=pQ=gQ([q(d.ContainerScoped),yQ(5,U(cA)),yQ(6,U(kA)),mQ("design:paramtypes",[SD,e.RpcProviderSource,cQ,lE,RJ,Object,RA,sD,uD])],EQ);var PQ=function(){if(IQ)return CQ;IQ=1;var e=function(){if(SQ)return AQ;SQ=1;var e=Le();return AQ=function(t,r,n){for(var i=-1,s=t.length;++i<s;){var o=t[i],a=r(o);if(null!=a&&(void 0===c?a==a&&!e(a):n(a,c)))var c=a,u=o}return u},AQ}(),t=RQ?kQ:(RQ=1,kQ=function(e,t){return e<t}),r=Yc();return CQ=function(n){return n&&n.length?e(n,r,t):void 0},CQ}(),TQ=n(PQ),_Q=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},NQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},MQ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const xQ=Symbol("GET_ALL_STORAGE_NODES");let OQ=class{streamStorageRegistryContract;streamStorageRegistryContractReadonly;streamIdBuilder;contractFactory;rpcProviderSource;theGraphClient;config;identity;logger;storageNodesCache;constructor(e,t,r,n,i,s,o,a,c){this.streamIdBuilder=e,this.contractFactory=t,this.rpcProviderSource=r,this.theGraphClient=i,this.config=s,this.identity=o,this.logger=c.createLogger("StreamStorageRegistry"),this.streamStorageRegistryContractReadonly=this.contractFactory.createReadContract(nb(this.config.contracts.streamStorageRegistryChainAddress),SA.StreamStorageRegistryABI,r.getProvider(),"streamStorageRegistry"),this.initStreamAssignmentEventListeners(a,n,c),this.storageNodesCache=DJ({valueFactory:e=>this.getStorageNodes_nonCached(e),...s.cache})}initStreamAssignmentEventListeners(e,t,r){const n=([e,t],r)=>({streamId:bE(e),nodeAddress:nb(t),blockNumber:r}),i=nb(this.config.contracts.streamStorageRegistryChainAddress),s=new uN(SA.StreamStorageRegistryABI);wD({sourceDefinition:{contractInterfaceFragment:s.getEvent("Added"),contractAddress:i},sourceEmitter:t,targetName:"streamAddedToStorageNode",targetEmitter:e,transformation:n,loggerFactory:r}),wD({sourceDefinition:{contractInterfaceFragment:s.getEvent("Removed"),contractAddress:i},sourceEmitter:t,targetName:"streamRemovedFromStorageNode",targetEmitter:e,transformation:n,loggerFactory:r})}async connectToContract(){if(!this.streamStorageRegistryContract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.streamStorageRegistryContract=this.contractFactory.createWriteContract(nb(this.config.contracts.streamStorageRegistryChainAddress),SA.StreamStorageRegistryABI,e,"streamStorageRegistry")}}async addStreamToStorageNode(e,t){const r=await this.streamIdBuilder.toStreamID(e);this.logger.debug("Add stream to storage node",{streamId:r,nodeAddress:t}),await this.connectToContract();const n=await nD(this.rpcProviderSource,this.config);await mD(this.streamStorageRegistryContract.addStorageNode(r,t,n)),this.storageNodesCache.invalidate((e=>e===r))}async removeStreamFromStorageNode(e,t){const r=await this.streamIdBuilder.toStreamID(e);this.logger.debug("Remove stream from storage node",{streamId:r,nodeAddress:t}),await this.connectToContract();const n=await nD(this.rpcProviderSource,this.config);await mD(this.streamStorageRegistryContract.removeStorageNode(r,t,n)),this.storageNodesCache.invalidate((e=>e===r))}async isStoredStream(e,t){const r=await this.streamIdBuilder.toStreamID(e);return this.logger.debug("Check if stream is stored in storage node",{streamId:r,nodeAddress:t}),await this.streamStorageRegistryContractReadonly.isStorageNodeOf(r,t)}async getStoredStreams(e){this.logger.debug("Get stored streams of storage node",{nodeAddress:e});const t=[],r=(await cE(this.theGraphClient.queryEntities(((t,r)=>({query:`{\n node (id: "${e}") {\n id\n metadata\n lastSeen\n storedStreams (first: ${r} orderBy: "id" where: { id_gt: "${t}"}) {\n id,\n metadata\n }\n }\n _meta {\n block {\n number\n }\n }\n }`})),(e=>(t.push(e._meta.block.number),null!==e.node?e.node.storedStreams:[]))))).map((e=>({id:bE(e.id),metadata:CJ(e.metadata)})));return{streams:r,blockNumber:TQ(t)}}async getStorageNodes(e){const t=void 0!==e?await this.streamIdBuilder.toStreamID(e):xQ;return this.storageNodesCache.get(t)}async getStorageNodes_nonCached(e){let t;if(e!==xQ){const r=e;this.logger.debug("Get storage nodes of stream",{streamId:r}),t=await cE(this.theGraphClient.queryEntities(((e,t)=>({query:`{\n stream (id: "${r}") {\n id\n metadata\n storageNodes (first: ${t} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n metadata\n lastSeen\n }\n }\n }`})),(e=>null!==e.stream?e.stream.storageNodes:[])))}else this.logger.debug("Get all storage nodes"),t=await cE(this.theGraphClient.queryEntities(((e,t)=>({query:`{\n nodes (first: ${t} orderBy: "id" where: { id_gt: "${e}"}) {\n id\n metadata\n lastSeen\n }\n }`}))));return t.map((e=>nb(e.id)))}};OQ=_Q([q(d.ContainerScoped),MQ(5,U(cA)),MQ(6,U(kA)),NQ("design:paramtypes",[RJ,SD,e.RpcProviderSource,cQ,lE,Object,RA,sD,uD])],OQ);
63
69
  /*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
64
- const cQ=256,uQ=3329,{mod:lQ,nttZetas:hQ,NTT:dQ,bitsCoder:fQ}=Gp({N:cQ,Q:uQ,F:3303,ROOT_OF_UNITY:17,newPoly:e=>new Uint16Array(e),brvBits:7,isKyber:!0}),pQ=e=>fQ(e,(e=>{if(e>=12)return{encode:e=>e,decode:e=>e};const t=2**(e-1);return{encode:t=>((t<<e)+uQ/2)/uQ,decode:r=>r*uQ+t>>>e}})(e));function gQ(e,t){for(let r=0;r<cQ;r++)e[r]=lQ(e[r]+t[r])}function mQ(e,t){for(let o=0;o<128;o++){let a=hQ[64+(o>>1)];1&o&&(a=-a);const{c0:c,c1:u}=(r=e[2*o+0],n=e[2*o+1],i=t[2*o+0],s=t[2*o+1],{c0:lQ(n*s*a+r*i),c1:lQ(r*s+n*i)});e[2*o+0]=c,e[2*o+1]=u}var r,n,i,s;return e}function yQ(e){const t=new Uint16Array(cQ);for(let r=0;r<cQ;){const n=e();if(n.length%3)throw new Error("SampleNTT: unaligned block");for(let e=0;r<cQ&&e+3<=n.length;e+=3){const i=4095&(n[e+0]|n[e+1]<<8),s=4095&(n[e+1]>>4|n[e+2]<<4);i<uQ&&(t[r++]=i),r<cQ&&s<uQ&&(t[r++]=s)}}return t}function bQ(e,t,r,n){const i=e(n*cQ/4,t,r),s=new Uint16Array(cQ),o=Ci(i);let a=0;for(let e=0,t=0,r=0,i=0;e<o.length;e++){let c=o[e];for(let e=0;e<32;e++)r+=1&c,c>>=1,a+=1,a===n?(i=r,r=0):a===2*n&&(s[t++]=lQ(i-r),r=0,a=0)}if(a)throw new Error(`sampleCBD: leftover bits: ${a}`);return s}const wQ=e=>{const{K:t,PRF:r,XOF:n,HASH512:i,ETA1:s,ETA2:o,du:a,dv:c}=e,u=pQ(1),l=pQ(c),h=pQ(a),d=ao(co(pQ(12),t),32),f=co(pQ(12),t),p=ao(co(h,t),l),g=ao(32,32);return{secretCoder:f,secretKeyLen:f.bytesLen,publicKeyLen:d.bytesLen,cipherTextLen:p.bytesLen,keygen:e=>{io(e,32);const o=new Uint8Array(33);o.set(e),o[32]=t;const a=i(o),[c,u]=g.decode(a),l=[],h=[];for(let e=0;e<t;e++)l.push(dQ.encode(bQ(r,u,e,s)));const p=n(c);for(let e=0;e<t;e++){const n=dQ.encode(bQ(r,u,t+e,s));for(let r=0;r<t;r++){gQ(n,mQ(yQ(p.get(r,e)),l[r]))}h.push(n)}p.clean();const m={publicKey:d.encode([h,c]),secretKey:f.encode(l)};return uo(c,u,l,h,o,a),m},encrypt:(e,i,a)=>{const[c,l]=d.decode(e),h=[];for(let e=0;e<t;e++)h.push(dQ.encode(bQ(r,a,e,s)));const f=n(l),g=new Uint16Array(cQ),m=[];for(let e=0;e<t;e++){const n=bQ(r,a,t+e,o),i=new Uint16Array(cQ);for(let r=0;r<t;r++){gQ(i,mQ(yQ(f.get(e,r)),h[r]))}gQ(n,dQ.decode(i)),m.push(n),gQ(g,mQ(c[e],h[e])),i.fill(0)}f.clean();const y=bQ(r,a,2*t,o);gQ(y,dQ.decode(g));const b=u.decode(i);return gQ(b,y),uo(c,h,g,y),p.encode([m,b])},decrypt:(e,r)=>{const[n,i]=p.decode(e),s=f.decode(r),o=new Uint16Array(cQ);for(let e=0;e<t;e++)gQ(o,mQ(s[e],dQ.encode(n[e])));return function(e,t){for(let r=0;r<cQ;r++)e[r]=lQ(e[r]-t[r])}(i,dQ.decode(o)),uo(o,s,n),u.encode(i)}}};function vQ(e){const t=wQ(e),{HASH256:r,HASH512:n,KDF:i}=e,{secretCoder:s,cipherTextLen:o}=t,a=t.publicKeyLen,c=ao(t.secretKeyLen,t.publicKeyLen,32,32),u=c.bytesLen;return{publicKeyLen:a,msgLen:32,keygen:(e=so(64))=>{io(e,64);const{publicKey:n,secretKey:i}=t.keygen(e.subarray(0,32)),s=r(n),o=c.encode([i,n,s,e.subarray(32)]);return uo(i,s),{publicKey:n,secretKey:o}},encapsulate:(i,o=so(32))=>{io(i,a),io(o,32);const c=i.subarray(0,384*e.K),u=s.encode(s.decode(c.slice()));if(!oo(u,c))throw uo(u),new Error("ML-KEM.encapsulate: wrong publicKey modulus");uo(u);const l=n.create().update(o).update(r(i)).digest(),h=t.encrypt(i,o,l.subarray(32,64));return l.subarray(32).fill(0),{cipherText:h,sharedSecret:l.subarray(0,32)}},decapsulate:(e,r)=>{io(r,u),io(e,o);const[s,a,l,h]=c.decode(r),d=t.decrypt(e,s),f=n.create().update(d).update(l).digest(),p=f.subarray(0,32),g=t.encrypt(a,d,f.subarray(32,64)),m=oo(e,g),y=i.create({dkLen:32}).update(h).update(e).digest();return uo(d,g,m?y:p),m?p:y}}}const EQ={HASH256:Ys,HASH512:eo,KDF:no,XOF:Hp,PRF:function(e,t,r){return no.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}},AQ=vQ({...EQ,...{N:cQ,Q:uQ,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}}),SQ=Buffer.from("streamr-key-exchange"),kQ=1568;class RQ{static async encryptForPublicKey(e,t,r){if(r===rH.ML_KEM)return this.encryptWithMLKEMPublicKey(e,t);if(r===rH.RSA)return this.encryptWithRSAPublicKey(e,t);throw new Error(`Unexpected encryption type: ${r}`)}static async decryptWithPrivateKey(e,t,r){if(r===rH.ML_KEM)return this.decryptWithMLKEMPrivateKey(e,t);if(r===rH.RSA)return this.decryptWithRSAPrivateKey(e,t);throw new Error(`Unexpected encryption type: ${r}`)}static toRSAPublicKeyString(e){const t=fw(e);if(!t.startsWith("-----BEGIN PUBLIC KEY-----")||!t.endsWith("-----END PUBLIC KEY-----\n"))throw new Error('"publicKey" must be an RSA public key (SPKI) in PEM format, encoded in UTF-8');return t}static toRSAPrivateKeyString(e){const t=fw(e);if(!t.startsWith("-----BEGIN PRIVATE KEY-----")||!t.endsWith("-----END PRIVATE KEY-----\n"))throw new Error('"privateKey" must be a PKCS#8 RSA private key in PEM format, encoded in UTF-8');return t}static encryptWithRSAPublicKey(e,t){const r=function(e,t){return Pv.publicEncrypt(e,t)}(this.toRSAPublicKeyString(t),e);return r}static decryptWithRSAPrivateKey(e,t){return function(e,t){return Pv.privateDecrypt(e,t)}(this.toRSAPrivateKeyString(t),e)}static async deriveAESWrapperKey(e,t){const r=Tv(),n=await r.importKey("raw",e,{name:"HKDF"},!1,["deriveKey"]),i=await r.deriveKey({name:"HKDF",hash:"SHA-512",salt:t,info:SQ},n,{name:"AES-CTR",length:256},!0,["encrypt","decrypt"]),s=await r.exportKey("raw",i);return new Uint8Array(s)}static async encryptWithMLKEMPublicKey(e,t){const{cipherText:r,sharedSecret:n}=AQ.encapsulate(t);if(r.length!==kQ)throw new Error(`Expected KEM cipher to be 1568, but it was ${r.length} bytes`);const i=so(64),s=await this.deriveAESWrapperKey(n,i),o=this.encryptWithAES(e,Buffer.from(s));return Buffer.concat([r,i,o])}static async decryptWithMLKEMPrivateKey(e,t){let r=0;const n=e.slice(0,kQ);r+=kQ;const i=e.slice(r,r+64);r+=64;const s=e.slice(r),o=AQ.decapsulate(n,t),a=await this.deriveAESWrapperKey(o,i);return this.decryptWithAES(s,Buffer.from(a))}static encryptWithAES(e,t){const r=so(16),n=function(e,t,r){const n=e.toLowerCase();if(dw[n])return hw.createCipheriv(n,t,r);throw new TypeError(`Invalid suite type. In browser only AES is supported but got ${e}.`)}("aes-256-ctr",t,r);return Buffer.concat([r,n.update(e),n.final()])}static decryptWithAES(e,t){const r=function(e,t,r){const n=e.toLowerCase();if(dw[n])return hw.createDecipheriv(n,t,r);throw new TypeError(`Invalid suite type. In browser only AES is supported but got ${e}.`)}("aes-256-ctr",t,e.slice(0,16));return Buffer.concat([r.update(e.slice(16)),r.final()])}static decryptStreamMessage(e,t){let r,n;try{r=this.decryptWithAES(e.content,t.data)}catch{throw new uA("AES decryption failed","DECRYPT_ERROR",e)}if(e.newGroupKey)try{n=t.decryptNextGroupKey(e.newGroupKey)}catch{throw new uA("Could not decrypt new encryption key","DECRYPT_ERROR",e)}return[r,n]}}class CQ extends Error{groupKey;constructor(e,t){super(e),this.groupKey=t}}class IQ{id;data;constructor(e,t){if(this.id=e,!e)throw new CQ(`groupKeyId must not be falsey ${e}`);if(!t)throw new CQ(`groupKeyBufferOrHexString must not be falsey ${t}`);this.data=t,IQ.validate(this)}static validate(e){if(!e)throw new CQ(`value must be a ${this.name}: ${e}`,e);if(!(e instanceof this))throw new CQ(`value must be a ${this.name}: ${e}`,e);if(!e.id||"string"!=typeof e.id)throw new CQ(`${this.name} id must be a string: ${e}`,e);if(e.id.includes("---BEGIN"))throw new CQ(`${this.name} public/private key is not a valid group key id: ${e}`,e);if(!e.data||!Buffer.isBuffer(e.data))throw new CQ(`${this.name} data must be a Buffer: ${e}`,e);if(32!==e.data.length)throw new CQ("Group key must have a size of 256 bits, not "+8*e.data.length,e)}static generate(e=mW("GroupKey")){const t=so(32);return new IQ(e,Buffer.from(t))}encryptNextGroupKey(e){return{id:e.id,data:RQ.encryptWithAES(e.data,this.data)}}decryptNextGroupKey(e){return new IQ(e.id,RQ.decryptWithAES(e.data,this.data))}}const PQ=(e,t)=>t.some((t=>e instanceof t));let TQ,_Q;const NQ=new WeakMap,MQ=new WeakMap,xQ=new WeakMap;let OQ={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return NQ.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return FQ(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function DQ(e){OQ=e(OQ)}function BQ(e){return(_Q||(_Q=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(UQ(this),t),FQ(this.request)}:function(...t){return FQ(e.apply(UQ(this),t))}}function LQ(e){return"function"==typeof e?BQ(e):(e instanceof IDBTransaction&&function(e){if(NQ.has(e))return;const t=new Promise(((t,r)=>{const n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),n()},s=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)}));NQ.set(e,t)}(e),PQ(e,TQ||(TQ=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,OQ):e)}function FQ(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,r)=>{const n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t(FQ(e.result)),n()},s=()=>{r(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",s)}));return xQ.set(t,e),t}(e);if(MQ.has(e))return MQ.get(e);const t=LQ(e);return t!==e&&(MQ.set(e,t),xQ.set(t,e)),t}const UQ=e=>xQ.get(e);const jQ=["get","getKey","getAll","getAllKeys","count"],qQ=["put","add","delete","clear"],zQ=new Map;function KQ(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(zQ.get(t))return zQ.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,i=qQ.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!i&&!jQ.includes(r))return;const s=async function(e,...t){const s=this.transaction(e,i?"readwrite":"readonly");let o=s.store;return n&&(o=o.index(t.shift())),(await Promise.all([o[r](...t),i&&s.done]))[0]};return zQ.set(t,s),s}DQ((e=>({...e,get:(t,r,n)=>KQ(t,r)||e.get(t,r,n),has:(t,r)=>!!KQ(t,r)||e.has(t,r)})));const GQ=["continue","continuePrimaryKey","advance"],VQ={},HQ=new WeakMap,$Q=new WeakMap,WQ={get(e,t){if(!GQ.includes(t))return e[t];let r=VQ[t];return r||(r=VQ[t]=function(...e){HQ.set(this,$Q.get(this)[t](...e))}),r}};async function*JQ(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,WQ);for($Q.set(r,t),xQ.set(r,UQ(t));t;)yield r,t=await(HQ.get(r)||t.continue()),HQ.delete(r)}function QQ(e,t){return t===Symbol.asyncIterator&&PQ(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&PQ(e,[IDBIndex,IDBObjectStore])}DQ((e=>({...e,get:(t,r,n)=>QQ(t,r)?JQ:e.get(t,r,n),has:(t,r)=>QQ(t,r)||e.has(t,r)})));class ZQ{db;static async createInstance(e){const t=await function(e,t,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){const o=indexedDB.open(e,t),a=FQ(o);return n&&o.addEventListener("upgradeneeded",(e=>{n(FQ(o.result),e.oldVersion,e.newVersion,FQ(o.transaction),e)})),r&&o.addEventListener("blocked",(e=>r(e.oldVersion,e.newVersion,e))),a.then((e=>{s&&e.addEventListener("close",(()=>s())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}(`streamr-sdk::${e.ownerId}`,1,{upgrade(t){e.namespaces.forEach((e=>t.createObjectStore(e)))}});return new ZQ(t)}constructor(e){this.db=e}async exists(){throw new Error("Method not implemented in browser Persistence.")}async get(e,t){return this.db.get(t,e)}async set(e,t,r){await this.db.put(r,t,e)}async close(){}}var YQ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},XQ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},eZ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const tZ={ENCRYPTION_KEYS:"EncryptionKeys",LATEST_ENCRYPTION_KEY_IDS:"LatestEncryptionKeyIds"};let rZ=class{persistence;identity;loggerFactory;constructor(e,t,r){this.identity=e,this.loggerFactory=r,t.onDestroy.listen((()=>{if(void 0!==this.persistence)return this.persistence.close()}))}async ensureInitialized(){this.persistence??=await ZQ.createInstance({loggerFactory:this.loggerFactory,ownerId:await this.identity.getUserId(),namespaces:Object.values(tZ),migrationsUrl:new URL("./encryption/migrations","undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:t&&"SCRIPT"===t.tagName.toUpperCase()&&t.src||new URL("exports-umd.min.js",document.baseURI).href)})}async getPersistence(e){return await this.ensureInitialized(),{get:t=>this.persistence.get(t,e),set:(t,r)=>this.persistence.set(t,r,e)}}};rZ=YQ([q(d.ContainerScoped),eZ(0,U(kA)),XQ("design:paramtypes",[RA,UW,uD])],rZ);var nZ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},iZ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};function sZ(e,t){return`${t}::${e}`}function oZ(e,t){return`${e}::${t}`}let aZ=class{persistenceManager;eventEmitter;logger;constructor(e,t,r){this.persistenceManager=e,this.eventEmitter=t,this.logger=r.createLogger("LocalGroupKeyStore")}async get(e,t){const r=await this.persistenceManager.getPersistence(tZ.ENCRYPTION_KEYS),n=await r.get(sZ(e,t));return void 0!==n?new IQ(e,Buffer.from(n,"hex")):void 0}async set(e,t,r){const n=await this.persistenceManager.getPersistence(tZ.ENCRYPTION_KEYS);await n.set(sZ(e,t),Buffer.from(r).toString("hex")),this.logger.debug("Set key",{keyId:e,publisherId:t}),this.eventEmitter.emit("encryptionKeyStoredToLocalStore",e)}async setLatestEncryptionKeyId(e,t,r){const n=await this.persistenceManager.getPersistence(tZ.LATEST_ENCRYPTION_KEY_IDS);this.logger.debug("Set latest encryptionKeyId",{keyId:e,publisherId:t,streamId:r}),await n.set(oZ(t,r),e)}async getLatestEncryptionKeyId(e,t){const r=await this.persistenceManager.getPersistence(tZ.LATEST_ENCRYPTION_KEY_IDS);return await r.get(oZ(e,t))}};var cZ,uZ,lZ,hZ,dZ,fZ,pZ,gZ,mZ,yZ,bZ,wZ,vZ,EZ,AZ,SZ,kZ,RZ,CZ,IZ,PZ,TZ,_Z,NZ,MZ,xZ,OZ,DZ,BZ,LZ,FZ,UZ,jZ,qZ,zZ,KZ,GZ,VZ,HZ,$Z,WZ,JZ,QZ,ZZ,YZ,XZ;function eY(){if(yZ)return mZ;yZ=1;var e=$B(),t=Nh(),r=QB(),n=JB(),i=Object.getOwnPropertySymbols?function(n){for(var i=[];n;)e(i,r(n)),n=t(n);return i}:n;return mZ=i}function tY(){if(EZ)return vZ;EZ=1;var e=WB(),t=eY(),r=Id();return vZ=function(n){return e(n,r,t)},vZ}function rY(){if(NZ)return _Z;NZ=1;var e=Ih(),t=function(){if(RZ)return kZ;RZ=1;var e=Ih();return kZ=function(t,r){var n=r?e(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)},kZ}(),r=function(){if(IZ)return CZ;IZ=1;var e=/\w*$/;return CZ=function(t){var r=new t.constructor(t.source,e.exec(t));return r.lastIndex=t.lastIndex,r}}(),n=function(){if(TZ)return PZ;TZ=1;var e=Oe(),t=e?e.prototype:void 0,r=t?t.valueOf:void 0;return PZ=function(e){return r?Object(r.call(e)):{}}}(),i=Ph();return _Z=function(s,o,a){var c=s.constructor;switch(o){case"[object ArrayBuffer]":return e(s);case"[object Boolean]":case"[object Date]":return new c(+s);case"[object DataView]":return t(s,a);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return i(s,a);case"[object Map]":case"[object Set]":return new c;case"[object Number]":case"[object String]":return new c(s);case"[object RegExp]":return r(s);case"[object Symbol]":return n(s)}},_Z}function nY(){if(DZ)return OZ;DZ=1;var e=function(){if(xZ)return MZ;xZ=1;var e=XB(),t=Be();return MZ=function(r){return t(r)&&"[object Map]"==e(r)}}(),t=Qc(),r=Ed(),n=r&&r.isMap,i=n?t(n):e;return OZ=i}function iY(){if(UZ)return FZ;UZ=1;var e=function(){if(LZ)return BZ;LZ=1;var e=XB(),t=Be();return BZ=function(r){return t(r)&&"[object Set]"==e(r)}}(),t=Qc(),r=Ed(),n=r&&r.isSet,i=n?t(n):e;return FZ=i}function sY(){if(qZ)return jZ;qZ=1;var e=Yl(),t=(uZ||(uZ=1,cZ=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e}),cZ),r=Rl(),n=function(){if(hZ)return lZ;hZ=1;var e=kd(),t=rA();return lZ=function(r,n){return r&&e(n,t(n),r)},lZ}(),i=function(){if(fZ)return dZ;fZ=1;var e=kd(),t=Id();return dZ=function(r,n){return r&&e(n,t(n),r)},dZ}(),s=Rh(),o=Th(),a=function(){if(gZ)return pZ;gZ=1;var e=kd(),t=QB();return pZ=function(r,n){return e(r,t(r),n)},pZ}(),c=function(){if(wZ)return bZ;wZ=1;var e=kd(),t=eY();return bZ=function(r,n){return e(r,t(r),n)},bZ}(),u=ZB(),l=tY(),h=XB(),d=function(){if(SZ)return AZ;SZ=1;var e=Object.prototype.hasOwnProperty;return AZ=function(t){var r=t.length,n=new t.constructor(r);return r&&"string"==typeof t[0]&&e.call(t,"index")&&(n.index=t.index,n.input=t.input),n},AZ}(),f=rY(),p=xh(),g=qu(),m=Kh(),y=nY(),b=Ne(),w=iY(),v=rA(),E=Id(),A="[object Arguments]",S="[object Function]",k="[object Object]",R={};return R[A]=R["[object Array]"]=R["[object ArrayBuffer]"]=R["[object DataView]"]=R["[object Boolean]"]=R["[object Date]"]=R["[object Float32Array]"]=R["[object Float64Array]"]=R["[object Int8Array]"]=R["[object Int16Array]"]=R["[object Int32Array]"]=R["[object Map]"]=R["[object Number]"]=R[k]=R["[object RegExp]"]=R["[object Set]"]=R["[object String]"]=R["[object Symbol]"]=R["[object Uint8Array]"]=R["[object Uint8ClampedArray]"]=R["[object Uint16Array]"]=R["[object Uint32Array]"]=!0,R["[object Error]"]=R[S]=R["[object WeakMap]"]=!1,jZ=function C(I,P,T,_,N,M){var x,O=1&P,D=2&P,B=4&P;if(T&&(x=N?T(I,_,N,M):T(I)),void 0!==x)return x;if(!b(I))return I;var L=g(I);if(L){if(x=d(I),!O)return o(I,x)}else{var F=h(I),U=F==S||"[object GeneratorFunction]"==F;if(m(I))return s(I,O);if(F==k||F==A||U&&!N){if(x=D||U?{}:p(I),!O)return D?c(I,i(x,I)):a(I,n(x,I))}else{if(!R[F])return N?I:{};x=f(I,F,O)}}M||(M=new e);var j=M.get(I);if(j)return j;M.set(I,x),w(I)?I.forEach((function(e){x.add(C(e,P,T,e,I,M))})):y(I)&&I.forEach((function(e,t){x.set(t,C(e,P,T,t,I,M))}));var q=L?void 0:(B?D?l:u:D?E:v)(I);return t(q||I,(function(e,t){q&&(e=I[t=e]),r(x,t,C(e,P,T,t,I,M))})),x},jZ}function oY(){if($Z)return HZ;$Z=1;var e=$B(),t=function(){if(VZ)return GZ;VZ=1;var e=Oe(),t=Oh(),r=qu(),n=e?e.isConcatSpreadable:void 0;return GZ=function(e){return r(e)||t(e)||!!(n&&e&&e[n])}}();return HZ=function r(n,i,s,o,a){var c=-1,u=n.length;for(s||(s=t),a||(a=[]);++c<u;){var l=n[c];i>0&&s(l)?i>1?r(l,i-1,s,o,a):e(a,l):o||(a[a.length]=l)}return a},HZ}function aY(){if(ZZ)return QZ;ZZ=1;var e=function(){if(JZ)return WZ;JZ=1;var e=oY();return WZ=function(t){return null!=t&&t.length?e(t,1):[]},WZ}(),t=Xc(),r=ru();return QZ=function(n){return r(t(n,void 0,e),n+"")}}aZ=nZ([q(d.ContainerScoped),iZ("design:paramtypes",[rZ,sD,uD])],aZ);var cY=function(){if(XZ)return YZ;XZ=1;var e=Jc(),t=sY(),r=bJ(),n=Pl(),i=kd(),s=function(){if(KZ)return zZ;KZ=1;var e=Gh();return zZ=function(t){return e(t)?void 0:t}}(),o=aY(),a=tY(),c=o((function(o,c){var u={};if(null==o)return u;var l=!1;c=e(c,(function(e){return e=n(e,o),l||(l=e.length>1),e})),i(o,a(o),u),l&&(u=t(u,7,s));for(var h=c.length;h--;)r(u,c[h]);return u}));return YZ=c}(),uY=n(cY),lY=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},hY=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let dY=class{theGraphClient;logger;constructor(e,t){this.theGraphClient=e,this.logger=t.createLogger("OperatorRegistry")}async findRandomNetworkEntrypoints(e,t,r){const n=this.theGraphClient.queryEntities((()=>({query:`{\n operators(\n orderBy: latestHeartbeatTimestamp\n orderDirection: desc\n first: ${t}\n where: {\n latestHeartbeatMetadata_contains: "\\"tls\\":true", \n latestHeartbeatTimestamp_gt: "${Math.floor(Date.now()/1e3)-60*r*60}"\n }\n ) {\n id\n latestHeartbeatMetadata\n }\n }`}))),i=[];for await(const e of n)i.push(JSON.parse(e.latestHeartbeatMetadata));const s=PU(i).slice(0,e);return this.logger.debug(`Found ${i.length} network entrypoints, picked ${s.length}`,{picked:s}),s}async findOperatorsOnStream(e,t,r){const n={query:`{\n stream(id: "${e}") {\n sponsorships(where: { isRunning: true }) {\n stakes(first: ${t}, orderBy: updateTimestamp, orderDirection: desc) {\n operator (\n where: {\n latestHeartbeatMetadata_contains: "\\"tls\\":true", \n latestHeartbeatTimestamp_gt: "${Math.floor(Date.now()/1e3)-60*r*60}"\n }\n ) {\n id\n latestHeartbeatMetadata\n }\n }\n }\n }\n }`},i=(await this.theGraphClient.queryEntity(n)).stream.sponsorships.flatMap((e=>e.stakes.map((e=>({operatorId:nb(e.operator.id),peerDescriptor:JSON.parse(e.operator.latestHeartbeatMetadata)})))));return i}};dY=lY([q(d.ContainerScoped),hY("design:paramtypes",[lE,uD])],dY);const fY=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};const pY=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var gY;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(gY||(gY={}));const mY=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>pY},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",gY]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>fY}])}};const yY=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var bY,wY,vY,EY,AY,SY;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(bY||(bY={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(wY||(wY={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}(vY||(vY={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(EY||(EY={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(AY||(AY={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(SY||(SY={}));const kY=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>pY},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>yY},{no:5,name:"ttl",kind:"scalar",T:13}])}};const RY=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const CY=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>pY}])}};const IY=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>UY}])}};const PY=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>TY}])}};const TY=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>pY},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>yY},{no:5,name:"storedAt",kind:"message",T:()=>yY},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const _Y=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const NY=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>UY},{no:2,name:"requestId",kind:"scalar",T:9}])}};const MY=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const xY=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>UY},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>UY},{no:3,name:"requestId",kind:"scalar",T:9}])}};const OY=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",bY]}])}};const DY=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>UY},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>TY},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>UY}])}};const BY=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const LY=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const FY=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const UY=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",wY]},{no:3,name:"udp",kind:"message",T:()=>jY},{no:4,name:"tcp",kind:"message",T:()=>jY},{no:5,name:"websocket",kind:"message",T:()=>jY},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const jY=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const qY=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>UY},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>$Y},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>UY},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>UY},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const zY=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",EY]}])}};const KY=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const GY=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>jY},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const VY=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>UY},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>UY},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const HY=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>UY},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",AY]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const $Y=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>UY},{no:3,name:"targetDescriptor",kind:"message",T:()=>UY},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>mY},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>KY},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>GY},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>VY},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>HY},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>OY}])}};const WY=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const JY=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const QY=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const ZY=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const YY=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const XY=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const eX=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const tX=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const rX=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",SY]}])}};const nX=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const iX=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const sX=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>TY}])}};const oX=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const aX=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>UY}])}};new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:_Y,O:NY},{name:"getClosestRingPeers",options:{},I:MY,O:xY},{name:"ping",options:{},I:BY,O:LY},{name:"leaveNotice",options:{},I:FY,O:fY}]),new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:qY,O:zY},{name:"forwardMessage",options:{},I:qY,O:zY}]),new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:qY,O:zY}]),new vF("dht.StoreRpc",[{name:"storeData",options:{},I:kY,O:RY},{name:"replicateData",options:{},I:PY,O:fY}]),new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:DY,O:fY}]),new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:WY,O:fY}]),new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:JY,O:fY},{name:"rtcOffer",options:{},I:QY,O:fY},{name:"rtcAnswer",options:{},I:ZY,O:fY},{name:"iceCandidate",options:{},I:YY,O:fY}]),new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:XY,O:tX},{name:"unlockRequest",options:{},I:eX,O:fY},{name:"gracefulDisconnect",options:{},I:rX,O:fY},{name:"setPrivate",options:{},I:nX,O:fY}]),new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:iX,O:sX},{name:"externalStoreData",options:{},I:CY,O:IY},{name:"externalFindClosestNodes",options:{},I:oX,O:aX}]);const cX=new class extends wF{constructor(){super("OperatorDiscoveryRequest",[{no:1,name:"streamPartId",kind:"scalar",T:9}])}};const uX=new class extends wF{constructor(){super("OperatorDiscoveryResponse",[{no:1,name:"operators",kind:"message",repeat:2,T:()=>UY}])}},lX=new vF("OperatorDiscovery",[{name:"discoverOperators",options:{},I:cX,O:uX}]);class hX{_transport;typeName=lX.typeName;methods=lX.methods;options=lX.options;constructor(e){this._transport=e}discoverOperators(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}var dX=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},fX=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},pX=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let gX=class{createNetworkNode(e){return(e=>new W$(new $$(e)))(e)}};gX=dX([q(d.ContainerScoped)],gX);const mX=new Bv("NetworkNodeFacade");let yX=class{cachedNode;startNodeCalled=!1;startNodeComplete=!1;messageListeners=[];networkNodeFactory;operatorRegistry;config;identity;eventEmitter;destroySignal;constructor(e,t,r,n,i){this.networkNodeFactory=e,this.operatorRegistry=t,this.config=r,this.identity=n,this.eventEmitter=new Sl,this.destroySignal=i,i.onDestroy.listen(this.destroy)}async getNetworkOptions(){const e=await this.getEntryPoints(),t=this.config.network.controlLayer.peerDescriptor?EW(this.config.network.controlLayer.peerDescriptor):void 0;return{layer0:{...this.config.network.controlLayer,entryPoints:e.map(EW),peerDescriptor:t,websocketPortRange:null!==this.config.network.controlLayer.websocketPortRange?this.config.network.controlLayer.websocketPortRange:void 0},networkNode:{...uY(this.config.network.node,"contentDeliveryBufferWhileConnecting"),bufferWhileConnecting:this.config.network.node.contentDeliveryBufferWhileConnecting},metricsContext:new $v}}destroy=_W((async()=>{const e=this.cachedNode;if(this.cachedNode=void 0,e&&this.startNodeCalled){if(!this.startNodeComplete){const e=this.startNodeTask();this.startNodeTask.reset(),await e}await e.stop()}this.startNodeTask.reset()}));startNodeTask=_W((async(e=!0)=>{this.startNodeCalled=!0;try{const t=await this.initNode();return this.destroySignal.isDestroyed()||await t.start(e),t.addMessageListener((e=>{if(this.messageListeners.length>0)try{const t=rW.toClientProtocol(e);for(const e of this.messageListeners)e(t)}catch(e){mX.trace("Could not translate message",{err:e})}})),this.destroySignal.isDestroyed()?await t.stop():this.eventEmitter.emit("start"),this.destroySignal.assertNotDestroyed(),t}finally{this.startNodeComplete=!0}}));async initNode(){if(this.destroySignal.assertNotDestroyed(),this.cachedNode)return this.cachedNode;const e=this.networkNodeFactory.createNetworkNode(await this.getNetworkOptions());return this.destroySignal.isDestroyed()||(this.cachedNode=e),e}startNode=this.startNodeTask;getNode(){return this.destroySignal.assertNotDestroyed(),this.startNodeTask()}async getNodeId(){return(await this.getNode()).getNodeId()}async join(e,t,r){const n=await this.getNode();await n.join(e,t,r)}async leave(e){const t=await this.getNode();await t.leave(e)}async broadcast(e,t){(await this.getNode()).broadcast(rW.toProtobuf(e),t)}addMessageListener(e){this.messageListeners.push(e)}removeMessageListener(e){ej(this.messageListeners,e)}async isProxiedStreamPart(e){return(await this.getNode()).isProxiedStreamPart(e)}async getMetricsContext(){return(await this.getNode()).getMetricsContext()}async getPeerDescriptor(){return(await this.getNode()).getPeerDescriptor()}async getDiagnosticInfo(){return(await this.getNode()).getDiagnosticInfo()}async getStreamParts(){return(await this.getNode()).getStreamParts()}async getNeighbors(e){return(await this.getNode()).getNeighbors(e)}async getOptions(){return(await this.getNode()).getOptions()}async inspect(e,t){this.isStarting()&&await this.startNodeTask(!1);const r=EW(e);return this.cachedNode.inspect(r,t)}async setProxies(e,t,r,n){this.isStarting()&&await this.startNodeTask(!1);const i=t.map(EW);await this.cachedNode.setProxies(e,i,await this.identity.getUserId(),r,n)}async setStreamPartEntryPoints(e,t){this.isStarting()&&await this.startNodeTask(!1);const r=t.map(EW);this.cachedNode.setStreamPartEntryPoints(e,r)}async discoverOperators(e,t){const r=await this.createExternalRpcClient(hX);return(await r.discoverOperators(cX.create({streamPartId:t}),{sourceDescriptor:await this.getPeerDescriptor(),targetDescriptor:EW(e)})).operators.map((e=>AW(e)))}async createExternalRpcClient(e){return this.isStarting()&&await this.startNodeTask(!1),this.cachedNode.createExternalRpcClient(e)}async registerOperator(e){(await this.getNode()).registerExternalNetworkRpcMethod(cX,uX,"discoverOperators",(async t=>{const r=AE.parse(t.streamPartId),n=e.getAssignedNodesForStreamPart(r);return uX.create({operators:n.map((e=>EW(e)))})}))}isStarting(){return!this.cachedNode||!this.startNodeComplete}once(e,t){this.eventEmitter.once(e,t)}async getEntryPoints(){const e=this.config.network.controlLayer.entryPointDiscovery,t=e?.enabled?await this.operatorRegistry.findRandomNetworkEntrypoints(e.maxEntryPoints,e.maxQueryResults,e.maxHeartbeatAgeHours):[];return[...this.config.network.controlLayer.entryPoints,...t]}};yX=dX([q(d.ContainerScoped),pX(2,U(cA)),pX(3,U(kA)),fX("design:paramtypes",[gX,dY,Object,RA,UW])],yX);const bX=()=>Wv(20),wX=t=>{const r=Buffer.concat([Buffer.from(`${t.messageId.streamId}${t.messageId.streamPartition}${t.messageId.timestamp}${t.messageId.sequenceNumber}${t.messageId.publisherId}${t.messageId.msgChainId}`),void 0!==t.prevMsgRef?Buffer.from(`${t.prevMsgRef.timestamp}${t.prevMsgRef.sequenceNumber}`):new Uint8Array(0)]);if(t.messageType===e.StreamMessageType.MESSAGE){const e=t.newGroupKey?Buffer.from(t.newGroupKey.id):void 0;return Buffer.concat([r,t.content,e??new Uint8Array(0),t.newGroupKey?.data??new Uint8Array(0)])}if(t.messageType===e.StreamMessageType.GROUP_KEY_REQUEST){const e=uH.fromBinary(t.content);return Buffer.concat([r,pw(e.requestId),e.recipientId,e.publicKey,Buffer.concat(e.groupKeyIds.map((e=>pw(e))))])}if(t.messageType===e.StreamMessageType.GROUP_KEY_RESPONSE){const e=lH.fromBinary(t.content);return Buffer.concat([r,pw(e.requestId),e.recipientId,Buffer.concat(e.groupKeys.map((e=>Buffer.concat([pw(e.id),e.data]))))])}throw new Error(`Assertion failed: unknown message type ${t.messageType}`)};var vX=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},EX=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},AX=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};e.MessageSigner=class{identity;constructor(e){this.identity=e}async createSignedMessage(e,t){const r=await this.identity.createMessageSignature(wX(e));return new tW({...e,signature:r,signatureType:t})}},e.MessageSigner=vX([q(d.ContainerScoped),AX(0,U(kA)),EX("design:paramtypes",[RA])],e.MessageSigner);var SX=["function isValidSignature(bytes32 hash, bytes signature) view returns (bytes4 magicValue)"],kX=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},RX=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const CX=new TE;let IX=class{contractsByAddress;publisherCache=new yE((()=>6e5));constructor(e,t){this.contractsByAddress=uJ({valueFactory:async r=>e.createReadContract(r,SX,t.getProvider(),"erc1271Contract")})}async isValidSignature(e,t,r){const n=function(e,t){return`${e}_${t}`}(e,kE(CX.recoverSignerUserId(r,t))),i=this.publisherCache.get(n);if(void 0!==i)return i;{const i=await this.contractsByAddress.get(e),s="0x1626ba7e"===await i.isValidSignature(CX.keccakHash(t),r);return this.publisherCache.set(n,s),s}}};IX=kX([q(d.ContainerScoped),RX("design:paramtypes",[SD,e.RpcProviderSource])],IX);const PX=t=>{const r=void 0!==t.prevMsgRef?`${t.prevMsgRef.timestamp}${t.prevMsgRef.sequenceNumber}`:"",n=void 0!==t.newGroupKey?(({id:e,data:t})=>JSON.stringify([e,gw(t)]))(t.newGroupKey):"",i=t.encryptionType===e.EncryptionType.NONE?fw(t.content):gw(t.content);return Buffer.from(`${t.messageId.streamId}${t.messageId.streamPartition}${t.messageId.timestamp}${t.messageId.sequenceNumber}${t.messageId.publisherId}${t.messageId.msgChainId}${r}${i}${n}`)};class TX extends RA{publicKeyString;publicKey;privateKey;constructor(e,t){super(),this.publicKey=e,this.privateKey=t,this.publicKeyString=kE(this.publicKey),this.assertValidKeyPair()}async getUserIdRaw(){return this.publicKey}async getUserId(){return this.publicKeyString}async getPrivateKey(){return this.privateKey}async getTransactionSigner(e){throw new Error("This key pair can not sign transactions!")}static getKeyPairFromConfig(e){const t=e.auth;if(!t.privateKey)throw new Error("A privateKey was expected in the config, but none is defined!");return t}}const _X=new TE;class NX extends TX{assertValidKeyPair(){_X.assertValidKeyPair(this.publicKey,this.privateKey)}getSignatureType(){return e.SignatureType.ECDSA_SECP256K1_EVM}async createMessageSignature(e){return _X.createSignature(e,this.privateKey)}async getTransactionSigner(e){const t=e.getProvider();return new GO(gw(this.privateKey),t)}static fromConfig(e){const t=e.auth.privateKey,r=e.auth.publicKey;return NX.fromPrivateKey(t,r)}static fromPrivateKey(e,t){return new NX(mw(t??new GO(e).address),mw(e))}static generate(){const e=_X.generateKeyPair();return new NX(e.publicKey,e.privateKey)}}class MX extends RA{provider;expectedChainId;signer;cachedUserIdString;cachedUserIdBytes;rateLimitedSigner;constructor(e,t){super(),this.provider=e,this.expectedChainId=t,this.signer=e.getSigner(),this.rateLimitedSigner=TW((async e=>{const t=await(await this.signer).signMessage(e);return await Qv(50),mw(t)}),1)}async getUserIdRaw(){return this.cachedUserIdBytes??=RE(await this.getUserId()),this.cachedUserIdBytes}async getUserId(){return this.cachedUserIdString??=kE(await(await this.signer).getAddress()),this.cachedUserIdString}getSignatureType(){return e.SignatureType.ECDSA_SECP256K1_EVM}async createMessageSignature(e){return this.rateLimitedSigner(e)}async getTransactionSigner(){if(void 0===this.expectedChainId)throw new Error("Streamr chainId not configuredin the StreamrClient options!");const e=(await this.provider.getNetwork()).chainId;if(e!==BigInt(this.expectedChainId))throw new Error(`Connect your wallet to the chain with chainId ${this.expectedChainId} (chainId of currently selected chain is ${e})`);return this.signer}static fromConfig(e){const t=e.auth?.ethereum,r=new Ex(t);return new MX(r,e.contracts.ethereumNetwork.chainId)}}const xX=PE.getInstance("ML_DSA_87");class OX extends TX{assertValidKeyPair(){xX.assertValidKeyPair(this.publicKey,this.privateKey)}getSignatureType(){return e.SignatureType.ML_DSA_87}async createMessageSignature(e){return xX.createSignature(e,this.privateKey)}static fromConfig(e){const t=TX.getKeyPairFromConfig(e);if(!t.publicKey)throw new Error("ML-DSA identity requires a publicKey to be given in the config!");return new OX(mw(t.publicKey),mw(t.privateKey))}static generate(){const e=xX.generateKeyPair();return new OX(e.publicKey,e.privateKey)}}const DX=new _E;class BX extends TX{cachedJWK;assertValidKeyPair(){DX.assertValidKeyPair(this.publicKey,this.privateKey)}getSignatureType(){return e.SignatureType.ECDSA_SECP256R1}async createMessageSignature(e){return this.cachedJWK??=DX.privateKeyToJWK(this.privateKey),DX.createSignature(e,this.cachedJWK)}static fromConfig(e){const t=TX.getKeyPairFromConfig(e),r=mw(t.privateKey),n=t.publicKey?mw(t.publicKey):DX.getPublicKeyFromPrivateKey(r);return new BX(n,r)}static generate(){const e=DX.generateKeyPair();return new BX(e.publicKey,e.privateKey)}}const LX=[{keyType:"ECDSA_SECP256K1_EVM",fromConfig:NX.fromConfig,signatureType:e.SignatureType.ECDSA_SECP256K1_EVM},{keyType:"ECDSA_SECP256R1",fromConfig:BX.fromConfig,signatureType:e.SignatureType.ECDSA_SECP256R1},{keyType:"ML_DSA_87",fromConfig:OX.fromConfig,signatureType:e.SignatureType.ML_DSA_87}],FX="ECDSA_SECP256K1_EVM";["ECDSA_SECP256K1_EVM","ECDSA_SECP256R1","ML_DSA_87"].forEach((e=>{if(!LX.find((t=>t.keyType===e)))throw new Error(`keyType missing from IDENTITIES: ${e}`)}));var UX=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},jX=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const qX=Object.fromEntries(LX.map((e=>[e.signatureType,PE.getInstance(e.keyType)]))),zX=PE.getInstance("ECDSA_SECP256K1_EVM");let KX=class{erc1271ContractFacade;constructor(e){this.erc1271ContractFacade=e}async assertSignatureIsValid(e){let t;try{t=await this.validate(e)}catch(t){throw new uA(`An error occurred during address recovery from signature: ${t}`,"INVALID_SIGNATURE",e)}if(!t)throw new uA("Signature validation failed","INVALID_SIGNATURE",e)}async validate(t){const r=qX[t.signatureType];if(r)return r.verifySignature(RE(t.getPublisherId()),wX(t),t.signature);if(t.signatureType===e.SignatureType.ECDSA_SECP256K1_LEGACY)return zX.verifySignature(RE(t.getPublisherId()),PX(t),t.signature);if(t.signatureType===e.SignatureType.ERC_1271)return this.erc1271ContractFacade.isValidSignature(nb(t.getPublisherId()),wX(t),t.signature);throw new Error(`Cannot validate message signature, unsupported signatureType: "${t.signatureType}"`)}};KX=UX([q(d.ContainerScoped),jX("design:paramtypes",[IX])],KX);const GX=async(e,t,r,n)=>{await VX(e,t,r,n).catch((t=>{throw t.streamMessage??=e,t}))},VX=async(t,r,n,i)=>{switch(await n.assertSignatureIsValid(t),t.messageType){case e.StreamMessageType.MESSAGE:return HX(t,r,i);case e.StreamMessageType.GROUP_KEY_REQUEST:return $X(t,kE(uH.fromBinary(t.content).recipientId),t.getPublisherId(),r,i);case e.StreamMessageType.GROUP_KEY_RESPONSE:return $X(t,t.getPublisherId(),kE(lH.fromBinary(t.content).recipientId),r,i);default:throw new uA(`Unknown message type: ${t.messageType}!`,"ASSERTION_FAILED",t)}},HX=async(e,t,r)=>{const n=e.getStreamId();if(r.validation.partitions){const r=await t.getStreamMetadata(n),i=eJ(r);if(e.getStreamPartition()<0||e.getStreamPartition()>=i)throw new uA(`Partition ${e.getStreamPartition()} is out of range (0..${i-1})`,"INVALID_PARTITION",e)}if(r.validation.permissions){const r=e.getPublisherId();if(!await t.isStreamPublisher(n,r))throw new uA(`${r} is not a publisher on stream ${n}`,"MISSING_PERMISSION",e)}},$X=async(e,t,r,n,i)=>{if(i.validation.permissions){const i=e.getStreamId();if(!await n.isStreamPublisher(i,t))throw new uA(`${t} is not a publisher on stream ${i}`,"MISSING_PERMISSION",e);if(!await n.isStreamSubscriber(i,r))throw new uA(`${r} is not a subscriber on stream ${i}`,"MISSING_PERMISSION",e)}};async function WX(e,{isPrivate:t=!1}={}){const r=t?"pkcs8":"spki",n=function(e){return String.fromCharCode.apply(null,[...new Uint8Array(e)])}(await Tv().exportKey(r,e)),i=t?"PRIVATE":"PUBLIC";return`-----BEGIN ${i} KEY-----\n${btoa(n)}\n-----END ${i} KEY-----\n`}class JX{privateKey;publicKey;constructor(e,t){this.privateKey=e,this.publicKey=t}getPublicKey(){return pw(this.publicKey)}getPrivateKey(){return pw(this.privateKey)}getEncryptionType(){return rH.RSA}static async create(e){const{privateKey:t,publicKey:r}=await async function(e){const{publicKey:t,privateKey:r}=await Tv().generateKey({name:"RSA-OAEP",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),[n,i]=await Promise.all([WX(r,{isPrivate:!0}),WX(t,{isPrivate:!1})]);return{privateKey:n,publicKey:i}}(e);return new JX(t,r)}}class QX{privateKey;publicKey;constructor(e,t){this.privateKey=e,this.publicKey=t}getPublicKey(){return this.publicKey}getPrivateKey(){return this.privateKey}getEncryptionType(){return rH.ML_KEM}static create(){const e=AQ.keygen();return new QX(Buffer.from(e.secretKey),Buffer.from(e.publicKey))}}const ZX=new Set([e.SignatureType.ML_DSA_87]),YX=new Set([rH.ML_KEM]),XX=new Set([e.EncryptionType.AES]);function e0(e,t){const r=XX.has(e),n=t.encryption?.requireQuantumResistantEncryption;return r||!n}function t0(e){return ZX.has(e.getSignatureType())}const r0={Resends:Symbol("Resends"),Subscriber:Symbol("Subscriber")};var n0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},i0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let o0=class{keyPair;pendingRequests=new vW(5e4);networkNodeFacade;streamRegistry;signatureValidator;messageSigner;store;subscriber;identity;logger;ensureStarted;config;requestGroupKey;constructor(e,t,r,n,i,s,o,a,c){var u,l;this.networkNodeFacade=e,this.streamRegistry=t,this.signatureValidator=r,this.messageSigner=n,this.store=i,this.subscriber=s,this.identity=a,this.logger=c.createLogger("SubscriberKeyExchange"),this.config=o,void 0===o.encryption.keys?(this.ensureStarted=_W((async()=>{this.keyPair=await async function(e,t){return t.encryption.requireQuantumResistantKeyExchange||t0(e)?QX.create():JX.create(t.encryption.rsaKeyLength)}(a,o),e.addMessageListener((e=>this.onMessage(e))),this.logger.debug("Started")})),this.requestGroupKey=(u=(e,t,r)=>this.doRequestGroupKey(e,t,r),l=o.encryption.maxKeyRequestsPerSecond,PW({limit:l,interval:1e3})(u))):(this.ensureStarted=async()=>{throw new uA("Assertion failed","ASSERTION_FAILED")},this.requestGroupKey=async()=>{throw new uA("Assertion failed","ASSERTION_FAILED")})}async doRequestGroupKey(e,t,r){await this.ensureStarted();const n=xF(),{message:i,request:s}=await this.createRequest(e,r,t,n);await this.networkNodeFacade.broadcast(i),this.pendingRequests.add(n),this.logger.debug("Sent group key request (waiting for response)",{groupKeyId:e,requestId:n,publisherId:t,keyEncryptionType:rH[s.encryptionType]})}async createRequest(t,r,n,i){const s={recipientId:RE(n),requestId:i,publicKey:this.keyPair.getPublicKey(),groupKeyIds:[t],encryptionType:this.keyPair.getEncryptionType()},o=this.subscriber.getERC1271ContractAddress(r);return{message:await this.messageSigner.createSignedMessage({messageId:new X$(AE.getStreamID(r),AE.getStreamPartition(r),Date.now(),0,void 0===o?await this.identity.getUserId():kE(o),bX()),content:uH.toBinary(s),contentType:e.ContentType.BINARY,messageType:e.StreamMessageType.GROUP_KEY_REQUEST,encryptionType:e.EncryptionType.NONE},void 0===o?this.identity.getSignatureType():e.SignatureType.ERC_1271),request:s}}async onMessage(t){if(t.messageType===e.StreamMessageType.GROUP_KEY_RESPONSE)try{const{requestId:e,recipientId:r,groupKeys:n,encryptionType:i}=lH.fromBinary(t.content),s=kE(r);await this.isAssignedToMe(t.getStreamPartID(),s,e)&&(this.logger.debug("Handle group key response",{requestId:e}),this.pendingRequests.delete(e),await GX(t,this.streamRegistry,this.signatureValidator,this.config),await Promise.all(n.map((async e=>{const r=await RQ.decryptWithPrivateKey(e.data,this.keyPair.getPrivateKey(),i);await this.store.set(e.id,t.getPublisherId(),r)}))))}catch(e){this.logger.debug("Failed to handle group key response",{err:e})}}async isAssignedToMe(e,t,r){if(this.pendingRequests.has(r)){const r=await this.identity.getUserId(),n=this.subscriber.getERC1271ContractAddress(e);return t===r||void 0!==n&&t===kE(n)}return!1}};o0=n0([q(d.ContainerScoped),s0(1,U(k((()=>WJ)))),s0(5,U(r0.Subscriber)),s0(6,U(cA)),s0(7,U(kA)),i0("design:paramtypes",[yX,WJ,KX,e.MessageSigner,aZ,Function,Object,RA,uD])],o0);var a0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},c0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},u0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const l0=async(e,t,r)=>{if(void 0!==r.keys)for(const n of Object.entries(r.keys))if(await t.toStreamID(n[0])===e)return new IQ(n[1].id,Buffer.from(mw(n[1].data)))};let h0=class{subscriberKeyExchange;localGroupKeyStore;explicitKeys;config;identity;eventEmitter;destroySignal;constructor(e,t,r,n,i,s,o){this.subscriberKeyExchange=e,this.localGroupKeyStore=t,this.config=n,this.identity=i,this.eventEmitter=s,this.destroySignal=o,void 0!==n.encryption.keys&&(this.explicitKeys=uJ({valueFactory:async e=>l0(e,r,n.encryption)}))}async fetchKey(e,t,r){if(void 0!==this.explicitKeys){const r=await this.explicitKeys.get(AE.getStreamID(e));if(void 0!==r)return r;throw new uA(`No encryption key available for stream part ID: groupKeyId=${t}, streamPartId=${e}`,"UNEXPECTED_INPUT")}let n=await this.localGroupKeyStore.get(t,r);if(void 0!==n)return n;await this.subscriberKeyExchange.requestGroupKey(t,r,e);const i=await eE(this.eventEmitter,"encryptionKeyStoredToLocalStore",this.config.encryption.keyRequestTimeout,(e=>e===t),this.destroySignal.abortSignal);return n=await this.localGroupKeyStore.get(i[0],r),n}async fetchLatestEncryptionKey(e,t){if(e!==await this.identity.getUserId())throw new Error("storeKey: fetching latest encryption keys for other publishers not supported.");const r=await this.localGroupKeyStore.getLatestEncryptionKeyId(e,t);return void 0!==r?this.localGroupKeyStore.get(r,e):void 0}async storeKey(e,t,r){if(t!==await this.identity.getUserId())throw new Error("storeKey: storing latest encryption keys for other publishers not supported.");if(void 0===e){const t=Buffer.from(so(32));e=new IQ(mW("GroupKey"),t)}return await this.localGroupKeyStore.set(e.id,t,e.data),await this.localGroupKeyStore.setLatestEncryptionKeyId(e.id,t,r),e}addKeyToLocalStore(e,t){return this.localGroupKeyStore.set(e.id,t,e.data)}};h0=a0([q(d.ContainerScoped),u0(3,U(cA)),u0(4,U(kA)),c0("design:paramtypes",[o0,aZ,YW,Object,RA,sD,UW])],h0);class d0{busy=new uE(!0);inputBuffer=[];outputBuffer;processMessageFn;onError;constructor(e,t,r){this.outputBuffer=e,this.processMessageFn=t,this.onError=r}async addMessage(e){if(this.inputBuffer.push(e),this.busy.isOpen()){for(this.busy.close();this.inputBuffer.length>0;){const e=this.inputBuffer.shift();try{const t=await this.processMessageFn(e);this.outputBuffer.push(t)}catch(e){this.onError.trigger(e)}}this.busy.open()}}}class f0{outputBuffer=new cW;processors=new Map;processMessageFn;onError;constructor(e,t){this.processMessageFn=e,this.onError=t}addMessage(e){const t=`${e.getPublisherId()}-${e.getMsgChainId()}`;let r=this.processors.get(t);void 0===r&&(r=new d0(this.outputBuffer,this.processMessageFn,this.onError),this.processors.set(t,r)),r.addMessage(e)}async flush(){await Promise.all(Array.from(this.processors.values()).map((e=>e.busy.waitUntilOpen())))}stop(e){this.outputBuffer.endWrite(e)}[Symbol.asyncIterator](){return this.outputBuffer}}const p0=new Bv("GapFiller"),g0=async e=>{try{await e()}catch(e){if("AbortError"!==e.code)throw e}};class m0{currentTask=void 0;chain;resend;getStorageNodeAddresses;strategy;initialWaitTime;retryWaitTime;maxRequestsPerGap;constructor(e){this.chain=e.chain,this.resend=e.resend,this.getStorageNodeAddresses=e.getStorageNodeAddresses,this.strategy=e.strategy,this.initialWaitTime=e.initialWaitTime,this.retryWaitTime=e.retryWaitTime,this.maxRequestsPerGap=e.maxRequestsPerGap,e.abortSignal.addEventListener("abort",(()=>{this.currentTask?.abortController.abort()}))}start(){this.chain.on("gapFound",(e=>this.onGapFound(e))),this.chain.on("gapResolved",(()=>this.onGapResolved()))}async onGapFound(e){const t=new AbortController;this.currentTask={gap:e,abortController:t};try{await g0((async()=>{if(await Qv(this.initialWaitTime,t.signal),this.maxRequestsPerGap>0&&await this.fetchFromStorageNode(e,t.signal),"full"===this.strategy)this.chain.resolveMessages(e.to.getMessageRef(),!0);else{if("light"!==this.strategy)throw new Error(`Assertion failed: unexpected gap fill strategy "${this.strategy}"`);this.chain.resolveMessages(void 0,!1)}}))}catch(t){this.onError(t,e)}}onGapResolved(){void 0!==this.currentTask&&(this.currentTask.abortController.abort(),this.currentTask=void 0)}async fetchFromStorageNode(e,t){const r=await this.getStorageNodeAddresses();if(r.length>0)for(let n=0;n<this.maxRequestsPerGap;n++){try{await g0((async()=>{const n=this.resend(e,oA(r),t);for await(const e of n)this.chain.addMessage(e)}))}catch(t){this.onError(t,e)}n!==this.maxRequestsPerGap-1&&await Qv(this.retryWaitTime,t)}}onError(e,t){p0.debug("Unable to fill gap",{error:{message:e?.message,code:e?.code},context:this.chain.getContext(),from:t.from.getMessageRef(),to:t.to.getMessageRef()})}}const y0=new Bv("OrderedMessageChain"),b0=(e,t)=>0===e.compareTo(t);class w0{lastOrderedMsg;currentGap;pendingMsgs;eventEmitter;context;abortSignal;constructor(e,t){this.context=e,this.pendingMsgs=new fE(((e,t)=>e.getMessageRef().compareTo(t.getMessageRef()))),this.eventEmitter=new Sl,this.abortSignal=t,t.addEventListener("abort",(()=>{this.eventEmitter.removeAllListeners()}))}addMessage(e){this.isStaleMessage(e)||(this.pendingMsgs.push(e),this.consumePendingOrderedMessages((e=>this.isNextOrderedMessage(e))))}resolveMessages(e,t){this.consumePendingOrderedMessages((t=>{if(this.isNextOrderedMessage(t))return!0;if(void 0===e||t.getMessageRef().compareTo(e)<=0){const e={from:this.lastOrderedMsg,to:t};return this.eventEmitter.emit("unfillableGap",e),!0}return!1}),t)}async waitUntilIdle(){const e=()=>this.pendingMsgs.isEmpty()||this.abortSignal.aborted;if(!e()){const t=new uE(!1),r=()=>{e()&&t.open()};this.on("orderedMessageAdded",r),this.abortSignal.addEventListener("abort",r),await t.waitUntilOpen(),this.off("orderedMessageAdded",r),this.abortSignal.removeEventListener("abort",r)}}consumePendingOrderedMessages(e,t=!0){for(;!this.pendingMsgs.isEmpty()&&e(this.pendingMsgs.peek());){const e=this.pendingMsgs.pop();this.lastOrderedMsg=e,this.eventEmitter.emit("orderedMessageAdded",e),this.checkGapResolved()}t&&this.checkGapFound()}checkGapFound(){this.pendingMsgs.isEmpty()||void 0!==this.currentGap||(this.currentGap={from:this.lastOrderedMsg,to:this.pendingMsgs.peek()},y0.debug("Gap found",{context:this.context,from:this.currentGap.from.getMessageRef(),to:this.currentGap.to.getMessageRef()}),this.eventEmitter.emit("gapFound",this.currentGap))}checkGapResolved(){if(void 0!==this.currentGap&&b0(this.lastOrderedMsg.getMessageRef(),this.currentGap.to.getMessageRef())){const e=this.currentGap;this.currentGap=void 0,y0.debug("Gap resolved",{context:this.context,from:e.from.getMessageRef(),to:e.to.getMessageRef()}),this.eventEmitter.emit("gapResolved")}}isNextOrderedMessage(e){const t=e.prevMsgRef;return void 0===this.lastOrderedMsg||void 0===t||b0(t,this.lastOrderedMsg.getMessageRef())}isStaleMessage(e){return void 0!==this.lastOrderedMsg&&e.getMessageRef().compareTo(this.lastOrderedMsg.getMessageRef())<=0||this.pendingMsgs.contains(e)}getContext(){return this.context}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}}class v0{chains;outBuffer=new cW;abortController=new AbortController;constructor(e,t,r,n,i){this.chains=uJ({valueFactory:async([s,o])=>{const a=((e,t,r,n,i,s)=>{const o=new w0(e,s);return o.on("unfillableGap",(e=>r(e))),new m0({chain:o,resend:async function*(t,r,i){const s=await n.resend(e.streamPartId,{from:{timestamp:t.from.getMessageRef().timestamp,sequenceNumber:t.from.getMessageRef().sequenceNumber+1},to:t.to.prevMsgRef,publisherId:e.publisherId,msgChainId:e.msgChainId,raw:!0},(async()=>[r]),i);yield*s},getStorageNodeAddresses:()=>t(AE.getStreamID(e.streamPartId)),strategy:i.gapFillStrategy,initialWaitTime:i.gapFillTimeout,retryWaitTime:i.retryResendAfter,maxRequestsPerGap:i.gapFill?i.maxGapRequests:0,abortSignal:s}).start(),o})({streamPartId:e,publisherId:s,msgChainId:o},t,r,n,i,this.abortController.signal);return a.on("orderedMessageAdded",(e=>this.onOrdered(e))),a}})}onOrdered(e){this.outBuffer.isDone()||pE((()=>this.outBuffer.push(e)))}destroy(){this.outBuffer.endWrite(),this.abortController.abort()}async addMessages(e){try{for await(const t of e){if(this.abortController.signal.aborted)return;(await this.chains.get([t.getPublisherId(),t.getMsgChainId()])).addMessage(t)}await Promise.all([...this.chains.values()].map((e=>e.waitUntilIdle()))),this.outBuffer.endWrite()}catch(e){this.outBuffer.endWrite(e)}}[Symbol.asyncIterator](){return this.outBuffer}}const E0=t=>{const r=t.loggerFactory.createLogger("messagePipeline"),n=new BW,i=new f0((async n=>{if(await GX(n,t.streamRegistry,t.signatureValidator,t.config),n.encryptionType!==e.EncryptionType.NONE&&!e0(n.encryptionType,t.config))throw new uA(`A message in stream ${n.getStreamId()} was rejected because the encryption type violates configured requirements (encryptionType: ${n.encryptionType})!`,"ENCRYPTION_POLICY_VIOLATION",n);if(!function(e,t){const r=ZX.has(e),n=t.encryption?.requireQuantumResistantSignatures;return r||!n}(n.signatureType,t.config))throw new uA(`A message in stream ${n.getStreamId()} was rejected because the signature type violates configured requirements (signatureType: ${n.encryptionType})!`,"SIGNATURE_POLICY_VIOLATION",n);let i;if(tW.isAESEncrypted(n))try{i=await(async(t,r,n)=>{if(n.isDestroyed())return t;let i;try{i=await r.fetchKey(t.getStreamPartID(),t.groupKeyId,t.getPublisherId())}catch{if(n.isDestroyed())return t;throw new uA(`Could not get encryption key ${t.groupKeyId}`,"DECRYPT_ERROR",t)}if(n.isDestroyed())return t;const[s,o]=RQ.decryptStreamMessage(t,i);return void 0!==o&&await r.addKeyToLocalStore(o,t.getPublisherId()),new tW({...t,content:s,encryptionType:e.EncryptionType.NONE})})(n,t.groupKeyManager,t.destroySignal)}catch(e){throw r.debug("Failed to decrypt",{messageId:n.messageId,err:e}),t.streamRegistry.invalidatePermissionCaches(n.getStreamId()),e}else i=n;return i.getParsedContent(),i}),n.onError),s=new WeakSet;if(n.onError.listen(((e,t)=>{throw t&&s.add(t.messageId),e&&"messageId"in e&&e.messageId&&s.add(e.messageId),e})),t.config.orderMessages){const e=new v0(t.streamPartId,t.getStorageNodes,(()=>{}),t.resends,t.config);n.pipe((async function*(t){setImmediate((()=>{e.addMessages(t)})),yield*e})),n.onBeforeFinally.listen((()=>{e.destroy()}))}return n.pipe((async function*(e){setImmediate((async()=>{let t;try{for await(const t of e)i.addMessage(t)}catch(e){t=e}await i.flush(),i.stop(t)})),yield*i})).filter((e=>!s.has(e.messageId))),n};var A0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},S0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},k0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let R0=class{resends;streamStorageRegistry;streamRegistry;signatureValidator;groupKeyManager;config;destroySignal;loggerFactory;constructor(e,t,r,n,i,s,o,a){this.resends=e,this.streamStorageRegistry=t,this.streamRegistry=r,this.signatureValidator=n,this.groupKeyManager=i,this.config=s,this.destroySignal=o,this.loggerFactory=a}createMessagePipeline(e){return E0({...e,getStorageNodes:e.getStorageNodes??(e=>this.streamStorageRegistry.getStorageNodes(e)),resends:this.resends,streamRegistry:this.streamRegistry,signatureValidator:this.signatureValidator,groupKeyManager:this.groupKeyManager,config:e.config??this.config,destroySignal:this.destroySignal,loggerFactory:this.loggerFactory})}};R0=A0([q(d.ContainerScoped),k0(0,U(r0.Resends)),k0(2,U(k((()=>WJ)))),k0(4,U(k((()=>h0)))),k0(5,U(cA)),S0("design:paramtypes",[Function,aQ,WJ,KX,h0,Object,UW,uD])],R0);var C0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},I0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},P0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const T0=(e,t,r,n={})=>{const i={...n,format:"raw"},[s,o]=AE.getStreamIDAndPartition(r),a=(e=>{const t=Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)));return new URLSearchParams(t).toString()})(i);return`${e}/streams/${encodeURIComponent(s)}/data/partitions/${o}/${t}?${a}`},_0=e=>({...e,publisherId:"publisherId"in e&&void 0!==e.publisherId?kE(e.publisherId):void 0});let N0=class{storageNodeRegistry;messagePipelineFactory;config;logger;constructor(e,t,r,n){this.storageNodeRegistry=e,this.messagePipelineFactory=t,this.config=r,this.logger=n.createLogger("Resends")}async resend(e,t,r,n){const i=t.raw??!1;if(function(e){return e&&"object"==typeof e&&"last"in e&&null!=e.last}(t)){if(t.last<=0){const e=new BW;return e.endWrite(),e}return this.fetchStream("last",e,{count:t.last},i,r,n)}if(function(e){return e&&"object"==typeof e&&"from"in e&&"to"in e&&e.to&&null!=e.from}(t))return this.fetchStream("range",e,{fromTimestamp:new Date(t.from.timestamp).getTime(),fromSequenceNumber:t.from.sequenceNumber,toTimestamp:new Date(t.to.timestamp).getTime(),toSequenceNumber:t.to.sequenceNumber,publisherId:t.publisherId,msgChainId:t.msgChainId},i,r,n);if(function(e){return e&&"object"==typeof e&&"from"in e&&!("to"in e)&&null!=e.from}(t))return this.fetchStream("from",e,{fromTimestamp:new Date(t.from.timestamp).getTime(),fromSequenceNumber:t.from.sequenceNumber,publisherId:t.publisherId},i,r,n);throw new uA(`can not resend without valid resend options: ${JSON.stringify({streamPartId:e,options:t})}`,"INVALID_ARGUMENT")}async fetchStream(e,t,r,n,i,s){const o=Wv(5);this.logger.debug("Fetch resend data",{loggerIdx:o,resendType:e,streamPartId:t,query:r});const a=AE.getStreamID(t),c=await i(a);if(!c.length)throw new uA(`no storage assigned: ${a}`,"NO_STORAGE_NODES");const u=c[XE(0,c.length-1)],l=(await this.storageNodeRegistry.getStorageNodeMetadata(u)).urls,h=T0(oA(l),e,t,r),d=n?new BW:this.messagePipelineFactory.createMessagePipeline({streamPartId:t,getStorageNodes:async()=>ju(c,u),config:1===c.length?{...this.config,orderMessages:!1}:this.config}),f=async function*(e,t){try{for await(const t of e)yield t}catch(e){throw await t(e)}}(async function*(e,t){yW.debug("Send HTTP request",{url:e});const r=new AbortController,n=rE(r.signal,t);try{const t=await fetch(e,{signal:n});if(yW.debug("Received HTTP response",{url:e,status:t.status}),!t.ok)throw new kW(t);if(!t.body)throw new Error("No Response Body");let i;try{const e=dW(t.body);i=e.pipe(new gE),e.on("error",(e=>i.destroy(e))),i.once("close",(()=>{r.abort()})),yield*i}catch(e){throw r.abort(),e}finally{i?.destroy()}}finally{n.destroy()}}(h,s),(async e=>{let t;if(e instanceof kW){const r=await e.response.text();let n;try{n=`: ${JSON.parse(r).error}`}catch{n=""}t=`Storage node fetch failed${n}, httpStatus=${e.response.status}, url=${e.response.url}`}else t=e?.message??"Unknown error";return new uA(t,"STORAGE_NODE_ERROR")}));return setImmediate((async()=>{let e=0;const t=sW(f,(e=>nW(e)));await async function(e,t){if(!e)throw new Error("no source");try{for await(const r of e)if(!await t.push(r))break}catch(e){t.endWrite(e)}finally{t.endWrite()}}(iW(t,(()=>e++)),d),this.logger.debug("Finished resend",{loggerIdx:o,messageCount:e})})),d}};function M0(e){return e.filter(Boolean).join("\n")}function x0(e){return e.flatMap((e=>function(e){return e instanceof O0?[e.ownStack,...[...e.errors].map((({stack:e})=>e))]:[e.stack]}(e))).filter(Boolean).join("\n")}N0=C0([j(),P0(0,U(k((()=>ID)))),P0(1,U(k((()=>R0)))),P0(2,U(cA)),I0("design:paramtypes",[ID,R0,Object,uD])],N0);class O0 extends Error{errors;ownMessage;ownStack;constructor(e=[],t=""){const r=M0([t,...e.map((e=>e.message))]);super(r),e.forEach((e=>{Object.assign(this,e)})),this.message=r,this.ownMessage=t,this.errors=new Set(e),this.ownStack=this.stack,this.stack=x0([this,...e])}static fromAllSettled(e=[],t=""){const r=e.map((({reason:e})=>e)).filter(Boolean);if(r.length)return new this(r,t)}static throwAllSettled(e=[],t=""){const r=this.fromAllSettled(e,t);if(r)throw r}static from(e,t,r){return t?e?e instanceof O0?e.extend(t,r,this):new this([e]).extend(t,r):(t&&r&&(t.message=M0([t.message,r])),t):(e&&r&&(e.message=M0([e.message,r])),e)}extend(e,t="",r=this.constructor){if(e===this||this.errors.has(e))return this;return new r([e,...this.errors],M0([t,this.ownMessage]))}}const D0=()=>{};function B0(e=[],t,{id:r="",onError:n,onDone:i,onChange:s}={}){let o;const a=e.slice().reverse().map((e=>async()=>{const t=await e();return"function"==typeof t?t:D0})),c=[],u=[],l=gD(1);let h=!1,d=!1;function f(e){try{if("function"!=typeof n)throw e;n(e)}catch(e){o=O0.from(o,e,`ScaffoldError:${r}`)}}let p=!1,g=!1;const m=gD(1);async function y(){p=await(async()=>{if(o)return!1;try{return await t()}catch(e){f(e)}return!1})();const e=g!==p;if(g=p,e&&"function"==typeof s){try{await s(p)}catch(e){f(e)}return y()}if(p){if(a.length){let e;h=!1,d=!0;const t=a.pop();c.push(t);try{e=await t()}catch(e){f(e)}return u.push(e??(()=>{})),void await y()}}else{if(u.length){h=!1,d=!0;const e=u.pop();try{await e()}catch(e){f(e)}return a.push(c.pop()),void await y()}if(o){const e=o;throw o=void 0,h=!0,e}}return h=!0,Promise.resolve()}function b(){return!(d&&h&&!l.activeCount&&!l.pendingCount)}const w=async()=>{await m((()=>y()))};let v;return Object.assign((async()=>{let e;try{v=l((()=>w())),await v}catch(t){throw e=t,t}finally{if(!b()&&(d=!1,"function"==typeof i)){const t=e;e=void 0,await i(p,t)}}}),{next:w,isActive:b,getCurrentStep:()=>v,get activeCount(){return l.activeCount},get pendingCount(){return l.pendingCount},setError(e){o=O0.from(o,e)},getError:()=>o,clearError(){const e=o;return o=void 0,e}})}class L0{streamPartId;onRetired=MW.once();isRetired=!1;isStopped=!1;subscriptions=new Set;pendingRemoval=new WeakSet;pipeline;node;constructor(e,t,r){this.streamPartId=e,this.distributeMessage=this.distributeMessage.bind(this),this.node=r,this.onError=this.onError.bind(this),this.pipeline=t.createMessagePipeline({streamPartId:e}),this.pipeline.onError.listen(this.onError),this.pipeline.pipe(this.distributeMessage).onBeforeFinally.listen((async()=>{this.isStopped||await this.stop()})),this.pipeline.flow()}async retire(){this.isRetired||(this.isRetired=!0,await this.onRetired.trigger())}async onError(e){await Promise.allSettled([...this.subscriptions].map((async t=>{await t.handleError(e)})))}async*distributeMessage(e){for await(const t of e)await Promise.all([...this.subscriptions].map((async e=>{await e.push(t)}))),yield t}onMessageInput=async t=>{if(!t||this.isStopped||this.isRetired)return;if(t.getStreamPartID()!==this.streamPartId)return;if(t.messageType!==e.StreamMessageType.MESSAGE)return;const r=[];let n=!1;for(const e of this.subscriptions.values())e.isRaw?r.push(e.push(t)):n=!0;n&&r.push(this.pipeline.push(t)),await Promise.all(r)};async subscribe(){if(this.node.addMessageListener(this.onMessageInput),!await this.node.isProxiedStreamPart(this.streamPartId)){const e=(e=>e.values().next().value)(this.subscriptions).deliveryOptions;await this.node.join(this.streamPartId,void 0,e)}}async unsubscribe(){this.pipeline.end(),this.pipeline.return(),this.pipeline.onError.end(new Error("done")),this.node.removeMessageListener(this.onMessageInput),await this.node.leave(this.streamPartId)}updateNodeSubscriptions=(()=>B0([async()=>(await this.subscribe(),async()=>{await this.unsubscribe(),await this.stop()})],(()=>this.shouldBeSubscribed())))();async updateSubscriptions(){await this.updateNodeSubscriptions(),this.shouldBeSubscribed()||this.isStopped||await this.stop()}shouldBeSubscribed(){return!this.isRetired&&!this.isStopped&&!!this.count()}async stop(){this.isStopped=!0,this.pipeline.end(),await this.retire(),await this.pipeline.return()}has(e){return this.subscriptions.has(e)}async add(e){if(!e||this.subscriptions.has(e)||this.pendingRemoval.has(e))return;const t=this.getERC1271ContractAddress();if(this.subscriptions.size>0&&t!==e.erc1271ContractAddress)throw new Error("Subscription ERC-1271 mismatch");this.subscriptions.add(e),e.onBeforeFinally.listen((()=>this.remove(e))),await this.updateSubscriptions()}async remove(e){if(e&&!this.pendingRemoval.has(e)&&this.subscriptions.has(e)){this.pendingRemoval.add(e),this.subscriptions.delete(e);try{e.isDone()||await e.unsubscribe()}finally{await this.updateSubscriptions()}}}getERC1271ContractAddress(){for(const e of this.subscriptions)if(void 0!==e.erc1271ContractAddress)return e.erc1271ContractAddress}count(){return this.subscriptions.size}}var F0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},U0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},j0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let q0=class{subSessions=new Map;node;messagePipelineFactory;logger;constructor(e,t,r){this.node=e,this.messagePipelineFactory=t,this.logger=r.createLogger("Subscriber")}getOrCreateSubscriptionSession(e){if(this.subSessions.has(e))return this.getSubscriptionSession(e);const t=new L0(e,this.messagePipelineFactory,this.node);return this.subSessions.set(e,t),t.onRetired.listen((()=>{this.subSessions.delete(e)})),this.logger.debug("Created new SubscriptionSession",{streamPartId:e}),t}async add(e){const t=this.getOrCreateSubscriptionSession(e.streamPartId);try{await t.add(e)}catch(t){throw this.logger.debug("Failed to add Subscription to SubscriptionSession",t),await this.remove(e),t}}async remove(e){const t=this.subSessions.get(e.streamPartId);t&&await t.remove(e)}getSubscriptions(){return[...this.subSessions.values()].reduce(((e,t)=>(e.push(...t.subscriptions),e)),[])}getERC1271ContractAddress(e){return this.subSessions.get(e)?.getERC1271ContractAddress()}getSubscriptionSession(e){return this.subSessions.get(e)}countSubscriptionSessions(){return this.subSessions.size}};q0=F0([j(),j0(1,U(k((()=>R0)))),U0("design:paramtypes",[yX,R0,uD])],q0),F.register(r0.Resends,{useClass:N0},{lifecycle:d.ContainerScoped}),F.register(r0.Subscriber,{useClass:q0},{lifecycle:d.ContainerScoped});var z0,K0,G0={},V0={};var H0,$0=function(){if(K0)return G0;K0=1,Object.defineProperty(G0,"__esModule",{value:!0}),G0.isConstructorToken=G0.isTransformDescriptor=G0.isTokenDescriptor=G0.isNormalToken=void 0;const e=function(){if(z0)return V0;z0=1,Object.defineProperty(V0,"__esModule",{value:!0}),V0.delay=V0.DelayedConstructor=void 0;class e{constructor(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}createProxy(e){let t,r=!1;return new Proxy({},this.createHandler((()=>(r||(t=e(this.wrap()),r=!0),t))))}createHandler(e){const t={};return this.reflectMethods.forEach((r=>{t[r]=(...t)=>(t[0]=e(),(0,Reflect[r])(...t))})),t}}return V0.DelayedConstructor=e,V0.delay=function(t){if(void 0===t)throw new Error("Attempt to `delay` undefined. Constructor must be wrapped in a callback");return new e(t)},V0}();return G0.isNormalToken=function(e){return"string"==typeof e||"symbol"==typeof e},G0.isTokenDescriptor=function(e){return"object"==typeof e&&"token"in e&&"multiple"in e},G0.isTransformDescriptor=function(e){return"object"==typeof e&&"token"in e&&"transform"in e},G0.isConstructorToken=function(t){return"function"==typeof t||t instanceof e.DelayedConstructor},G0}(),W0={};var J0,Q0,Z0=(H0||(H0=1,Object.defineProperty(W0,"__esModule",{value:!0}),W0.formatErrorCtor=void 0,W0.formatErrorCtor=function(e,t,r){const[,n=null]=e.toString().match(/constructor\(([\w, ]+)\)/)||[];return function(e,t,r=" "){return[e,...t.message.split("\n").map((e=>r+e))].join("\n")}(`Cannot inject the dependency ${function(e,t){return null===e?`at position #${t}`:`"${e.split(",")[t].trim()}" at position #${t}`}(n,t)} of "${e.name}" constructor. Reason:`,r)}),W0);F.constructor.prototype.resolveParams=function(e,t){return(r,n)=>{try{return $0.isTokenDescriptor(r)?$0.isTransformDescriptor(r)?r.multiple?this.resolve(r.transform).transform(this.resolveAll(r.token),...r.transformArgs):this.resolve(r.transform).transform(this.resolve(r.token,e),...r.transformArgs):r.multiple?this.resolveAll(r.token):this.resolve(r.token,e):$0.isTransformDescriptor(r)?this.resolve(r.transform,e).transform(this.resolve(r.token,e),...r.transformArgs):this.resolve(r,e)}catch(e){throw e.message=Z0.formatErrorCtor(t,n,e),e}}};var Y0,X0,e1=function(){if(Q0)return J0;Q0=1;var e=Td(),t=Nd()((function(t,r,n){e(t,r,n)}));return J0=t}(),t1=n(e1);var r1=function(){if(X0)return Y0;X0=1;var e=De(),t=qu(),r=Be();return Y0=function(n){return"string"==typeof n||!t(n)&&r(n)&&"[object String]"==e(n)}}(),n1=n(r1);class i1{currentGroupKey;queuedGroupKey;streamId;identity;groupKeyManager;static async createInstance(e,t,r,n){const i=new i1(e,t,r);return i.currentGroupKey=n??await i.groupKeyManager.fetchLatestEncryptionKey(await t.getUserId(),e)??void 0,i}constructor(e,t,r){this.streamId=e,this.identity=t,this.groupKeyManager=r}async useGroupKey(){this.currentGroupKey||(this.currentGroupKey=this.queuedGroupKey??await this.rekey(),this.queuedGroupKey=void 0);const e={current:this.currentGroupKey,next:this.queuedGroupKey};return this.queuedGroupKey&&(this.currentGroupKey=this.queuedGroupKey,this.queuedGroupKey=void 0),e}async rotate(e){const t=await this.identity.getUserId();return e=await this.groupKeyManager.storeKey(e,t,this.streamId),this.queuedGroupKey=e,e}async rekey(e){const t=await this.identity.getUserId();return e=await this.groupKeyManager.storeKey(e,t,this.streamId),this.currentGroupKey=e,this.queuedGroupKey=void 0,e}}class s1{streamId;identity;defaultPartition;defaultMessageChainIds;prevMsgRefs=new Map;streamRegistry;groupKeyQueue;signatureValidator;messageSigner;config;firstMessage=!0;constructor(e){this.streamId=e.streamId,this.identity=e.identity,this.streamRegistry=e.streamRegistry,this.groupKeyQueue=e.groupKeyQueue,this.signatureValidator=e.signatureValidator,this.messageSigner=e.messageSigner,this.config=e.config,this.defaultMessageChainIds=uJ({valueFactory:async()=>bX()})}async createMessage(t,r,n){const i=await this.getPublisherId(r);if(this.config.validation.permissions){if(!await this.streamRegistry.isStreamPublisher(this.streamId,i))throw this.streamRegistry.invalidatePermissionCaches(this.streamId),new uA(`You don't have permission to publish to this stream. Using address: ${i}`,"MISSING_PERMISSION")}let s;if(this.config.validation.partitions){const e=await this.streamRegistry.getStreamMetadata(this.streamId),t=eJ(e);if(void 0!==n){if(n<0||n>=t)throw new Error(`Partition ${n} is out of range (0..${t-1})`);if(void 0!==r.partitionKey)throw new Error('Invalid combination of "partition" and "partitionKey"');s=n}else s=void 0!==r.partitionKey?function(e,t){if(!(Number.isSafeInteger(e)&&e>0))throw new Error(`lengthOfArray is not a safe positive integer! ${e}`);if(1===e)return 0;if("number"==typeof t)return Math.abs(t)%e;const r=_v(t).readInt32LE(0);return Math.abs(r)%e}(t,r.partitionKey):this.getDefaultPartition(t)}else{if(void 0===n)throw new Error("Explicit partition must be set when partition validation is disabled");s=n}const o=r.msgChainId??await this.defaultMessageChainIds.get(s),a=SW([s,o]),c=this.prevMsgRefs.get(a),u=((e,t)=>{if(void 0!==t&&e<t.timestamp)throw new Error("prevMessageRef must come before current");const r=t?.timestamp===e?t.sequenceNumber+1:0;return new Y$(e,r)})(r.timestamp,c);this.prevMsgRefs.set(a,u);const l=new X$(this.streamId,s,u.timestamp,u.sequenceNumber,i,o),h=this.config.validation.permissions&&await this.streamRegistry.hasPublicSubscribePermission(this.streamId)?e.EncryptionType.NONE:e.EncryptionType.AES;if(!e0(h,this.config))throw new uA(`Publishing to stream ${this.streamId} was prevented because configuration requires encryption!`,"ENCRYPTION_POLICY_VIOLATION");let d,f,p,g;if(t instanceof Uint8Array?(g=e.ContentType.BINARY,p=t):(g=e.ContentType.JSON,p=pw(JSON.stringify(t))),h===e.EncryptionType.AES){const e=await this.groupKeyQueue.useGroupKey();p=RQ.encryptWithAES(p,e.current.data),d=e.current.id,void 0!==e.next&&(f=e.current.encryptNextGroupKey(e.next))}const m=await this.messageSigner.createSignedMessage({messageId:l,messageType:e.StreamMessageType.MESSAGE,content:p,prevMsgRef:c,encryptionType:h,groupKeyId:d,newGroupKey:f,contentType:g},void 0!==r.erc1271Contract?e.SignatureType.ERC_1271:this.identity.getSignatureType());return this.firstMessage&&(this.firstMessage=!1,void 0!==r.erc1271Contract&&await this.signatureValidator.assertSignatureIsValid(m)),m}async getPublisherId(e){return void 0!==e.erc1271Contract?kE(nb(e.erc1271Contract)):this.identity.getUserId()}getDefaultPartition(e){return(void 0===this.defaultPartition||this.defaultPartition>=e)&&(this.defaultPartition=XE(e-1)),this.defaultPartition}}var o1=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},a1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},c1=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let u1=class{messageFactories;groupKeyQueues;concurrencyLimit=gD(1);node;streamRegistry;streamIdBuilder;identity;signatureValidator;messageSigner;config;constructor(e,t,r,n,i,s,o,a){this.node=e,this.streamRegistry=t,this.streamIdBuilder=n,this.identity=i,this.signatureValidator=s,this.messageSigner=o,this.config=a,this.messageFactories=uJ({valueFactory:async e=>this.createMessageFactory(e)}),this.groupKeyQueues=uJ({valueFactory:async e=>{const t=await l0(e,this.streamIdBuilder,this.config.encryption);return await i1.createInstance(e,this.identity,r,t)}})}async publish(e,t,r,n){const i=(e=>void 0===e?.timestamp?Date.now():e.timestamp instanceof Date?e.timestamp.getTime():n1(e.timestamp)?new Date(e.timestamp).getTime():e.timestamp)(r);return this.concurrencyLimit((async()=>{const[s,o]=await this.streamIdBuilder.toStreamPartElements(e);try{const e=await this.messageFactories.get(s),a=await e.createMessage(t,{...r,timestamp:i},o);return await this.node.broadcast(a,n),a}catch(e){const t=e instanceof uA?e.code:"UNKNOWN_ERROR";throw new uA(`Failed to publish to stream ${s}. Cause: ${e.message}`,t)}}))}getGroupKeyQueue(e){return this.groupKeyQueues.get(e)}async createMessageFactory(e){return new s1({streamId:e,identity:this.identity,streamRegistry:this.streamRegistry,groupKeyQueue:await this.groupKeyQueues.get(e),signatureValidator:this.signatureValidator,messageSigner:this.messageSigner,config:this.config})}};var l1,h1;u1=o1([q(d.ContainerScoped),c1(4,U(kA)),c1(7,U(cA)),a1("design:paramtypes",[yX,WJ,h0,YW,RA,KX,e.MessageSigner,Object])],u1);var d1,f1=n(function(){if(h1)return l1;h1=1;var e=sY();return l1=function(t){return e(t,5)}}()),p1={exports:{}};var g1=function(){if(d1)return p1.exports;d1=1,p1.exports=u,p1.exports.default=u;const e={properties:{environment:{type:"string",enum:["polygon","polygonAmoy","peaq","iotex","dev2"],description:"applies all environment-specific defaults for the given environment"},id:{type:"string"},logLevel:{type:"string",enum:["silent","fatal","error","warn","info","debug","trace"],default:"info"},auth:{type:"object",additionalProperties:!1,properties:{publicKey:{type:"string",format:"hex-string"},privateKey:{type:"string",format:"hex-string"},keyType:{type:"string",default:"ECDSA_SECP256K1_EVM"},ethereum:{type:"object"},identity:{type:"object"}}},orderMessages:{type:"boolean",default:!0},gapFill:{type:"boolean",default:!0},maxGapRequests:{type:"number",default:5},retryResendAfter:{type:"number",default:5e3},gapFillTimeout:{type:"number",default:5e3},gapFillStrategy:{type:"string",enum:["light","full"],default:"light"},network:{type:"object",additionalProperties:!1,required:[],properties:{controlLayer:{type:"object",additionalProperties:!1,properties:{entryPoints:{type:"array",items:{$ref:"#/definitions/peerDescriptor"}},entryPointDiscovery:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"},maxEntryPoints:{type:"number"},maxQueryResults:{type:"number"},maxHeartbeatAgeHours:{type:"number"}},default:{enabled:!0,maxEntryPoints:5,maxQueryResults:50,maxHeartbeatAgeHours:24}},websocketPortRange:{anyOf:[{type:"null"},{$ref:"#/definitions/portRange"}],default:{min:32200,max:32250}},websocketHost:{type:"string",format:"hostname"},peerDescriptor:{$ref:"#/definitions/peerDescriptor"},maxConnections:{type:"number",default:80},tlsCertificate:{description:"Files to use for TLS",type:"object",required:["certFileName","privateKeyFileName"],additionalProperties:!1,properties:{certFileName:{type:"string",description:"Path of certificate file"},privateKeyFileName:{type:"string",description:"Path of private key file"}}},iceServers:{type:"array",items:{type:"object",required:["url","port"],additionalProperties:!1,properties:{url:{type:"string"},port:{type:"number"},username:{type:"string"},password:{type:"string"},tcp:{type:"boolean"}}},default:[{url:"stun:stun.streamr.network",port:5349},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q=="},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q==",tcp:!0}]},webrtcAllowPrivateAddresses:{type:"boolean",default:!1},webrtcDatachannelBufferThresholdLow:{type:"number",default:32768},webrtcDatachannelBufferThresholdHigh:{type:"number",default:131072},maxMessageSize:{type:"number",default:1048576},externalIp:{type:"string",format:"ipv4"},webrtcPortRange:{$ref:"#/definitions/portRange",default:{min:5e4,max:64e3}},networkConnectivityTimeout:{type:"number",default:1e4},websocketServerEnableTls:{type:"boolean",default:!0},autoCertifierUrl:{type:"string",default:"https://ns1.streamr-nodes.xyz:59833"},autoCertifierConfigFile:{type:"string",default:"~/.streamr/certificate.json"},geoIpDatabaseFolder:{type:"string"}},default:{}},node:{type:"object",additionalProperties:!1,properties:{streamPartitionNeighborTargetCount:{type:"number",default:4},streamPartitionMinPropagationTargets:{type:"number",default:2},streamPartitionMaxPropagationBufferSize:{type:"number",default:150},contentDeliveryBufferWhileConnecting:{type:"boolean",default:!0},acceptProxyConnections:{type:"boolean",default:!1}},default:{}}},default:{}},contracts:{type:"object",additionalProperties:!1,properties:{ethereumNetwork:{type:"object",additionalProperties:!1,properties:{chainId:{type:"number"},overrides:{type:"object"},highGasPriceStrategy:{type:"boolean"}},default:{}},streamRegistryChainAddress:{type:"string",format:"ethereum-address"},streamStorageRegistryChainAddress:{type:"string",format:"ethereum-address"},storageNodeRegistryChainAddress:{type:"string",format:"ethereum-address"},sponsorshipFactoryChainAddress:{type:"string",format:"ethereum-address"},rpcs:{type:"array",items:{type:"object",$ref:"#/definitions/rpcProviderConfig"},minItems:1},rpcQuorum:{type:"number",default:2},theGraphUrl:{type:"string",format:"uri"},maxConcurrentCalls:{type:"number",default:10},pollInterval:{type:"number",default:4e3}},default:{}},encryption:{type:"object",additionalProperties:!1,properties:{keyRequestTimeout:{type:"number",default:3e4},maxKeyRequestsPerSecond:{type:"number",default:20},rsaKeyLength:{type:"number",default:4096},requireQuantumResistantKeyExchange:{type:"boolean",default:!1},requireQuantumResistantSignatures:{type:"boolean",default:!1},requireQuantumResistantEncryption:{type:"boolean",default:!1},keys:{type:"object",propertyNames:{$ref:"#/definitions/streamIdOrPath"},additionalProperties:{$ref:"#/definitions/encryptionKey"}}},default:{}},validation:{type:"object",additionalProperties:!1,properties:{permissions:{type:"boolean",default:!0},partitions:{type:"boolean",default:!0}},default:{}},metrics:{anyOf:[{type:"boolean"},{type:"object",additionalProperties:!1,properties:{periods:{type:"array",items:{type:"object",required:["streamId","duration"],properties:{id:{type:"string"},duration:{type:"number"}}}},maxPublishDelay:{type:"number"}}}]},cache:{type:"object",additionalProperties:!1,properties:{maxSize:{type:"number",default:1e4},maxAge:{type:"number",default:864e5}},default:{}},_timeouts:{type:"object",additionalProperties:!1,properties:{theGraph:{type:"object",additionalProperties:!1,properties:{indexTimeout:{type:"number",default:6e4},indexPollInterval:{type:"number",default:1e3},fetchTimeout:{type:"number",default:3e4}},default:{}},storageNode:{type:"object",additionalProperties:!1,properties:{timeout:{type:"number",default:3e4},retryInterval:{type:"number",default:1e3}},default:{}},ensStreamCreation:{type:"object",additionalProperties:!1,properties:{timeout:{type:"number",default:18e4},retryInterval:{type:"number",default:1e3}},default:{}},jsonRpcTimeout:{type:"number",default:3e4}},default:{}}}},t=Object.prototype.hasOwnProperty,r=/^(0x)?[a-fA-F0-9]+$/,n=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,i=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,s=/^0x[a-fA-F0-9]{40}$/,o=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,a={enum:["browser","nodejs"]};function c(e,{instancePath:t="",parentData:r,parentDataProperty:n,rootData:i=e}={}){if(!e||"object"!=typeof e||Array.isArray(e))return c.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;for(const r in e)if("nodeId"!==r&&"id"!==r&&"type"!==r&&"websocket"!==r)return c.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"}],!1;if(void 0!==e.nodeId){const r=0;if("string"!=typeof e.nodeId)return c.errors=[{instancePath:t+"/nodeId",schemaPath:"#/properties/nodeId/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var s=0===r}else s=!0;if(s){if(void 0!==e.id){const r=0;if("string"!=typeof e.id)return c.errors=[{instancePath:t+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;s=0===r}else s=!0;if(s){if(void 0!==e.type){let r=e.type;const n=0;if("string"!=typeof r)return c.errors=[{instancePath:t+"/type",schemaPath:"#/definitions/nodeType/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("browser"!==r&&"nodejs"!==r)return c.errors=[{instancePath:t+"/type",schemaPath:"#/definitions/nodeType/enum",keyword:"enum",params:{allowedValues:a.enum},message:"must be equal to one of the allowed values"}],!1;s=0===n}else s=!0;if(s)if(void 0!==e.websocket){let r=e.websocket;const n=0;if(!r||"object"!=typeof r||Array.isArray(r))return c.errors=[{instancePath:t+"/websocket",schemaPath:"#/definitions/connectivityMethod/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let e;if(void 0===r.host&&(e="host")||void 0===r.port&&(e="port")||void 0===r.tls&&(e="tls"))return c.errors=[{instancePath:t+"/websocket",schemaPath:"#/definitions/connectivityMethod/required",keyword:"required",params:{missingProperty:e},message:"must have required property '"+e+"'"}],!1;for(const e in r)if("host"!==e&&"port"!==e&&"tls"!==e)return c.errors=[{instancePath:t+"/websocket",schemaPath:"#/definitions/connectivityMethod/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(void 0!==r.host){const e=0;if("string"!=typeof r.host)return c.errors=[{instancePath:t+"/websocket/host",schemaPath:"#/definitions/connectivityMethod/properties/host/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var o=0===e}else o=!0;if(o){if(void 0!==r.port){let e=r.port;const n=0;if("number"!=typeof e||!isFinite(e))return c.errors=[{instancePath:t+"/websocket/port",schemaPath:"#/definitions/connectivityMethod/properties/port/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;o=0===n}else o=!0;if(o)if(void 0!==r.tls){const e=0;if("boolean"!=typeof r.tls)return c.errors=[{instancePath:t+"/websocket/tls",schemaPath:"#/definitions/connectivityMethod/properties/tls/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;o=0===e}else o=!0}}s=0===n}else s=!0}}return c.errors=null,!0}function u(a,{instancePath:l="",parentData:h,parentDataProperty:d,rootData:f=a}={}){let p=null,g=0;if(0===g){if(!a||"object"!=typeof a||Array.isArray(a))return u.errors=[{instancePath:l,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===a.logLevel&&(a.logLevel="info"),void 0===a.orderMessages&&(a.orderMessages=!0),void 0===a.gapFill&&(a.gapFill=!0),void 0===a.maxGapRequests&&(a.maxGapRequests=5),void 0===a.retryResendAfter&&(a.retryResendAfter=5e3),void 0===a.gapFillTimeout&&(a.gapFillTimeout=5e3),void 0===a.gapFillStrategy&&(a.gapFillStrategy="light"),void 0===a.network&&(a.network={}),void 0===a.contracts&&(a.contracts={}),void 0===a.encryption&&(a.encryption={}),void 0===a.validation&&(a.validation={}),void 0===a.cache&&(a.cache={}),void 0===a._timeouts&&(a._timeouts={});const h=g;for(const r in a)if(!t.call(e.properties,r))return u.errors=[{instancePath:l,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"}],!1;if(h===g){if(void 0!==a.environment){let t=a.environment;const r=g;if("string"!=typeof t)return u.errors=[{instancePath:l+"/environment",schemaPath:"#/properties/environment/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("polygon"!==t&&"polygonAmoy"!==t&&"peaq"!==t&&"iotex"!==t&&"dev2"!==t)return u.errors=[{instancePath:l+"/environment",schemaPath:"#/properties/environment/enum",keyword:"enum",params:{allowedValues:e.properties.environment.enum},message:"must be equal to one of the allowed values"}],!1;var m=r===g}else m=!0;if(m){if(void 0!==a.id){const e=g;if("string"!=typeof a.id)return u.errors=[{instancePath:l+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;m=e===g}else m=!0;if(m){let h=a.logLevel;const d=g;if("string"!=typeof h)return u.errors=[{instancePath:l+"/logLevel",schemaPath:"#/properties/logLevel/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("silent"!==h&&"fatal"!==h&&"error"!==h&&"warn"!==h&&"info"!==h&&"debug"!==h&&"trace"!==h)return u.errors=[{instancePath:l+"/logLevel",schemaPath:"#/properties/logLevel/enum",keyword:"enum",params:{allowedValues:e.properties.logLevel.enum},message:"must be equal to one of the allowed values"}],!1;if(m=d===g){if(void 0!==a.auth){let e=a.auth;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/auth",schemaPath:"#/properties/auth/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.keyType&&(e.keyType="ECDSA_SECP256K1_EVM");const t=g;for(const t in e)if("publicKey"!==t&&"privateKey"!==t&&"keyType"!==t&&"ethereum"!==t&&"identity"!==t)return u.errors=[{instancePath:l+"/auth",schemaPath:"#/properties/auth/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.publicKey){let t=e.publicKey;const n=g;if(g===n&&g===n){if("string"!=typeof t)return u.errors=[{instancePath:l+"/auth/publicKey",schemaPath:"#/properties/auth/properties/publicKey/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!r.test(t))return u.errors=[{instancePath:l+"/auth/publicKey",schemaPath:"#/properties/auth/properties/publicKey/format",keyword:"format",params:{format:"hex-string"},message:'must match format "hex-string"'}],!1}var y=n===g}else y=!0;if(y){if(void 0!==e.privateKey){let t=e.privateKey;const n=g;if(g===n&&g===n){if("string"!=typeof t)return u.errors=[{instancePath:l+"/auth/privateKey",schemaPath:"#/properties/auth/properties/privateKey/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!r.test(t))return u.errors=[{instancePath:l+"/auth/privateKey",schemaPath:"#/properties/auth/properties/privateKey/format",keyword:"format",params:{format:"hex-string"},message:'must match format "hex-string"'}],!1}y=n===g}else y=!0;if(y){const t=g;if("string"!=typeof e.keyType)return u.errors=[{instancePath:l+"/auth/keyType",schemaPath:"#/properties/auth/properties/keyType/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(y=t===g){if(void 0!==e.ethereum){let t=e.ethereum;const r=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/auth/ethereum",schemaPath:"#/properties/auth/properties/ethereum/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;y=r===g}else y=!0;if(y)if(void 0!==e.identity){let t=e.identity;const r=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/auth/identity",schemaPath:"#/properties/auth/properties/identity/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;y=r===g}else y=!0}}}}}}m=t===g}else m=!0;if(m){const h=g;if("boolean"!=typeof a.orderMessages)return u.errors=[{instancePath:l+"/orderMessages",schemaPath:"#/properties/orderMessages/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(m=h===g){const h=g;if("boolean"!=typeof a.gapFill)return u.errors=[{instancePath:l+"/gapFill",schemaPath:"#/properties/gapFill/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(m=h===g){let h=a.maxGapRequests;const d=g;if("number"!=typeof h||!isFinite(h))return u.errors=[{instancePath:l+"/maxGapRequests",schemaPath:"#/properties/maxGapRequests/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(m=d===g){let h=a.retryResendAfter;const d=g;if("number"!=typeof h||!isFinite(h))return u.errors=[{instancePath:l+"/retryResendAfter",schemaPath:"#/properties/retryResendAfter/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(m=d===g){let h=a.gapFillTimeout;const d=g;if("number"!=typeof h||!isFinite(h))return u.errors=[{instancePath:l+"/gapFillTimeout",schemaPath:"#/properties/gapFillTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(m=d===g){let h=a.gapFillStrategy;const d=g;if("string"!=typeof h)return u.errors=[{instancePath:l+"/gapFillStrategy",schemaPath:"#/properties/gapFillStrategy/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("light"!==h&&"full"!==h)return u.errors=[{instancePath:l+"/gapFillStrategy",schemaPath:"#/properties/gapFillStrategy/enum",keyword:"enum",params:{allowedValues:e.properties.gapFillStrategy.enum},message:"must be equal to one of the allowed values"}],!1;if(m=d===g){let h=a.network;const d=g;if(g===d){if(!h||"object"!=typeof h||Array.isArray(h))return u.errors=[{instancePath:l+"/network",schemaPath:"#/properties/network/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===h.controlLayer&&(h.controlLayer={}),void 0===h.node&&(h.node={});const r=g;for(const e in h)if("controlLayer"!==e&&"node"!==e)return u.errors=[{instancePath:l+"/network",schemaPath:"#/properties/network/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(r===g){let r=h.controlLayer;const s=g;if(g===s){if(!r||"object"!=typeof r||Array.isArray(r))return u.errors=[{instancePath:l+"/network/controlLayer",schemaPath:"#/properties/network/properties/controlLayer/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===r.entryPointDiscovery&&(r.entryPointDiscovery={enabled:!0,maxEntryPoints:5,maxQueryResults:50,maxHeartbeatAgeHours:24}),void 0===r.websocketPortRange&&(r.websocketPortRange={min:32200,max:32250}),void 0===r.maxConnections&&(r.maxConnections=80),void 0===r.iceServers&&(r.iceServers=[{url:"stun:stun.streamr.network",port:5349},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q=="},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q==",tcp:!0}]),void 0===r.webrtcAllowPrivateAddresses&&(r.webrtcAllowPrivateAddresses=!1),void 0===r.webrtcDatachannelBufferThresholdLow&&(r.webrtcDatachannelBufferThresholdLow=32768),void 0===r.webrtcDatachannelBufferThresholdHigh&&(r.webrtcDatachannelBufferThresholdHigh=131072),void 0===r.maxMessageSize&&(r.maxMessageSize=1048576),void 0===r.webrtcPortRange&&(r.webrtcPortRange={min:5e4,max:64e3}),void 0===r.networkConnectivityTimeout&&(r.networkConnectivityTimeout=1e4),void 0===r.websocketServerEnableTls&&(r.websocketServerEnableTls=!0),void 0===r.autoCertifierUrl&&(r.autoCertifierUrl="https://ns1.streamr-nodes.xyz:59833"),void 0===r.autoCertifierConfigFile&&(r.autoCertifierConfigFile="~/.streamr/certificate.json");const s=g;for(const n in r)if(!t.call(e.properties.network.properties.controlLayer.properties,n))return u.errors=[{instancePath:l+"/network/controlLayer",schemaPath:"#/properties/network/properties/controlLayer/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:n},message:"must NOT have additional properties"}],!1;if(s===g){if(void 0!==r.entryPoints){let e=r.entryPoints;const t=g;if(g===t){if(!Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/entryPoints",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPoints/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{const t=e.length;for(let r=0;r<t;r++){const t=g;if(c(e[r],{instancePath:l+"/network/controlLayer/entryPoints/"+r,parentData:e,parentDataProperty:r,rootData:f})||(p=null===p?c.errors:p.concat(c.errors),g=p.length),!(t===g))break}}}var b=t===g}else b=!0;if(b){let e=r.entryPointDiscovery;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{const t=g;for(const t in e)if("enabled"!==t&&"maxEntryPoints"!==t&&"maxQueryResults"!==t&&"maxHeartbeatAgeHours"!==t)return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.enabled){const t=g;if("boolean"!=typeof e.enabled)return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/enabled",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/enabled/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;var w=t===g}else w=!0;if(w){if(void 0!==e.maxEntryPoints){let t=e.maxEntryPoints;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/maxEntryPoints",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/maxEntryPoints/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;w=r===g}else w=!0;if(w){if(void 0!==e.maxQueryResults){let t=e.maxQueryResults;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/maxQueryResults",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/maxQueryResults/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;w=r===g}else w=!0;if(w)if(void 0!==e.maxHeartbeatAgeHours){let t=e.maxHeartbeatAgeHours;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/maxHeartbeatAgeHours",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/maxHeartbeatAgeHours/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;w=r===g}else w=!0}}}}}if(b=t===g){let e=r.websocketPortRange;const t=g,s=g;let o=!1;const a=g;if(null!==e){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketPortRange/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};null===p?p=[e]:p.push(e),g++}var v=a===g;if(o=o||v,!o){const t=g;if(g===g)if(e&&"object"==typeof e&&!Array.isArray(e)){let t;if(void 0===e.min&&(t="min")||void 0===e.max&&(t="max")){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/definitions/portRange/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"};null===p?p=[e]:p.push(e),g++}else{const t=g;for(const t in e)if("min"!==t&&"max"!==t){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/definitions/portRange/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"};null===p?p=[e]:p.push(e),g++;break}if(t===g){if(void 0!==e.min){let t=e.min;const r=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/network/controlLayer/websocketPortRange/min",schemaPath:"#/definitions/portRange/properties/min/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}var E=r===g}else E=!0;if(E)if(void 0!==e.max){let t=e.max;const r=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/network/controlLayer/websocketPortRange/max",schemaPath:"#/definitions/portRange/properties/max/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}E=r===g}else E=!0}}}else{const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/definitions/portRange/type",keyword:"type",params:{type:"object"},message:"must be object"};null===p?p=[e]:p.push(e),g++}v=t===g;o=o||v}if(!o){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketPortRange/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};return null===p?p=[e]:p.push(e),g++,u.errors=p,!1}if(g=s,null!==p&&(s?p.length=s:p=null),b=t===g){if(void 0!==r.websocketHost){let e=r.websocketHost;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/network/controlLayer/websocketHost",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketHost/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!n.test(e))return u.errors=[{instancePath:l+"/network/controlLayer/websocketHost",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketHost/format",keyword:"format",params:{format:"hostname"},message:'must match format "hostname"'}],!1}b=t===g}else b=!0;if(b){if(void 0!==r.peerDescriptor){const e=g;c(r.peerDescriptor,{instancePath:l+"/network/controlLayer/peerDescriptor",parentData:r,parentDataProperty:"peerDescriptor",rootData:f})||(p=null===p?c.errors:p.concat(c.errors),g=p.length);b=e===g}else b=!0;if(b){let e=r.maxConnections;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/maxConnections",schemaPath:"#/properties/network/properties/controlLayer/properties/maxConnections/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){if(void 0!==r.tlsCertificate){let e=r.tlsCertificate;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let t;if(void 0===e.certFileName&&(t="certFileName")||void 0===e.privateKeyFileName&&(t="privateKeyFileName"))return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"}],!1;{const t=g;for(const t in e)if("certFileName"!==t&&"privateKeyFileName"!==t)return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.certFileName){const t=g;if("string"!=typeof e.certFileName)return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate/certFileName",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/properties/certFileName/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var A=t===g}else A=!0;if(A)if(void 0!==e.privateKeyFileName){const t=g;if("string"!=typeof e.privateKeyFileName)return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate/privateKeyFileName",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/properties/privateKeyFileName/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;A=t===g}else A=!0}}}}b=t===g}else b=!0;if(b){let e=r.iceServers;const t=g;if(g===t){if(!Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{const t=e.length;for(let r=0;r<t;r++){let t=e[r];const n=g;if(g===n){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r,schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let e;if(void 0===t.url&&(e="url")||void 0===t.port&&(e="port"))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r,schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/required",keyword:"required",params:{missingProperty:e},message:"must have required property '"+e+"'"}],!1;{const e=g;for(const e in t)if("url"!==e&&"port"!==e&&"username"!==e&&"password"!==e&&"tcp"!==e)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r,schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){if(void 0!==t.url){const e=g;if("string"!=typeof t.url)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/url",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var S=e===g}else S=!0;if(S){if(void 0!==t.port){let e=t.port;const n=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/port",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/port/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;S=n===g}else S=!0;if(S){if(void 0!==t.username){const e=g;if("string"!=typeof t.username)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/username",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/username/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;S=e===g}else S=!0;if(S){if(void 0!==t.password){const e=g;if("string"!=typeof t.password)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/password",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/password/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;S=e===g}else S=!0;if(S)if(void 0!==t.tcp){const e=g;if("boolean"!=typeof t.tcp)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/tcp",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/tcp/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;S=e===g}else S=!0}}}}}}}if(!(n===g))break}}}if(b=t===g){const e=g;if("boolean"!=typeof r.webrtcAllowPrivateAddresses)return u.errors=[{instancePath:l+"/network/controlLayer/webrtcAllowPrivateAddresses",schemaPath:"#/properties/network/properties/controlLayer/properties/webrtcAllowPrivateAddresses/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(b=e===g){let e=r.webrtcDatachannelBufferThresholdLow;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcDatachannelBufferThresholdLow",schemaPath:"#/properties/network/properties/controlLayer/properties/webrtcDatachannelBufferThresholdLow/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){let e=r.webrtcDatachannelBufferThresholdHigh;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcDatachannelBufferThresholdHigh",schemaPath:"#/properties/network/properties/controlLayer/properties/webrtcDatachannelBufferThresholdHigh/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){let e=r.maxMessageSize;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/maxMessageSize",schemaPath:"#/properties/network/properties/controlLayer/properties/maxMessageSize/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){if(void 0!==r.externalIp){let e=r.externalIp;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/network/controlLayer/externalIp",schemaPath:"#/properties/network/properties/controlLayer/properties/externalIp/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!i.test(e))return u.errors=[{instancePath:l+"/network/controlLayer/externalIp",schemaPath:"#/properties/network/properties/controlLayer/properties/externalIp/format",keyword:"format",params:{format:"ipv4"},message:'must match format "ipv4"'}],!1}b=t===g}else b=!0;if(b){let e=r.webrtcPortRange;const t=g;if(g===g){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange",schemaPath:"#/definitions/portRange/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let t;if(void 0===e.min&&(t="min")||void 0===e.max&&(t="max"))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange",schemaPath:"#/definitions/portRange/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"}],!1;{const t=g;for(const t in e)if("min"!==t&&"max"!==t)return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange",schemaPath:"#/definitions/portRange/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.min){let t=e.min;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange/min",schemaPath:"#/definitions/portRange/properties/min/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;var k=r===g}else k=!0;if(k)if(void 0!==e.max){let t=e.max;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange/max",schemaPath:"#/definitions/portRange/properties/max/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;k=r===g}else k=!0}}}}if(b=t===g){let e=r.networkConnectivityTimeout;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/networkConnectivityTimeout",schemaPath:"#/properties/network/properties/controlLayer/properties/networkConnectivityTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){const e=g;if("boolean"!=typeof r.websocketServerEnableTls)return u.errors=[{instancePath:l+"/network/controlLayer/websocketServerEnableTls",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketServerEnableTls/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(b=e===g){const e=g;if("string"!=typeof r.autoCertifierUrl)return u.errors=[{instancePath:l+"/network/controlLayer/autoCertifierUrl",schemaPath:"#/properties/network/properties/controlLayer/properties/autoCertifierUrl/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(b=e===g){const e=g;if("string"!=typeof r.autoCertifierConfigFile)return u.errors=[{instancePath:l+"/network/controlLayer/autoCertifierConfigFile",schemaPath:"#/properties/network/properties/controlLayer/properties/autoCertifierConfigFile/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(b=e===g)if(void 0!==r.geoIpDatabaseFolder){const e=g;if("string"!=typeof r.geoIpDatabaseFolder)return u.errors=[{instancePath:l+"/network/controlLayer/geoIpDatabaseFolder",schemaPath:"#/properties/network/properties/controlLayer/properties/geoIpDatabaseFolder/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;b=e===g}else b=!0}}}}}}}}}}}}}}}}}}}}if(s===g){let e=h.node;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/node",schemaPath:"#/properties/network/properties/node/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.streamPartitionNeighborTargetCount&&(e.streamPartitionNeighborTargetCount=4),void 0===e.streamPartitionMinPropagationTargets&&(e.streamPartitionMinPropagationTargets=2),void 0===e.streamPartitionMaxPropagationBufferSize&&(e.streamPartitionMaxPropagationBufferSize=150),void 0===e.contentDeliveryBufferWhileConnecting&&(e.contentDeliveryBufferWhileConnecting=!0),void 0===e.acceptProxyConnections&&(e.acceptProxyConnections=!1);const t=g;for(const t in e)if("streamPartitionNeighborTargetCount"!==t&&"streamPartitionMinPropagationTargets"!==t&&"streamPartitionMaxPropagationBufferSize"!==t&&"contentDeliveryBufferWhileConnecting"!==t&&"acceptProxyConnections"!==t)return u.errors=[{instancePath:l+"/network/node",schemaPath:"#/properties/network/properties/node/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.streamPartitionNeighborTargetCount;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/node/streamPartitionNeighborTargetCount",schemaPath:"#/properties/network/properties/node/properties/streamPartitionNeighborTargetCount/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let t=e.streamPartitionMinPropagationTargets;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/node/streamPartitionMinPropagationTargets",schemaPath:"#/properties/network/properties/node/properties/streamPartitionMinPropagationTargets/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let t=e.streamPartitionMaxPropagationBufferSize;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/node/streamPartitionMaxPropagationBufferSize",schemaPath:"#/properties/network/properties/node/properties/streamPartitionMaxPropagationBufferSize/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){const t=g;if("boolean"!=typeof e.contentDeliveryBufferWhileConnecting)return u.errors=[{instancePath:l+"/network/node/contentDeliveryBufferWhileConnecting",schemaPath:"#/properties/network/properties/node/properties/contentDeliveryBufferWhileConnecting/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){if("boolean"!=typeof e.acceptProxyConnections)return u.errors=[{instancePath:l+"/network/node/acceptProxyConnections",schemaPath:"#/properties/network/properties/node/properties/acceptProxyConnections/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1}}}}}}}}}}}if(m=d===g){let n=a.contracts;const i=g;if(g===i){if(!n||"object"!=typeof n||Array.isArray(n))return u.errors=[{instancePath:l+"/contracts",schemaPath:"#/properties/contracts/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===n.ethereumNetwork&&(n.ethereumNetwork={}),void 0===n.rpcQuorum&&(n.rpcQuorum=2),void 0===n.maxConcurrentCalls&&(n.maxConcurrentCalls=10),void 0===n.pollInterval&&(n.pollInterval=4e3);const r=g;for(const r in n)if(!t.call(e.properties.contracts.properties,r))return u.errors=[{instancePath:l+"/contracts",schemaPath:"#/properties/contracts/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"}],!1;if(r===g){let e=n.ethereumNetwork;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/contracts/ethereumNetwork",schemaPath:"#/properties/contracts/properties/ethereumNetwork/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{const t=g;for(const t in e)if("chainId"!==t&&"overrides"!==t&&"highGasPriceStrategy"!==t)return u.errors=[{instancePath:l+"/contracts/ethereumNetwork",schemaPath:"#/properties/contracts/properties/ethereumNetwork/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.chainId){let t=e.chainId;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/contracts/ethereumNetwork/chainId",schemaPath:"#/properties/contracts/properties/ethereumNetwork/properties/chainId/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;var R=r===g}else R=!0;if(R){if(void 0!==e.overrides){let t=e.overrides;const r=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/contracts/ethereumNetwork/overrides",schemaPath:"#/properties/contracts/properties/ethereumNetwork/properties/overrides/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;R=r===g}else R=!0;if(R)if(void 0!==e.highGasPriceStrategy){const t=g;if("boolean"!=typeof e.highGasPriceStrategy)return u.errors=[{instancePath:l+"/contracts/ethereumNetwork/highGasPriceStrategy",schemaPath:"#/properties/contracts/properties/ethereumNetwork/properties/highGasPriceStrategy/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;R=t===g}else R=!0}}}}if(C=t===g){if(void 0!==n.streamRegistryChainAddress){let e=n.streamRegistryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/streamRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamRegistryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/streamRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamRegistryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}var C=t===g}else C=!0;if(C){if(void 0!==n.streamStorageRegistryChainAddress){let e=n.streamStorageRegistryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/streamStorageRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamStorageRegistryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/streamStorageRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamStorageRegistryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}C=t===g}else C=!0;if(C){if(void 0!==n.storageNodeRegistryChainAddress){let e=n.storageNodeRegistryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/storageNodeRegistryChainAddress",schemaPath:"#/properties/contracts/properties/storageNodeRegistryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/storageNodeRegistryChainAddress",schemaPath:"#/properties/contracts/properties/storageNodeRegistryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}C=t===g}else C=!0;if(C){if(void 0!==n.sponsorshipFactoryChainAddress){let e=n.sponsorshipFactoryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/sponsorshipFactoryChainAddress",schemaPath:"#/properties/contracts/properties/sponsorshipFactoryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/sponsorshipFactoryChainAddress",schemaPath:"#/properties/contracts/properties/sponsorshipFactoryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}C=t===g}else C=!0;if(C){if(void 0!==n.rpcs){let e=n.rpcs;const t=g;if(g===t){if(!Array.isArray(e))return u.errors=[{instancePath:l+"/contracts/rpcs",schemaPath:"#/properties/contracts/properties/rpcs/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;if(e.length<1)return u.errors=[{instancePath:l+"/contracts/rpcs",schemaPath:"#/properties/contracts/properties/rpcs/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"}],!1;{const t=e.length;for(let r=0;r<t;r++){let t=e[r];const n=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r,schemaPath:"#/properties/contracts/properties/rpcs/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;if(g===g){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r,schemaPath:"#/definitions/rpcProviderConfig/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let e;if(void 0===t.url&&(e="url"))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r,schemaPath:"#/definitions/rpcProviderConfig/required",keyword:"required",params:{missingProperty:e},message:"must have required property '"+e+"'"}],!1;if(void 0!==t.url){let e=t.url;if(g===g&&g===g){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/rpcs/"+r+"/url",schemaPath:"#/definitions/rpcProviderConfig/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!o.test(e))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r+"/url",schemaPath:"#/definitions/rpcProviderConfig/properties/url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'}],!1}}}}if(!(n===g))break}}}C=t===g}else C=!0;if(C){let e=n.rpcQuorum;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/contracts/rpcQuorum",schemaPath:"#/properties/contracts/properties/rpcQuorum/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(C=t===g){if(void 0!==n.theGraphUrl){let e=n.theGraphUrl;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/theGraphUrl",schemaPath:"#/properties/contracts/properties/theGraphUrl/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!o.test(e))return u.errors=[{instancePath:l+"/contracts/theGraphUrl",schemaPath:"#/properties/contracts/properties/theGraphUrl/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'}],!1}C=t===g}else C=!0;if(C){let e=n.maxConcurrentCalls;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/contracts/maxConcurrentCalls",schemaPath:"#/properties/contracts/properties/maxConcurrentCalls/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(C=t===g){let e=n.pollInterval;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/contracts/pollInterval",schemaPath:"#/properties/contracts/properties/pollInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;C=t===g}}}}}}}}}}}}if(m=i===g){let e=a.encryption;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/encryption",schemaPath:"#/properties/encryption/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.keyRequestTimeout&&(e.keyRequestTimeout=3e4),void 0===e.maxKeyRequestsPerSecond&&(e.maxKeyRequestsPerSecond=20),void 0===e.rsaKeyLength&&(e.rsaKeyLength=4096),void 0===e.requireQuantumResistantKeyExchange&&(e.requireQuantumResistantKeyExchange=!1),void 0===e.requireQuantumResistantSignatures&&(e.requireQuantumResistantSignatures=!1),void 0===e.requireQuantumResistantEncryption&&(e.requireQuantumResistantEncryption=!1);const t=g;for(const t in e)if("keyRequestTimeout"!==t&&"maxKeyRequestsPerSecond"!==t&&"rsaKeyLength"!==t&&"requireQuantumResistantKeyExchange"!==t&&"requireQuantumResistantSignatures"!==t&&"requireQuantumResistantEncryption"!==t&&"keys"!==t)return u.errors=[{instancePath:l+"/encryption",schemaPath:"#/properties/encryption/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.keyRequestTimeout;const n=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/encryption/keyRequestTimeout",schemaPath:"#/properties/encryption/properties/keyRequestTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(n===g){let t=e.maxKeyRequestsPerSecond;const n=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/encryption/maxKeyRequestsPerSecond",schemaPath:"#/properties/encryption/properties/maxKeyRequestsPerSecond/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(n===g){let t=e.rsaKeyLength;const n=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/encryption/rsaKeyLength",schemaPath:"#/properties/encryption/properties/rsaKeyLength/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(n===g){const t=g;if("boolean"!=typeof e.requireQuantumResistantKeyExchange)return u.errors=[{instancePath:l+"/encryption/requireQuantumResistantKeyExchange",schemaPath:"#/properties/encryption/properties/requireQuantumResistantKeyExchange/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){const t=g;if("boolean"!=typeof e.requireQuantumResistantSignatures)return u.errors=[{instancePath:l+"/encryption/requireQuantumResistantSignatures",schemaPath:"#/properties/encryption/properties/requireQuantumResistantSignatures/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){const t=g;if("boolean"!=typeof e.requireQuantumResistantEncryption)return u.errors=[{instancePath:l+"/encryption/requireQuantumResistantEncryption",schemaPath:"#/properties/encryption/properties/requireQuantumResistantEncryption/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g)if(void 0!==e.keys){let t=e.keys;const n=g;if(g===n){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/encryption/keys",schemaPath:"#/properties/encryption/properties/keys/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;for(const e in t){const t=g;if("string"!=typeof e){const t={instancePath:l+"/encryption/keys",schemaPath:"#/definitions/streamIdOrPath/type",keyword:"type",params:{type:"string"},message:"must be string",propertyName:e};null===p?p=[t]:p.push(t),g++}var I=t===g;if(!I){const t={instancePath:l+"/encryption/keys",schemaPath:"#/properties/encryption/properties/keys/propertyNames",keyword:"propertyNames",params:{propertyName:e},message:"property name must be valid"};return null===p?p=[t]:p.push(t),g++,u.errors=p,!1}}if(I)for(const e in t){let n=t[e];const i=g;if(g===g){if(!n||"object"!=typeof n||Array.isArray(n))return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/definitions/encryptionKey/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let t;if(void 0===n.id&&(t="id")||void 0===n.data&&(t="data"))return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/definitions/encryptionKey/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"}],!1;if(void 0!==n.id){const t=g;if("string"!=typeof n.id)return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/id",schemaPath:"#/definitions/encryptionKey/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var P=t===g}else P=!0;if(P)if(void 0!==n.data){let t=n.data;const i=g;if(g===i&&g===i){if("string"!=typeof t)return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/data",schemaPath:"#/definitions/encryptionKey/properties/data/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!r.test(t))return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/data",schemaPath:"#/definitions/encryptionKey/properties/data/format",keyword:"format",params:{format:"hex-string"},message:'must match format "hex-string"'}],!1}P=i===g}else P=!0}}if(!(i===g))break}}}else;}}}}}}}}if(m=t===g){let e=a.validation;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/validation",schemaPath:"#/properties/validation/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.permissions&&(e.permissions=!0),void 0===e.partitions&&(e.partitions=!0);const t=g;for(const t in e)if("permissions"!==t&&"partitions"!==t)return u.errors=[{instancePath:l+"/validation",schemaPath:"#/properties/validation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){const t=g;if("boolean"!=typeof e.permissions)return u.errors=[{instancePath:l+"/validation/permissions",schemaPath:"#/properties/validation/properties/permissions/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){if("boolean"!=typeof e.partitions)return u.errors=[{instancePath:l+"/validation/partitions",schemaPath:"#/properties/validation/properties/partitions/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1}}}}if(m=t===g){if(void 0!==a.metrics){let e=a.metrics;const t=g,r=g;let n=!1;const i=g;if("boolean"!=typeof e){const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf/0/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};null===p?p=[e]:p.push(e),g++}var T=i===g;if(n=n||T,!n){const t=g;if(g===t)if(e&&"object"==typeof e&&!Array.isArray(e)){const t=g;for(const t in e)if("periods"!==t&&"maxPublishDelay"!==t){const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"};null===p?p=[e]:p.push(e),g++;break}if(t===g){if(void 0!==e.periods){let t=e.periods;const r=g;if(g===r)if(Array.isArray(t)){const e=t.length;for(let r=0;r<e;r++){let e=t[r];const n=g;if(g===n)if(e&&"object"==typeof e&&!Array.isArray(e)){let t;if(void 0===e.streamId&&(t="streamId")||void 0===e.duration&&(t="duration")){const e={instancePath:l+"/metrics/periods/"+r,schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"};null===p?p=[e]:p.push(e),g++}else{if(void 0!==e.id){const t=g;if("string"!=typeof e.id){const e={instancePath:l+"/metrics/periods/"+r+"/id",schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};null===p?p=[e]:p.push(e),g++}var _=t===g}else _=!0;if(_)if(void 0!==e.duration){let t=e.duration;const n=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/metrics/periods/"+r+"/duration",schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/properties/duration/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}_=n===g}else _=!0}}else{const e={instancePath:l+"/metrics/periods/"+r,schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/type",keyword:"type",params:{type:"object"},message:"must be object"};null===p?p=[e]:p.push(e),g++}if(!(n===g))break}}else{const e={instancePath:l+"/metrics/periods",schemaPath:"#/properties/metrics/anyOf/1/properties/periods/type",keyword:"type",params:{type:"array"},message:"must be array"};null===p?p=[e]:p.push(e),g++}var N=r===g}else N=!0;if(N)if(void 0!==e.maxPublishDelay){let t=e.maxPublishDelay;const r=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/metrics/maxPublishDelay",schemaPath:"#/properties/metrics/anyOf/1/properties/maxPublishDelay/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}N=r===g}else N=!0}}else{const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};null===p?p=[e]:p.push(e),g++}T=t===g;n=n||T}if(!n){const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};return null===p?p=[e]:p.push(e),g++,u.errors=p,!1}g=r,null!==p&&(r?p.length=r:p=null);m=t===g}else m=!0;if(m){let e=a.cache;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/cache",schemaPath:"#/properties/cache/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.maxSize&&(e.maxSize=1e4),void 0===e.maxAge&&(e.maxAge=864e5);const t=g;for(const t in e)if("maxSize"!==t&&"maxAge"!==t)return u.errors=[{instancePath:l+"/cache",schemaPath:"#/properties/cache/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.maxSize;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/cache/maxSize",schemaPath:"#/properties/cache/properties/maxSize/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let t=e.maxAge;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/cache/maxAge",schemaPath:"#/properties/cache/properties/maxAge/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}if(m=t===g){let e=a._timeouts;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/_timeouts",schemaPath:"#/properties/_timeouts/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.theGraph&&(e.theGraph={}),void 0===e.storageNode&&(e.storageNode={}),void 0===e.ensStreamCreation&&(e.ensStreamCreation={}),void 0===e.jsonRpcTimeout&&(e.jsonRpcTimeout=3e4);const t=g;for(const t in e)if("theGraph"!==t&&"storageNode"!==t&&"ensStreamCreation"!==t&&"jsonRpcTimeout"!==t)return u.errors=[{instancePath:l+"/_timeouts",schemaPath:"#/properties/_timeouts/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.theGraph;const r=g;if(g===r){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/_timeouts/theGraph",schemaPath:"#/properties/_timeouts/properties/theGraph/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===t.indexTimeout&&(t.indexTimeout=6e4),void 0===t.indexPollInterval&&(t.indexPollInterval=1e3),void 0===t.fetchTimeout&&(t.fetchTimeout=3e4);const e=g;for(const e in t)if("indexTimeout"!==e&&"indexPollInterval"!==e&&"fetchTimeout"!==e)return u.errors=[{instancePath:l+"/_timeouts/theGraph",schemaPath:"#/properties/_timeouts/properties/theGraph/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){let e=t.indexTimeout;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/theGraph/indexTimeout",schemaPath:"#/properties/_timeouts/properties/theGraph/properties/indexTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.indexPollInterval;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/theGraph/indexPollInterval",schemaPath:"#/properties/_timeouts/properties/theGraph/properties/indexPollInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.fetchTimeout;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/theGraph/fetchTimeout",schemaPath:"#/properties/_timeouts/properties/theGraph/properties/fetchTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}}if(r===g){let t=e.storageNode;const r=g;if(g===r){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/_timeouts/storageNode",schemaPath:"#/properties/_timeouts/properties/storageNode/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===t.timeout&&(t.timeout=3e4),void 0===t.retryInterval&&(t.retryInterval=1e3);const e=g;for(const e in t)if("timeout"!==e&&"retryInterval"!==e)return u.errors=[{instancePath:l+"/_timeouts/storageNode",schemaPath:"#/properties/_timeouts/properties/storageNode/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){let e=t.timeout;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/storageNode/timeout",schemaPath:"#/properties/_timeouts/properties/storageNode/properties/timeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.retryInterval;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/storageNode/retryInterval",schemaPath:"#/properties/_timeouts/properties/storageNode/properties/retryInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}if(r===g){let t=e.ensStreamCreation;const r=g;if(g===r){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===t.timeout&&(t.timeout=18e4),void 0===t.retryInterval&&(t.retryInterval=1e3);const e=g;for(const e in t)if("timeout"!==e&&"retryInterval"!==e)return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){let e=t.timeout;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation/timeout",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/properties/timeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.retryInterval;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation/retryInterval",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/properties/retryInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}if(r===g){let t=e.jsonRpcTimeout;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/_timeouts/jsonRpcTimeout",schemaPath:"#/properties/_timeouts/properties/jsonRpcTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}}}m=t===g}}}}}}}}}}}}}}}}}}}return u.errors=p,0===g}return p1.exports}(),m1=n(g1);const y1={network:{controlLayer:{entryPointDiscovery:{enabled:!1},websocketPortRange:{min:32400,max:32800},iceServers:[],webrtcAllowPrivateAddresses:!0,websocketServerEnableTls:!1}},encryption:{rsaKeyLength:640},_timeouts:{theGraph:{indexTimeout:1e4,indexPollInterval:500},storageNode:{timeout:3e4,retryInterval:500},ensStreamCreation:{timeout:2e4,retryInterval:500}},metrics:!1};nb("0xde1112f631486CfC759A50196853011528bC5FA0");const b1=(e={})=>{let t=f1(e);const r=t.environment??aA;t=w1(r,t);const n=v1(t);return n.id??=bW("undefined"!=typeof process&&process.pid?`${process.pid}`:Wv(4),"/"),n},w1=(e,t)=>{const r=ZO.config[e];let n=aE({environment:e,network:{controlLayer:{entryPoints:r.entryPoints}},contracts:{ethereumNetwork:{chainId:r.id},streamRegistryChainAddress:r.contracts.StreamRegistry,streamStorageRegistryChainAddress:r.contracts.StreamStorageRegistry,storageNodeRegistryChainAddress:r.contracts.StorageNodeRegistry,sponsorshipFactoryChainAddress:r.contracts.SponsorshipFactory,rpcs:r.rpcEndpoints,theGraphUrl:r.theGraphUrl}},t);return"polygon"===e?n.contracts.ethereumNetwork={highGasPriceStrategy:!0,...n.contracts.ethereumNetwork}:"dev2"===e&&(n=aE(y1,n)),n},v1=e=>{if(!m1(e))throw new Error(m1.errors.map((e=>{let t=e.instancePath+" "+e.message;return e.params.additionalProperty&&(t+=`: ${e.params.additionalProperty}`),t})).join("\n"));return e},E1={...Object.fromEntries(LX.map((e=>[e.signatureType,e.keyType]))),[e.SignatureType.ECDSA_SECP256K1_LEGACY]:"ECDSA_SECP256K1_LEGACY",[e.SignatureType.ERC_1271]:"ERC_1271"};function A1(e){const t=E1[e];if(!t)throw new Error(`Unknown signature type: ${e}`);return t}const S1=e=>({content:e.getParsedContent(),streamId:e.getStreamId(),streamPartition:e.getStreamPartition(),timestamp:e.getTimestamp(),sequenceNumber:e.getSequenceNumber(),signature:e.signature,signatureType:A1(e.signatureType),publisherId:e.getPublisherId(),msgChainId:e.getMsgChainId(),encryptionKeyId:e.groupKeyId,streamMessage:e});var k1=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},R1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},C1=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const I1={periods:[{duration:6e4,streamId:"streamr.eth/metrics/nodes/firehose/min"},{duration:36e5,streamId:"streamr.eth/metrics/nodes/firehose/hour"},{duration:864e5,streamId:"streamr.eth/metrics/nodes/firehose/day"}],maxPublishDelay:3e4};let P1=class{publisher;node;config;eventEmitter;destroySignal;constructor(e,t,r,n,i){this.publisher=e,this.node=t,this.config=(e=>{if(!0===e.metrics)return I1;if(!1===e.metrics)return{...I1,periods:[]};if(void 0!==e.metrics)return aE(I1,e.metrics);{const t=void 0!==e.auth?.ethereum;return{...I1,periods:t?[]:I1.periods}}})(r),this.eventEmitter=n,this.destroySignal=i;const s=_W((async()=>{const e=await this.node.getMetricsContext(),t=await this.node.getNodeId();this.config.periods.forEach((r=>{e.createReportProducer((async e=>{await this.publish(e,r.streamId,t)}),r.duration,this.destroySignal.abortSignal)}))}));this.config.periods.length>0&&(this.eventEmitter.on("messagePublished",(()=>s())),this.eventEmitter.on("streamPartSubscribed",(()=>s())))}async publish(e,t,r){await Qv(Math.random()*this.config.maxPublishDelay);const n={...e,node:{...e.node,id:r}};try{await this.publisher.publish(t,n,{timestamp:e.period.end,partitionKey:r})}catch(e){console.warn(`Unable to publish metrics: ${e.message}`)}}};P1=k1([q(d.ContainerScoped),C1(2,U(cA)),R1("design:paramtypes",[u1,yX,Object,sD,UW])],P1);var T1=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},_1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let N1=class{streamIdBuilder;operatorRegistry;node;logger;constructor(e,t,r,n){this.streamIdBuilder=e,this.operatorRegistry=t,this.node=r,this.logger=n.createLogger("ProxyNodeFinder")}async find(e,t=1,r=100,n=24){const[i,s]=await this.streamIdBuilder.toStreamPartElements(e);this.logger.debug(`Trying to find ${t} proxy nodes for stream ${i} partition ${s}`);const o=await this.operatorRegistry.findOperatorsOnStream(i,r,n);if(this.logger.debug(`Found ${o.length} operators on stream ${i}`),o.length<t)throw new Error(`Not enough operators found for stream ${i}: found ${o.length} operators, but ${t} are required`);const a=PU(o),c=[];let u=()=>{};const l=new Promise((e=>{u=e}));let h=0;const d=async e=>{for(;h<a.length&&c.length<t;){const r=a[h];h++;const n=EE(i,s??0);try{const i=await this.node.discoverOperators(r.peerDescriptor,n);i.length>0?c.length<t&&(this.logger.debug(`(worker ${e}): found ${i.length} nodes for operator ${r.operatorId} and streamPartId ${n}`),c.push(oA(i)),c.length>=t&&u()):this.logger.debug(`(worker ${e}): no nodes found for operator ${r.operatorId} and streamPartId ${n}`)}catch(t){this.logger.error(`(worker ${e}): error discovering nodes for operator ${r.operatorId}: ${t.message}`)}}};if(await Promise.race([Promise.all(Array.from({length:t},((e,t)=>d(t)))),l]),c.length<t)throw new Error(`Not enough proxy nodes were resolved for stream ${i}: found ${c.length} nodes, but ${t} are required`);return c}};var M1,x1;N1=T1([q(d.ContainerScoped),_1("design:paramtypes",[YW,dY,yX,uD])],N1);var O1,D1,B1,L1,F1,U1,j1=n(function(){if(x1)return M1;x1=1;var e=De(),t=Be();return M1=function(r){return"number"==typeof r||t(r)&&"[object Number]"==e(r)}}());function q1(){if(L1)return B1;L1=1;var e=function(){if(D1)return O1;D1=1;var e=Math.ceil,t=Math.max;return O1=function(r,n,i,s){for(var o=-1,a=t(e((n-r)/(i||1)),0),c=Array(a);a--;)c[s?a:++o]=r,r+=i;return c}}(),t=_d(),r=Fe();return B1=function(n){return function(i,s,o){return o&&"number"!=typeof o&&t(i,s,o)&&(s=o=void 0),i=r(i),void 0===s?(s=i,i=0):s=r(s),o=void 0===o?i<s?1:-1:r(o),e(i,s,o,n)}}}var z1=function(){if(U1)return F1;U1=1;var e=q1()();return F1=e}(),K1=n(z1);class G1{id;client;constructor(e,t){this.id=e,this.client=t}publish(e,t){return this.client.publish(this.id,e,t)}async hasPermission(e){return this.client.hasPermission({streamId:this.id,...e})}async getPermissions(){return this.client.getPermissions(this.id)}async grantPermissions(...e){return this.client.grantPermissions(this.id,...e.map(iJ))}async revokePermissions(...e){return this.client.revokePermissions(this.id,...e.map(iJ))}async addToStorageNode(e,t={wait:!1}){await this.client.addStreamToStorageNode(this.id,e,t)}async removeFromStorageNode(e){return this.client.removeStreamFromStorageNode(this.id,nb(e))}async getStorageNodes(){return this.client.getStorageNodes(this.id)}async getStreamParts(){return K1(0,await this.getPartitionCount()).map((e=>EE(this.id,e)))}async getPartitionCount(){return eJ(await this.getMetadata())}async getDescription(){const e=(await this.getMetadata()).description;return n1(e)?e:void 0}async setDescription(e){await this.setMetadata({...await this.getMetadata(),description:e})}async getStorageDayCount(){const e=(await this.getMetadata()).storageDays;return j1(e)?e:void 0}async setStorageDayCount(e){await this.setMetadata({...await this.getMetadata(),storageDays:e})}async getMetadata(){return this.client.getStreamMetadata(this.id)}async setMetadata(e){await this.client.setStreamMetadata(this.id,e)}}function V1(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:o,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);const i=o.prototype,s=Object.keys(i);for(let e=0;e<s.length;e++){const t=s[e];t in r||(r[t]=i[t].bind(r))}}const i=r?.Parent??Object;class s extends i{}function o(e){var t;const i=r?.Parent?new s:this;n(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(s,"name",{value:e}),Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}class H1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class $1 extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const W1={};function J1(e){return W1}function Q1(e,t){return"bigint"==typeof t?t.toString():t}function Z1(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Y1(e){return null==e}function X1(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const e2=Symbol("evaluating");function t2(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==e2)return void 0===n&&(n=e2,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function r2(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function n2(...e){const t={};for(const r of e){const e=Object.getOwnPropertyDescriptors(r);Object.assign(t,e)}return Object.defineProperties({},t)}function i2(e){return JSON.stringify(e)}const s2="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function o2(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const a2=Z1((()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}}));function c2(e){if(!1===o2(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const r=t.prototype;return!1!==o2(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function u2(e){return c2(e)?{...e}:Array.isArray(e)?[...e]:e}const l2=new Set(["string","number","symbol"]);function h2(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function d2(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const f2={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function p2(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function g2(e,t){return t.map((t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t}))}function m2(e){return"string"==typeof e?e:e?.message}function y2(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const i=m2(e.inst?._zod.def?.error?.(e))??m2(t?.error?.(e))??m2(r.customError?.(e))??m2(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function b2(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function w2(...e){const[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}const v2=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Q1,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},E2=V1("$ZodError",v2),A2=V1("$ZodError",v2,{Parent:Error});const S2=e=>(t,r,n,i)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new H1;if(o.issues.length){const t=new(i?.Err??e)(o.issues.map((e=>y2(e,s,J1()))));throw s2(t,i?.callee),t}return o.value},k2=e=>async(t,r,n,i)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const t=new(i?.Err??e)(o.issues.map((e=>y2(e,s,J1()))));throw s2(t,i?.callee),t}return o.value},R2=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new H1;return s.issues.length?{success:!1,error:new(e??E2)(s.issues.map((e=>y2(e,i,J1()))))}:{success:!0,data:s.value}},C2=R2(A2),I2=e=>async(t,r,n)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map((e=>y2(e,i,J1()))))}:{success:!0,data:s.value}},P2=I2(A2),T2=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return S2(e)(t,r,i)},_2=e=>(t,r,n)=>S2(e)(t,r,n),N2=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return k2(e)(t,r,i)},M2=e=>async(t,r,n)=>k2(e)(t,r,n),x2=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return R2(e)(t,r,i)},O2=e=>(t,r,n)=>R2(e)(t,r,n),D2=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return I2(e)(t,r,i)},B2=e=>async(t,r,n)=>I2(e)(t,r,n),L2=/^-?\d+$/,F2=/^-?\d+(?:\.\d+)?/,U2=V1("$ZodCheck",((e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])})),j2={number:"number",bigint:"bigint",object:"date"},q2=V1("$ZodCheckLessThan",((e,t)=>{U2.init(e,t);const r=j2[typeof t.value];e._zod.onattach.push((e=>{const r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)})),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),z2=V1("$ZodCheckGreaterThan",((e,t)=>{U2.init(e,t);const r=j2[typeof t.value];e._zod.onattach.push((e=>{const r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)})),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),K2=V1("$ZodCheckMultipleOf",((e,t)=>{U2.init(e,t),e._zod.onattach.push((e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)})),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===function(e,t){const r=(e.toString().split(".")[1]||"").length,n=t.toString();let i=(n.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(n)){const e=n.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}const s=r>i?r:i;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}})),G2=V1("$ZodCheckNumberFormat",((e,t)=>{U2.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=f2[t.format];e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=s,r&&(n.pattern=L2)})),e._zod.check=o=>{const a=o.value;if(r){if(!Number.isInteger(a))return void o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}))}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}})),V2=V1("$ZodCheckMaxLength",((e,t)=>{var r;U2.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Y1(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=r=>{const n=r.value;if(n.length<=t.maximum)return;const i=b2(n);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}})),H2=V1("$ZodCheckMinLength",((e,t)=>{var r;U2.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Y1(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const i=b2(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}})),$2=V1("$ZodCheckLengthEquals",((e,t)=>{var r;U2.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Y1(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length})),e._zod.check=r=>{const n=r.value,i=n.length;if(i===t.length)return;const s=b2(n),o=i>t.length;r.issues.push({origin:s,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}})),W2=V1("$ZodCheckOverwrite",((e,t)=>{U2.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}));class J2{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter((e=>e)),r=Math.min(...t.map((e=>e.length-e.trimStart().length))),n=t.map((e=>e.slice(r))).map((e=>" ".repeat(2*this.indent)+e));for(const e of n)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map((e=>` ${e}`))].join("\n"))}}const Q2={major:4,minor:1,patch:13},Z2=V1("$ZodType",((e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Q2;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push((()=>{e._zod.run=e._zod.parse}));else{const t=(e,t,r)=>{let n,i=p2(e);for(const s of t){if(s._zod.def.when){if(!s._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,o=s._zod.check(e);if(o instanceof Promise&&!1===r?.async)throw new H1;if(n||o instanceof Promise)n=(n??Promise.resolve()).then((async()=>{await o;e.issues.length!==t&&(i||(i=p2(e,t)))}));else{if(e.issues.length===t)continue;i||(i=p2(e,t))}}return n?n.then((()=>e)):e},r=(r,i,s)=>{if(p2(r))return r.aborted=!0,r;const o=t(i,n,s);if(o instanceof Promise){if(!1===s.async)throw new H1;return o.then((t=>e._zod.parse(t,s)))}return e._zod.parse(o,s)};e._zod.run=(i,s)=>{if(s.skipChecks)return e._zod.parse(i,s);if("backward"===s.direction){const t=e._zod.parse({value:i.value,issues:[]},{...s,skipChecks:!0});return t instanceof Promise?t.then((e=>r(e,i,s))):r(t,i,s)}const o=e._zod.parse(i,s);if(o instanceof Promise){if(!1===s.async)throw new H1;return o.then((e=>t(e,n,s)))}return t(o,n,s)}}e["~standard"]={validate:t=>{try{const r=C2(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return P2(e,t).then((e=>e.success?{value:e.data}:{issues:e.error?.issues}))}},vendor:"zod",version:1}})),Y2=V1("$ZodNumber",((e,t)=>{Z2.init(e,t),e._zod.pattern=e._zod.bag.pattern??F2,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;const s="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}})),X2=V1("$ZodNumberFormat",((e,t)=>{G2.init(e,t),Y2.init(e,t)})),e3=V1("$ZodUnknown",((e,t)=>{Z2.init(e,t),e._zod.parse=e=>e})),t3=V1("$ZodNever",((e,t)=>{Z2.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}));function r3(e,t,r){e.issues.length&&t.issues.push(...g2(r,e.issues)),t.value[r]=e.value}const n3=V1("$ZodArray",((e,t)=>{Z2.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const s=[];for(let e=0;e<i.length;e++){const o=i[e],a=t.element._zod.run({value:o,issues:[]},n);a instanceof Promise?s.push(a.then((t=>r3(t,r,e)))):r3(a,r,e)}return s.length?Promise.all(s).then((()=>r)):r}}));function i3(e,t,r,n){e.issues.length&&t.issues.push(...g2(r,e.issues)),void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function s3(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=(n=e.shape,Object.keys(n).filter((e=>"optional"===n[e]._zod.optin&&"optional"===n[e]._zod.optout)));var n;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function o3(e,t,r,n,i,s){const o=[],a=i.keySet,c=i.catchall._zod,u=c.def.type;for(const i in t){if(a.has(i))continue;if("never"===u){o.push(i);continue}const s=c.run({value:t[i],issues:[]},n);s instanceof Promise?e.push(s.then((e=>i3(e,r,i,t)))):i3(s,r,i,t)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s}),e.length?Promise.all(e).then((()=>r)):r}const a3=V1("$ZodObject",((e,t)=>{Z2.init(e,t);const r=Object.getOwnPropertyDescriptor(t,"shape");if(!r?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}const n=Z1((()=>s3(t)));t2(e._zod,"propValues",(()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r}));const i=o2,s=t.catchall;let o;e._zod.parse=(t,r)=>{o??(o=n.value);const a=t.value;if(!i(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],u=o.shape;for(const e of o.keys){const n=u[e]._zod.run({value:a[e],issues:[]},r);n instanceof Promise?c.push(n.then((r=>i3(r,t,e,a)))):i3(n,t,e,a)}return s?o3(c,a,t,r,n.value,e):c.length?Promise.all(c).then((()=>t)):t}})),c3=V1("$ZodObjectJIT",((e,t)=>{a3.init(e,t);const r=e._zod.parse,n=Z1((()=>s3(t)));let i;const s=o2,o=!W1.jitless,a=o&&a2.value,c=t.catchall;let u;e._zod.parse=(l,h)=>{u??(u=n.value);const d=l.value;return s(d)?o&&a&&!1===h?.async&&!0!==h.jitless?(i||(i=(e=>{const t=new J2(["shape","payload","ctx"]),r=n.value,i=e=>{const t=i2(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const s=Object.create(null);let o=0;for(const e of r.keys)s[e]="key_"+o++;t.write("const newResult = {};");for(const e of r.keys){const r=s[e],n=i2(e);t.write(`const ${r} = ${i(e)};`),t.write(`\n if (${r}.issues.length) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${n}, ...iss.path] : [${n}]\n })));\n }\n \n \n if (${r}.value === undefined) {\n if (${n} in input) {\n newResult[${n}] = undefined;\n }\n } else {\n newResult[${n}] = ${r}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,r)=>a(e,t,r)})(t.shape)),l=i(l,h),c?o3([],d,l,h,u,e):l):r(l,h):(l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l)}}));function u3(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;const i=e.filter((e=>!p2(e)));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((e=>e.issues.map((e=>y2(e,n,J1())))))}),t)}const l3=V1("$ZodUnion",((e,t)=>{Z2.init(e,t),t2(e._zod,"optin",(()=>t.options.some((e=>"optional"===e._zod.optin))?"optional":void 0)),t2(e._zod,"optout",(()=>t.options.some((e=>"optional"===e._zod.optout))?"optional":void 0)),t2(e._zod,"values",(()=>{if(t.options.every((e=>e._zod.values)))return new Set(t.options.flatMap((e=>Array.from(e._zod.values))))})),t2(e._zod,"pattern",(()=>{if(t.options.every((e=>e._zod.pattern))){const e=t.options.map((e=>e._zod.pattern));return new RegExp(`^(${e.map((e=>X1(e.source))).join("|")})$`)}}));const r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(i,s)=>{if(r)return n(i,s);let o=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},s);if(t instanceof Promise)a.push(t),o=!0;else{if(0===t.issues.length)return t;a.push(t)}}return o?Promise.all(a).then((t=>u3(t,i,e,s))):u3(a,i,e,s)}})),h3=V1("$ZodIntersection",((e,t)=>{Z2.init(e,t),e._zod.parse=(e,r)=>{const n=e.value,i=t.left._zod.run({value:n,issues:[]},r),s=t.right._zod.run({value:n,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then((([t,r])=>f3(e,t,r))):f3(e,i,s)}}));function d3(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(c2(e)&&c2(t)){const r=Object.keys(t),n=Object.keys(e).filter((e=>-1!==r.indexOf(e))),i={...e,...t};for(const r of n){const n=d3(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};i[r]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const i=d3(e[n],t[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function f3(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),p2(e))return e;const n=d3(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const p3=V1("$ZodEnum",((e,t)=>{Z2.init(e,t);const r=function(e){const t=Object.values(e).filter((e=>"number"==typeof e));return Object.entries(e).filter((([e,r])=>-1===t.indexOf(+e))).map((([e,t])=>t))}(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((e=>l2.has(typeof e))).map((e=>"string"==typeof e?e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e.toString())).join("|")})$`),e._zod.parse=(t,i)=>{const s=t.value;return n.has(s)||t.issues.push({code:"invalid_value",values:r,input:s,inst:e}),t}})),g3=V1("$ZodTransform",((e,t)=>{Z2.init(e,t),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new $1(e.constructor.name);const i=t.transform(r.value,r);if(n.async){return(i instanceof Promise?i:Promise.resolve(i)).then((e=>(r.value=e,r)))}if(i instanceof Promise)throw new H1;return r.value=i,r}}));function m3(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const y3=V1("$ZodOptional",((e,t)=>{Z2.init(e,t),e._zod.optin="optional",e._zod.optout="optional",t2(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0)),t2(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${X1(e.source)})?$`):void 0})),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then((t=>m3(t,e.value))):m3(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}})),b3=V1("$ZodNullable",((e,t)=>{Z2.init(e,t),t2(e._zod,"optin",(()=>t.innerType._zod.optin)),t2(e._zod,"optout",(()=>t.innerType._zod.optout)),t2(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${X1(e.source)}|null)$`):void 0})),t2(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0)),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)})),w3=V1("$ZodDefault",((e,t)=>{Z2.init(e,t),e._zod.optin="optional",t2(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);if(void 0===e.value)return e.value=t.defaultValue,e;const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then((e=>v3(e,t))):v3(n,t)}}));function v3(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const E3=V1("$ZodPrefault",((e,t)=>{Z2.init(e,t),e._zod.optin="optional",t2(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,r)=>("backward"===r.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))})),A3=V1("$ZodNonOptional",((e,t)=>{Z2.init(e,t),t2(e._zod,"values",(()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter((e=>void 0!==e))):void 0})),e._zod.parse=(r,n)=>{const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then((t=>S3(t,e))):S3(i,e)}}));function S3(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const k3=V1("$ZodCatch",((e,t)=>{Z2.init(e,t),t2(e._zod,"optin",(()=>t.innerType._zod.optin)),t2(e._zod,"optout",(()=>t.innerType._zod.optout)),t2(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then((n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map((e=>y2(e,r,J1())))},input:e.value}),e.issues=[]),e))):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map((e=>y2(e,r,J1())))},input:e.value}),e.issues=[]),e)}})),R3=V1("$ZodPipe",((e,t)=>{Z2.init(e,t),t2(e._zod,"values",(()=>t.in._zod.values)),t2(e._zod,"optin",(()=>t.in._zod.optin)),t2(e._zod,"optout",(()=>t.out._zod.optout)),t2(e._zod,"propValues",(()=>t.in._zod.propValues)),e._zod.parse=(e,r)=>{if("backward"===r.direction){const n=t.out._zod.run(e,r);return n instanceof Promise?n.then((e=>C3(e,t.in,r))):C3(n,t.in,r)}const n=t.in._zod.run(e,r);return n instanceof Promise?n.then((e=>C3(e,t.out,r))):C3(n,t.out,r)}}));function C3(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const I3=V1("$ZodReadonly",((e,t)=>{Z2.init(e,t),t2(e._zod,"propValues",(()=>t.innerType._zod.propValues)),t2(e._zod,"values",(()=>t.innerType._zod.values)),t2(e._zod,"optin",(()=>t.innerType?._zod?.optin)),t2(e._zod,"optout",(()=>t.innerType?._zod?.optout)),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(P3):P3(n)}}));function P3(e){return e.value=Object.freeze(e.value),e}const T3=V1("$ZodCustom",((e,t)=>{U2.init(e,t),Z2.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then((t=>_3(t,r,n,e)));_3(i,r,n,e)}}));function _3(e,t,r,n){if(!e){const e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(w2(e))}}var N3;class M3{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(N3=globalThis).__zod_globalRegistry??(N3.__zod_globalRegistry=new M3);const x3=globalThis.__zod_globalRegistry;function O3(e,t){return new q2({check:"less_than",...d2(t),value:e,inclusive:!1})}function D3(e,t){return new q2({check:"less_than",...d2(t),value:e,inclusive:!0})}function B3(e,t){return new z2({check:"greater_than",...d2(t),value:e,inclusive:!1})}function L3(e,t){return new z2({check:"greater_than",...d2(t),value:e,inclusive:!0})}function F3(e,t){return new K2({check:"multiple_of",...d2(t),value:e})}function U3(e,t){return new H2({check:"min_length",...d2(t),minimum:e})}function j3(e){const t=function(e,t){const r=new U2({check:"custom",...d2(t)});return r._zod.check=e,r}((r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(w2(e,r.value,t._zod.def));else{const n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(w2(n))}},e(r.value,r))));return t}const q3=V1("ZodError",((e,t)=>{E2.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const r={_errors:[]},n=e=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map((e=>n({issues:e})));else if("invalid_key"===i.code)n({issues:i.issues});else if("invalid_element"===i.code)n({issues:i.issues});else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){const r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(e),r}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const r={},n=[];for(const i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Q1,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Q1,2)}},isEmpty:{get:()=>0===e.issues.length}})}),{Parent:Error}),z3=S2(q3),K3=k2(q3),G3=R2(q3),V3=I2(q3),H3=T2(q3),$3=_2(q3),W3=N2(q3),J3=M2(q3),Q3=x2(q3),Z3=O2(q3),Y3=D2(q3),X3=B2(q3),e6=V1("ZodType",((e,t)=>(Z2.init(e,t),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(n2(t,{checks:[...t.checks??[],...r.map((e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e))]})),e.clone=(t,r)=>h2(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>z3(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>G3(e,t,r),e.parseAsync=async(t,r)=>K3(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>V3(e,t,r),e.spa=e.safeParseAsync,e.encode=(t,r)=>H3(e,t,r),e.decode=(t,r)=>$3(e,t,r),e.encodeAsync=async(t,r)=>W3(e,t,r),e.decodeAsync=async(t,r)=>J3(e,t,r),e.safeEncode=(t,r)=>Q3(e,t,r),e.safeDecode=(t,r)=>Z3(e,t,r),e.safeEncodeAsync=async(t,r)=>Y3(e,t,r),e.safeDecodeAsync=async(t,r)=>X3(e,t,r),e.refine=(t,r)=>e.check(function(e,t={}){return function(e,t,r){return new e({type:"custom",check:"custom",fn:t,...d2(r)})}(C6,e,t)}(t,r)),e.superRefine=t=>e.check(j3(t)),e.overwrite=t=>e.check(new W2({check:"overwrite",tx:t})),e.optional=()=>m6(e),e.nullable=()=>b6(e),e.nullish=()=>m6(b6(e)),e.nonoptional=t=>function(e,t){return new E6({type:"nonoptional",innerType:e,...d2(t)})}(e,t),e.array=()=>{return function(e,t,r){return new e({type:"array",element:t,...d2(r)})}(u6,e,t);var t},e.or=t=>{return new h6({type:"union",options:[e,t],...d2(r)});var r},e.and=t=>new d6({type:"intersection",left:e,right:t}),e.transform=t=>k6(e,new p6({type:"transform",transform:t})),e.default=t=>{return r=t,new w6({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():u2(r)}});var r},e.prefault=t=>{return r=t,new v6({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():u2(r)}});var r},e.catch=t=>{return new A6({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>k6(e,t),e.readonly=()=>new R6({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return x3.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>x3.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return x3.get(e);const r=e.clone();return x3.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e))),t6=V1("ZodNumber",((e,t)=>{Y2.init(e,t),e6.init(e,t),e.gt=(t,r)=>e.check(B3(t,r)),e.gte=(t,r)=>e.check(L3(t,r)),e.min=(t,r)=>e.check(L3(t,r)),e.lt=(t,r)=>e.check(O3(t,r)),e.lte=(t,r)=>e.check(D3(t,r)),e.max=(t,r)=>e.check(D3(t,r)),e.int=t=>e.check(i6(t)),e.safe=t=>e.check(i6(t)),e.positive=t=>e.check(B3(0,t)),e.nonnegative=t=>e.check(L3(0,t)),e.negative=t=>e.check(O3(0,t)),e.nonpositive=t=>e.check(D3(0,t)),e.multipleOf=(t,r)=>e.check(F3(t,r)),e.step=(t,r)=>e.check(F3(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null}));function r6(e){return function(e,t){return new e({type:"number",checks:[],...d2(t)})}(t6,e)}const n6=V1("ZodNumberFormat",((e,t)=>{X2.init(e,t),t6.init(e,t)}));function i6(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...d2(t)})}(n6,e)}const s6=V1("ZodUnknown",((e,t)=>{e3.init(e,t),e6.init(e,t)}));function o6(){return new s6({type:"unknown"})}const a6=V1("ZodNever",((e,t)=>{t3.init(e,t),e6.init(e,t)}));function c6(e){return function(e,t){return new e({type:"never",...d2(t)})}(a6,e)}const u6=V1("ZodArray",((e,t)=>{n3.init(e,t),e6.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(U3(t,r)),e.nonempty=t=>e.check(U3(1,t)),e.max=(t,r)=>e.check(function(e,t){return new V2({check:"max_length",...d2(t),maximum:e})}(t,r)),e.length=(t,r)=>e.check(function(e,t){return new $2({check:"length_equals",...d2(t),length:e})}(t,r)),e.unwrap=()=>e.element}));const l6=V1("ZodObject",((e,t)=>{c3.init(e,t),e6.init(e,t),t2(e,"shape",(()=>t.shape)),e.keyof=()=>function(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map((e=>[e,e]))):e;return new f6({type:"enum",entries:r,...d2(t)})}(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:o6()}),e.loose=()=>e.clone({...e._zod.def,catchall:o6()}),e.strict=()=>e.clone({...e._zod.def,catchall:c6()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!c2(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const n=n2(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return r2(this,"shape",r),r},checks:[]});return h2(e,n)}(e,t),e.safeExtend=t=>function(e,t){if(!c2(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return r2(this,"shape",r),r},checks:e._zod.def.checks};return h2(e,r)}(e,t),e.merge=t=>function(e,t){const r=n2(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return r2(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return h2(e,r)}(e,t),e.pick=t=>function(e,t){const r=e._zod.def,n=n2(e._zod.def,{get shape(){const e={};for(const n in t){if(!(n in r.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(e[n]=r.shape[n])}return r2(this,"shape",e),e},checks:[]});return h2(e,n)}(e,t),e.omit=t=>function(e,t){const r=e._zod.def,n=n2(e._zod.def,{get shape(){const n={...e._zod.def.shape};for(const e in t){if(!(e in r.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return r2(this,"shape",n),n},checks:[]});return h2(e,n)}(e,t),e.partial=(...t)=>function(e,t,r){const n=n2(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(const t in n)i[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return r2(this,"shape",i),i},checks:[]});return h2(t,n)}(g6,e,t[0]),e.required=(...t)=>function(e,t,r){const n=n2(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(const t in n)i[t]=new e({type:"nonoptional",innerType:n[t]});return r2(this,"shape",i),i},checks:[]});return h2(t,n)}(E6,e,t[0])}));const h6=V1("ZodUnion",((e,t)=>{l3.init(e,t),e6.init(e,t),e.options=t.options}));const d6=V1("ZodIntersection",((e,t)=>{h3.init(e,t),e6.init(e,t)}));const f6=V1("ZodEnum",((e,t)=>{p3.init(e,t),e6.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{const i={};for(const n of e){if(!r.has(n))throw new Error(`Key ${n} not found in enum`);i[n]=t.entries[n]}return new f6({...t,checks:[],...d2(n),entries:i})},e.exclude=(e,n)=>{const i={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new f6({...t,checks:[],...d2(n),entries:i})}}));const p6=V1("ZodTransform",((e,t)=>{g3.init(e,t),e6.init(e,t),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new $1(e.constructor.name);r.addIssue=n=>{if("string"==typeof n)r.issues.push(w2(n,r.value,t));else{const t=n;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),r.issues.push(w2(t))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then((e=>(r.value=e,r))):(r.value=i,r)}}));const g6=V1("ZodOptional",((e,t)=>{y3.init(e,t),e6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function m6(e){return new g6({type:"optional",innerType:e})}const y6=V1("ZodNullable",((e,t)=>{b3.init(e,t),e6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function b6(e){return new y6({type:"nullable",innerType:e})}const w6=V1("ZodDefault",((e,t)=>{w3.init(e,t),e6.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}));const v6=V1("ZodPrefault",((e,t)=>{E3.init(e,t),e6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const E6=V1("ZodNonOptional",((e,t)=>{A3.init(e,t),e6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const A6=V1("ZodCatch",((e,t)=>{k3.init(e,t),e6.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}));const S6=V1("ZodPipe",((e,t)=>{R3.init(e,t),e6.init(e,t),e.in=t.in,e.out=t.out}));function k6(e,t){return new S6({type:"pipe",in:e,out:t})}const R6=V1("ZodReadonly",((e,t)=>{I3.init(e,t),e6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const C6=V1("ZodCustom",((e,t)=>{T3.init(e,t),e6.init(e,t)}));class I6 extends Error{reasonText;constructor(e){super(`Failed to parse metadata: ${e}`),this.reasonText=e}}const P6=new Bv("Operator");class T6{contractAddress;contract;contractReadonly;contractFactory;rpcProviderSource;theGraphClient;identity;getEthersOverrides;eventEmitter=new sE;constructor(e,t,r,n,i,s,o,a,c){this.contractAddress=e,this.contractFactory=t,this.rpcProviderSource=r,this.contractReadonly=t.createReadContract(nb(e),SA.OperatorABI,r.getProvider(),"operator"),this.theGraphClient=i,this.identity=s,this.getEthersOverrides=c,this.initEventGateways(e,n,a),o.onDestroy.listen((()=>{this.eventEmitter.removeAllListeners()}))}initEventGateways(e,t,r){const n=new uN(SA.OperatorABI),i=([e])=>({sponsorship:nb(e)});wD({sourceDefinition:{contractInterfaceFragment:n.getEvent("Staked"),contractAddress:e},sourceEmitter:t,targetName:"staked",targetEmitter:this.eventEmitter,transformation:i,loggerFactory:r}),wD({sourceDefinition:{contractInterfaceFragment:n.getEvent("Unstaked"),contractAddress:e},sourceEmitter:t,targetName:"unstaked",targetEmitter:this.eventEmitter,transformation:i,loggerFactory:r});wD({sourceDefinition:{contractInterfaceFragment:n.getEvent("ReviewRequest"),contractAddress:e},sourceEmitter:t,targetName:"reviewRequested",targetEmitter:this.eventEmitter,transformation:([e,t,r,n,i])=>{const s=function(e){if(void 0===e)throw new I6("no metadata");let t;try{t=JSON.parse(e)}catch{throw new I6("malformed metadata")}const r=Number(t.partition);if(isNaN(r))throw new I6('invalid or missing "partition" field');try{vE(r)}catch{throw new I6("invalid partition numbering")}return r}(i);return{sponsorship:nb(e),targetOperator:nb(t),partition:s,votingPeriodStartTimestamp:1e3*Number(r),votingPeriodEndTimestamp:1e3*Number(n)}},loggerFactory:r})}async writeHeartbeat(e){const t=JSON.stringify(e);await this.connectToContract(),await(await this.contract.heartbeat(t,await this.getEthersOverrides())).wait()}async getTimestampOfLastHeartbeat(){const e=await this.theGraphClient.queryEntity({query:`{\n operator(id: "${await this.getContractAddress()}") {\n latestHeartbeatTimestamp\n }\n }`});if(null!==e.operator&&null!==e.operator.latestHeartbeatTimestamp){const t=parseInt(e.operator.latestHeartbeatTimestamp);if(isNaN(t))throw new Error("Assertion failed: unexpected non-integer latestHeartbeatTimestamp");return 1e3*t}}async getContractAddress(){return nb(await this.contractReadonly.getAddress())}async getSponsorships(){const e=await this.getContractAddress(),t=this.theGraphClient.queryEntities(((t,r)=>({query:`\n {\n operator(id: "${e}") {\n stakes(where: {id_gt: "${t}"}, first: ${r}) {\n id\n sponsorship {\n id\n operatorCount\n stream {\n id\n }\n }\n }\n }\n }\n `})),(e=>e.operator?.stakes??[])),r=[];for await(const e of t)r.push({sponsorshipAddress:nb(e.sponsorship.id),streamId:bE(e.sponsorship.stream.id),operatorCount:e.sponsorship.operatorCount});return r}async getExpiredFlags(e,t){const r=Math.floor((Date.now()-t)/1e3),n=this.theGraphClient.queryEntities(((t,n)=>({query:`\n {\n flags (where : {\n id_gt: "${t}",\n voteEndTimestamp_lt: ${r},\n result_in: ["waiting", "voting"],\n sponsorship_in: ${JSON.stringify(e)}\n }, first: ${n}) {\n id\n flaggingTimestamp\n target {\n id\n }\n sponsorship {\n id\n }\n }\n }`}))),i=[];for await(const e of n)i.push({id:e.id,flaggingTimestamp:e.flaggingTimestamp,targetOperator:nb(e.target.id),sponsorship:nb(e.sponsorship.id)});return i}async getOperatorsInSponsorship(e){const t=this.theGraphClient.queryEntities(((t,r)=>({query:`\n {\n sponsorship(id: "${e}") {\n stakes(where: {id_gt: "${t}"}, first: ${r}) {\n id\n operator {\n id\n }\n }\n }\n }\n `})),(e=>e.sponsorship?.stakes??[])),r=[];for await(const e of t)r.push(nb(e.operator.id));return r}async flag(e,t,r){const n=JSON.stringify({partition:r});await this.connectToContract(),await(await this.contract.flag(e,t,n,await this.getEthersOverrides())).wait()}async getEarnings(e,t){const{addresses:r,earnings:n,maxAllowedEarnings:i}=await this.contractReadonly.getSponsorshipsAndEarnings(),s=r.map(((e,t)=>({address:e,earnings:n[t]}))).filter((t=>t.earnings>=e)).sort(((e,t)=>((e,t)=>e<t?-1:e>t?1:0)(e.earnings,t.earnings))).slice(0,t);return{sponsorshipAddresses:s.map((e=>nb(e.address))),sum:s.reduce(((e,t)=>e+t.earnings),0n),maxAllowedEarnings:i}}async withdrawEarningsFromSponsorships(e){await this.connectToContract(),await(await this.contract.withdrawEarningsFromSponsorships(e,await this.getEthersOverrides())).wait()}async triggerAnotherOperatorWithdraw(e,t){await this.connectToContract(),await(await this.contract.triggerAnotherOperatorWithdraw(e,t,await this.getEthersOverrides())).wait()}async getStakedOperators(){const e=this.theGraphClient.queryEntities(((e,t)=>({query:`\n {\n operators(where: {totalStakeInSponsorshipsWei_gt: "0", id_gt: "${e}"}, first: ${t}) {\n id\n }\n }\n `}))),t=[];for await(const r of e)t.push(nb(r.id));return t}async*pullStakedStreams(e){const t=await this.getContractAddress();this.theGraphClient.updateRequiredBlockNumber(e);const r=this.theGraphClient.queryEntities(((e,r)=>({query:`\n {\n operator(id: "${t}") {\n stakes(where: {id_gt: "${e}"}, first: ${r}) {\n sponsorship {\n id\n stream {\n id\n }\n }\n }\n }\n _meta {\n block {\n number\n }\n }\n }\n `})),(e=>e.operator?e.operator.stakes:(P6.error("Unable to find operator in The Graph",{operatorContractAddress:t}),[])));for await(const e of r)yield{sponsorship:nb(e.sponsorship.id),streamId:bE(e.sponsorship.stream.id)}}async hasOpenFlag(e){const t=await this.getContractAddress(),r=this.theGraphClient.queryEntities((()=>({query:`\n {\n flags(where: {\n sponsorship: "${e}",\n target: "${t}",\n result_in: ["waiting", "voting"]\n }) {\n id\n }\n }\n `}))),n=await cE(r,1);return n.length>0&&(P6.debug("Found open flag",{flag:n[0]}),!0)}async getStreamId(e){const t=this.contractFactory.createReadContract(nb(e),SA.SponsorshipABI,this.rpcProviderSource.getProvider(),"sponsorship");return bE(await t.streamId())}async voteOnFlag(e,t,r){const n=r?"0x0000000000000000000000000000000000000000000000000000000000000001":"0x0000000000000000000000000000000000000000000000000000000000000000";await this.connectToContract();const i=1300000n,s=await this.contract.voteOnFlag.estimateGas(e,t,n);if(s>i)throw new Error(`Gas estimate (${s}) exceeds limit (1300000)`);await(await this.contract.voteOnFlag(e,t,n,{...await this.getEthersOverrides(),gasLimit:i})).wait()}async closeFlag(e,t){await this.voteOnFlag(e,t,!1)}async fetchRedundancyFactor(){const e=function(e,t){const r={type:"object",shape:e??{},...d2(t)};return new l6(r)}({redundancyFactor:r6().int().gte(1)}),t=await this.contractReadonly.metadata();if(0===t.length)return 1;let r,n;try{r=JSON.parse(t)}catch{return void P6.warn("Encountered malformed metadata",{operatorAddress:await this.getContractAddress(),metadataAsString:t})}try{n=e.parse(r)}catch(e){return void P6.warn("Encountered invalid metadata",{operatorAddress:await this.getContractAddress(),metadataAsString:t,reason:e?.reason})}return n.redundancyFactor}getCurrentBlockNumber(){return this.rpcProviderSource.getProvider().getBlockNumber()}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}async connectToContract(){if(void 0===this.contract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.contract=this.contractFactory.createWriteContract(this.contractAddress,SA.OperatorABI,e,"operator")}}}var _6=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},N6=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},M6=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let x6=class{config;constructor(e,t,r,n){this.config=t,this.initEventListener(r,e,n)}initEventListener(e,t,r){const n=nb(this.config.contracts.sponsorshipFactoryChainAddress),i=new uN(SA.SponsorshipFactoryABI);wD({sourceDefinition:{contractInterfaceFragment:i.getEvent("NewSponsorship"),contractAddress:n},sourceEmitter:t,targetName:"sponsorshipCreated",targetEmitter:e,transformation:([e,t],r)=>({sponsorshipContractAddress:nb(e),streamId:bE(t),blockNumber:r}),loggerFactory:r})}};x6=_6([q(d.ContainerScoped),M6(1,U(cA)),N6("design:paramtypes",[DJ,Object,sD,uD])],x6);var O6,D6=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},B6=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},L6=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};!function(e){e[e.NONE=0]="NONE",e[e.NORMAL=1]="NORMAL",e[e.ERC_1271=2]="ERC_1271"}(O6||(O6={}));let F6=class{networkNodeFacade;streamRegistry;signatureValidator;messageSigner;store;identity;logger;erc1271Publishers=new Set;config;constructor(t,r,n,i,s,o,a,c,u){this.networkNodeFacade=t,this.streamRegistry=r,this.signatureValidator=n,this.messageSigner=i,this.store=s,this.identity=o,this.logger=u.createLogger("PublisherKeyExchange"),this.config=a,void 0===a.encryption.keys&&(t.once("start",(async()=>{t.addMessageListener((e=>this.onMessage(e))),this.logger.debug("Started")})),c.on("messagePublished",(t=>{if(t.signatureType===e.SignatureType.ERC_1271){const e=t.getPublisherId();this.erc1271Publishers.has(e)||(this.logger.debug("Add ERC-1271 publisher",{publisherId:e}),this.erc1271Publishers.add(e))}})))}async onMessage(t){if(t.messageType===e.StreamMessageType.GROUP_KEY_REQUEST)try{const{recipientId:e,requestId:r,publicKey:n,groupKeyIds:i,encryptionType:s}=uH.fromBinary(t.content),o=kE(e);if(!function(e,t){const r=YX.has(e),n=t.encryption?.requireQuantumResistantKeyExchange;return r||!n}(s,this.config))throw new uA(`EncryptionType in key request (${s}) is not compliant with encryption settings!`,"ENCRYPTION_POLICY_VIOLATION",t);const a=await this.getResponseType(o);if(a!==O6.NONE){this.logger.debug("Handling group key request",{requestId:r,responseType:a,keyEncryptionType:rH[s]}),await GX(t,this.streamRegistry,this.signatureValidator,this.config);const e=await this.identity.getUserId(),c=ju(await Promise.all(i.map((t=>this.store.get(t,e)))),void 0);if(c.length>0){const e=await this.createResponse(c,a,o,t.getStreamPartID(),n,t.getPublisherId(),r,s);await this.networkNodeFacade.broadcast(e),this.logger.debug("Handled group key request (found keys)",{groupKeyIds:c.map((e=>e.id)).join(),recipient:t.getPublisherId()})}else this.logger.debug("Handled group key request (no keys found)",{requestId:r,recipient:t.getPublisherId()})}}catch(e){this.logger.debug("Failed to handle group key request",e)}}async getResponseType(e){return e===await this.identity.getUserId()?O6.NORMAL:this.erc1271Publishers.has(e)?O6.ERC_1271:O6.NONE}async createResponse(t,r,n,i,s,o,a,c){const u=await Promise.all(t.map((async e=>({id:e.id,data:await RQ.encryptForPublicKey(e.data,s,c)})))),l={recipientId:RE(o),requestId:a,groupKeys:u,encryptionType:c};return this.messageSigner.createSignedMessage({messageId:new X$(AE.getStreamID(i),AE.getStreamPartition(i),Date.now(),0,n,bX()),content:lH.toBinary(l),contentType:e.ContentType.BINARY,messageType:e.StreamMessageType.GROUP_KEY_RESPONSE,encryptionType:e.EncryptionType.NONE},r===O6.NORMAL?this.identity.getSignatureType():e.SignatureType.ERC_1271)}};F6=D6([q(d.ContainerScoped),L6(5,U(kA)),L6(6,U(cA)),B6("design:paramtypes",[yX,WJ,KX,e.MessageSigner,aZ,RA,Object,sD,uD])],F6);class U6{pipeline;onFinally;onBeforeFinally;onError;constructor(e){this.pipeline=e??new BW,this.onFinally=this.pipeline.onFinally,this.onBeforeFinally=this.pipeline.onBeforeFinally,this.onError=this.pipeline.onError}useLegacyOnMessageHandler(e){return this.pipeline.onMessage.listen((async t=>{const r=S1(t);await e(r.content,uY(r,"content"))})),this.pipeline.flow(),this}async*[Symbol.asyncIterator](){for await(const e of this.pipeline)yield S1(e)}async push(e){await this.pipeline.push(e)}pipe(e){return this.pipeline.pipe(e)}async handleError(e){await this.pipeline.handleError(e)}end(e){this.pipeline.end(e)}isDone(){return this.pipeline.isDone()}return(){return this.pipeline.return()}}class j6 extends U6{streamPartId;isRaw;erc1271ContractAddress;deliveryOptions;eventEmitter;logger;constructor(e,t,r,n,i,s){super(),this.streamPartId=e,this.isRaw=t,this.erc1271ContractAddress=r,this.deliveryOptions=n,this.eventEmitter=i,this.logger=s.createLogger("Subscription"),this.onError.listen((e=>{this.eventEmitter.emit("error",e),this.logger.debug("Encountered error",{err:e})}))}async unsubscribe(){this.end(),await this.return(),this.eventEmitter.removeAllListeners()}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.off(e,t)}}const q6=new Bv("waitForStorage");const z6=async(e,t,r,n,i,s,o,a,c)=>{if(r.wait){if(await o.isStoredStream(e,t))return;let u;try{const s=EE(wW(t),0);u=new j6(s,!1,void 0,void 0,new Sl,a),await i.add(u);const l=async function(e,t,r){const n=new Set;for await(const i of e){const e=i.content.streamPart;try{const r=AE.parse(e),[i,s]=AE.getStreamIDAndPartition(r);if(i===t.id&&s<t.partitions&&(n.add(s),n.size===t.partitions))return}catch{r.createLogger("waitForAssignmentsToPropagate").debug("Ignore malformed content")}}}(u,{id:e,partitions:n},a);await o.addStreamToStorageNode(e,t),await Xv(l,r.timeout??c._timeouts.storageNode.timeout,"storage node did not respond")}finally{s.invalidatePermissionCaches(e),await(u?.unsubscribe())}}else await o.addStreamToStorageNode(e,t)},K6=new Bv("StreamrClient");const G6=function(e,t){DA("string"==typeof e,"value must be a string","value",e);let r=18;return r=cS(t,"unit"),HS.fromString(e,{decimals:r,width:512}).value}("1",18);const V6=new Bv("operatorContractUtils");const H6=async(e,t,r,n,i)=>{const s=J6(n),o=await s.connect(e).transferAndCall(t,r,"0x");await o.wait(void 0,i)},$6=e=>new JN(e,SA.OperatorABI),W6=e=>new JN(e,SA.SponsorshipABI),J6=e=>new JN(e,SA.DATAv2ABI),Q6={delegate:async(e,t,r,n)=>{V6.debug("Delegate",{amount:r.toString()});const i=await $6(t).connect(e.provider).token();await H6(e,t,r,i,n)},undelegate:async(e,t,r,n)=>{V6.debug("Undelegate",{amount:r.toString()}),await(await $6(t).connect(e).undelegate(r)).wait(void 0,n)},deploySponsorshipContract:async function(e){V6.debug("Deploying SponsorshipContract");const t=[{contractAddress:ZO.config[e.environmentId].contracts.SponsorshipStakeWeightedAllocationPolicy,param:e.earningsPerSecond},{contractAddress:ZO.config[e.environmentId].contracts.SponsorshipDefaultLeavePolicy,param:e.minStakeDuration??0},{contractAddress:ZO.config[e.environmentId].contracts.SponsorshipVoteKickPolicy,param:0}];void 0!==e.maxOperatorCount&&t.push({contractAddress:ZO.config[e.environmentId].contracts.SponsorshipMaxOperatorsJoinPolicy,param:e.maxOperatorCount});const r=rN.defaultAbiCoder().encode(["uint32","string","string","address[]","uint[]"],[(e.minOperatorCount??1).toString(),e.streamId,e.metadata??"{}",t.map((e=>e.contractAddress)),t.map((e=>e.param))]),n=await J6(ZO.config[e.environmentId].contracts.DATA).connect(e.deployer).transferAndCall(ZO.config[e.environmentId].contracts.SponsorshipFactory,e.sponsorAmount??0n,r),i=await n.wait(void 0,e.transactionTimeout),s=new uN(SA.SponsorshipFactoryABI),o=i.logs.map((e=>s.parseLog(e))).find((e=>"NewSponsorship"===e?.name)).args.sponsorshipContract;return V6.debug("Deployed SponsorshipContract",{address:o}),new JN(o,SA.SponsorshipABI,e.deployer)},sponsor:async(e,t,r,n)=>{V6.debug("Sponsor",{amount:r.toString()});const i=await W6(t).connect(e.provider).token();await H6(e,t,r,i,n)},stake:async(e,t,r,n,i={},s=()=>{},o)=>{V6.debug("Stake",{amount:rk(n),sponsorshipContractAddress:r});const a=$6(t).connect(e),c=await a.stake(r,n,i);V6.debug("Stake: transaction submitted",{tx:c.hash,nonce:c.nonce}),s(c),V6.debug("Stake: waiting for transaction to be mined",{tx:c.hash,timeout:o});try{const e=await c.wait(void 0,o);return V6.debug("Stake: confirmation received",{receipt:e?.hash}),e}catch(e){throw V6.error("Stake: error waiting for tx to be mined",{tx:c.hash,error:e}),e}},unstake:async(e,t,r,n,i={},s=()=>{},o)=>{V6.debug("Unstake",{amount:rk(n),sponsorshipContractAddress:r});const a=$6(t).connect(e),c=W6(r).connect(e),u=await c.stakedWei(t)-n,l=await a.reduceStakeTo(r,u,i);V6.debug("Unstake: transaction submitted",{tx:l.hash,nonce:l.nonce}),s(l),V6.debug("Unstake: waiting for transaction to be mined",{tx:l.hash,timeout:o});try{const e=await l.wait(void 0,o);return V6.debug("Unstake: confirmation received",{receipt:e?.hash}),e}catch(e){throw V6.error("Unstake: error waiting for tx to be mined",{tx:l.hash,error:e}),e}},deployOperatorContract:async function(e){V6.debug("Deploying OperatorContract");const t=new JN(ZO.config[e.environmentId].contracts.OperatorFactory,SA.OperatorFactoryABI,e.deployer);if(await t.operators(await e.deployer.getAddress())!==CI)throw new Error("Operator already has a contract");var r,n;const i=(await(await t.deployOperator((r=G6,n=(e.operatorsCutPercentage??0)/100,r*BigInt(IE*n)/BigInt(IE)),e.operatorTokenName??`OperatorToken-${Date.now()}`,e.metadata??"",[ZO.config[e.environmentId].contracts.OperatorDefaultDelegationPolicy,ZO.config[e.environmentId].contracts.OperatorDefaultExchangeRatePolicy,ZO.config[e.environmentId].contracts.OperatorDefaultUndelegationPolicy],[0,0,0])).wait(void 0,e.transactionTimeout)).logs.find((e=>"NewOperator"===e.fragment?.name)).args.operatorContractAddress,s=new JN(i,SA.OperatorABI,e.deployer);return V6.debug("Deployed OperatorContract",{address:i}),s},getOperatorContract:$6};e.ConfigInjectionToken=cA,e.DEFAULT_ENVIRONMENT_ID=aA,e.DEFAULT_KEY_TYPE=FX,e.ECDSAKeyPairIdentity=BX,e.ENVIRONMENT_IDS=["polygon","polygonAmoy","peaq","iotex","dev2"],e.EncryptedGroupKey=hH,e.EncryptionKey=IQ,e.EthereumKeyPairIdentity=NX,e.EthereumProviderIdentity=MX,e.Identity=RA,e.KeyPairIdentity=TX,e.MLDSAKeyPairIdentity=OX,e.MessageID=X$,e.MessageRef=Y$,e.Operator=T6,e.STREAMR_STORAGE_NODE_ADDRESS="0x9dc08ff97f5c156181ec6a0b13fc3946454e529a",e.STREAMR_STORAGE_NODE_GERMANY="0x31546eEA76F2B2b3C5cC06B1c93601dc35c9D916",e.Stream=G1,e.StreamMessage=tW,e.StreamrClient=class{id;publisher;subscriber;resends;node;rpcProviderSource;streamRegistry;streamStorageRegistry;storageNodeRegistry;operatorRegistry;contractFactory;localGroupKeyStore;chainEventPoller;theGraphClient;streamIdBuilder;config;identity;eventEmitter;destroySignal;loggerFactory;proxyNodeFinder;constructor(t={},r=F){const n=b1(t),i=function(e){if(void 0!==e.auth?.privateKey){const t=e.auth.keyType??FX,r=LX.find((e=>e.keyType===t));if(r)return r.fromConfig(e);throw new Error(`Unsupported keyType given in config: ${t}`)}return void 0!==e.auth?.identity?e.auth?.identity:void 0!==e.auth?.ethereum?MX.fromConfig(e):NX.generate()}(n);!function(e,t){const r=t0(e),n=t.encryption?.requireQuantumResistantSignatures;if(n&&!r)throw new uA("Quantum resistant signatures are required, but the configured key type doesn't enable quantum resistance!","SIGNATURE_POLICY_VIOLATION")}(i,n),(e=>{void 0!==e.auth?.privateKey&&(e.auth.privateKey="(redacted)")})(n);const s=r.createChildContainer();s.register(kA,{useValue:i}),s.register(cA,{useValue:n});const o=((e,t)=>{const r=new lE({serverUrl:t.contracts.theGraphUrl,fetch:(e,r)=>{const n=t._timeouts.theGraph.fetchTimeout,i=[AbortSignal.timeout(n)];r?.signal instanceof AbortSignal&&i.push(r.signal);const s=rE(...i);try{return fetch(e,aE(r,{signal:s}))}finally{s.destroy()}},indexTimeout:t._timeouts.theGraph.indexTimeout,indexPollInterval:t._timeouts.theGraph.indexPollInterval});return e.on("contractTransactionConfirmed",(e=>{null!=e.receipt&&r.updateRequiredBlockNumber(e.receipt.blockNumber)})),r})(s.resolve(sD),n);s.register(lE,{useValue:o}),this.id=n.id,this.config=n,this.identity=i,this.theGraphClient=o,this.publisher=s.resolve(u1),this.subscriber=s.resolve(r0.Subscriber),this.resends=s.resolve(r0.Resends),this.node=s.resolve(yX),this.rpcProviderSource=s.resolve(e.RpcProviderSource),this.streamRegistry=s.resolve(WJ),this.streamStorageRegistry=s.resolve(aQ),this.storageNodeRegistry=s.resolve(ID),this.operatorRegistry=s.resolve(dY),this.contractFactory=s.resolve(SD),this.localGroupKeyStore=s.resolve(aZ),this.chainEventPoller=s.resolve(DJ),this.streamIdBuilder=s.resolve(YW),this.eventEmitter=s.resolve(sD),this.destroySignal=s.resolve(UW),this.loggerFactory=s.resolve(uD),this.proxyNodeFinder=s.resolve(N1),s.resolve(F6),s.resolve(P1),s.resolve(x6)}async publish(e,t,r,n){const i=await this.publisher.publish(e,t,r,n);return this.eventEmitter.emit("messagePublished",i),S1(i)}async publishRaw(e,t){await this.node.broadcast(e,t),this.eventEmitter.emit("messagePublished",e)}async updateEncryptionKey(e){if(void 0===e.streamId)throw new Error("streamId required");const t=await this.streamIdBuilder.toStreamID(e.streamId),r=await this.publisher.getGroupKeyQueue(t);if("rotate"===e.distributionMethod)await r.rotate(e.key);else{if("rekey"!==e.distributionMethod)throw new Error(`assertion failed: distribution method ${e.distributionMethod}`);await r.rekey(e.key)}}async addEncryptionKey(e,t){await this.localGroupKeyStore.set(e.id,kE(t),e.data)}async subscribe(e,t){if(!0===e.raw&&void 0!==e.resend)throw new Error("Raw subscriptions are not supported for resend");const r=await this.streamIdBuilder.toStreamPartID(e),n=new Sl,i=new j6(r,e.raw??!1,void 0!==e.erc1271Contract?nb(e.erc1271Contract):void 0,e.delivery??{},n,this.loggerFactory);return void 0!==e.resend&&((e,t,r,n,i,s,o)=>{if(e.pipe((async function*(i){try{const i=await r.resend(e.streamPartId,_0(t),n);e.onBeforeFinally.listen((async()=>{i.end(),await i.return()})),yield*i}catch(r){"NO_STORAGE_NODES"===r.code?o.createLogger("resendSubscription").warn("Skip resend (no storage assigned to stream)",{streamPartId:e.streamPartId,resendOptions:t}):await e.handleError(r)}s.emit("resendCompleted"),yield*i})),i.orderMessages){const t=new v0(e.streamPartId,n,(()=>{}),r,i);e.pipe((async function*(e){setImmediate((()=>{t.addMessages(e)})),yield*t})),e.onBeforeFinally.listen((()=>t.destroy()))}})(i,e.resend,this.resends,(e=>this.streamStorageRegistry.getStorageNodes(e)),this.config,n,this.loggerFactory),await this.subscriber.add(i),void 0!==t&&i.useLegacyOnMessageHandler(t),this.eventEmitter.emit("streamPartSubscribed",void 0),i}async unsubscribe(e){if(e instanceof j6){const t=e;return this.subscriber.remove(t)}{const t=await this.getSubscriptions(e);return Promise.allSettled(t.map((e=>this.subscriber.remove(e))))}}async getSubscriptions(e){const t=void 0!==e?await this.streamIdBuilder.getMatcher(e):()=>!0;return this.subscriber.getSubscriptions().filter((e=>t(e.streamPartId)))}async resend(e,t,r){const n=await this.streamIdBuilder.toStreamPartID(e),i=await this.resends.resend(n,_0(t),(e=>this.streamStorageRegistry.getStorageNodes(e))),s=new U6(i);return void 0!==r&&s.useLegacyOnMessageHandler(r),s}waitForStorage(e,t){const r={interval:this.config._timeouts.storageNode.retryInterval,timeout:this.config._timeouts.storageNode.timeout,count:100};return(async(e,t,r,n)=>{if(!e)throw new uA("waitForStorage requires a Message","INVALID_ARGUMENT");const i=t.messageMatchFn??((e,t)=>yw(e.signature,t.signature)),s=Date.now();let o,a=!1;for(;!a;){const c=Date.now()-s;if(c>t.timeout)throw q6.debug("Timed out waiting for storage to contain message",{expected:e.streamMessage.messageId,lastReceived:o?.map((e=>e.messageId))}),new Error(`timed out after ${c}ms waiting for message`);const u=e=>n.getStorageNodes(e),l=await r.resend(EE(e.streamId,e.streamPartition),{last:t.count},u);o=await cE(l);for(const t of o)if(i(e,S1(t)))return a=!0,void q6.debug("Found matching message");q6.debug("Retry after delay (matching message not found)",{expected:e.streamMessage.messageId,"last-3":o.slice(-3).map((e=>e.messageId)),delayInMs:t.interval}),await Qv(t.interval)}})(e,t1(r,t),this.resends,this.streamStorageRegistry)}async getStream(e){const t=await this.streamIdBuilder.toStreamID(e);return await this.streamRegistry.getStreamMetadata(t),new G1(t,this)}async createStream(e){const t="object"==typeof e?e:{id:e},r=await this.streamIdBuilder.toStreamID(t.id),n=t1({partitions:1},uY(t,"id"));return await this.streamRegistry.createStream(r,n),new G1(r,this)}async getOrCreateStream(e){try{return await this.getStream(e.id)}catch(t){if("STREAM_NOT_FOUND"===t.code)return this.createStream(e);throw t}}async getStreamMetadata(e){const t=await this.streamIdBuilder.toStreamID(e);return this.streamRegistry.getStreamMetadata(t)}async setStreamMetadata(e,t){const r=await this.streamIdBuilder.toStreamID(e);await this.streamRegistry.setStreamMetadata(r,t)}deleteStream(e){return this.streamRegistry.deleteStream(e)}searchStreams(e,t){if(K6.debug("Search for streams",{term:e,permissionFilter:t}),void 0===e&&void 0===t)throw new Error("Requires a search term or a permission filter");const r=this.streamRegistry.searchStreams(e,void 0!==t?(e=>({...e,userId:kE(e.userId)}))(t):void 0);return sW(r,(e=>new G1(e,this)))}getStreamPublishers(e){return this.streamRegistry.getStreamPublishers(e)}getStreamSubscribers(e){return this.streamRegistry.getStreamSubscribers(e)}async hasPermission(e){return this.streamRegistry.hasPermission(await(async(e,t)=>{const r={...e,streamId:await t.toStreamID(e.streamId)};return"userId"in r?{...r,userId:kE(r.userId)}:r})(e,this.streamIdBuilder))}getPermissions(e){return this.streamRegistry.getPermissions(e)}grantPermissions(e,...t){return this.streamRegistry.grantPermissions(e,...t.map(iJ))}revokePermissions(e,...t){return this.streamRegistry.revokePermissions(e,...t.map(iJ))}setPermissions(...e){return this.streamRegistry.setPermissions(...e.map((e=>({...e,assignments:e.assignments.map(iJ)}))))}async isStreamPublisher(e,t){const r=await this.streamIdBuilder.toStreamID(e);return this.streamRegistry.isStreamPublisher(r,kE(t))}async isStreamSubscriber(e,t){const r=await this.streamIdBuilder.toStreamID(e);return this.streamRegistry.isStreamSubscriber(r,kE(t))}async addStreamToStorageNode(e,t,r={wait:!1}){const n=await this.streamIdBuilder.toStreamID(e);await z6(n,nb(t),r,eJ(await this.streamRegistry.getStreamMetadata(n)),this.subscriber,this.streamRegistry,this.streamStorageRegistry,this.loggerFactory,this.config)}async removeStreamFromStorageNode(e,t){return this.streamStorageRegistry.removeStreamFromStorageNode(e,nb(t))}async isStoredStream(e,t){return this.streamStorageRegistry.isStoredStream(e,nb(t))}async getStoredStreams(e){const t=await this.streamStorageRegistry.getStoredStreams(nb(e));for(const e of t.streams)this.streamRegistry.populateMetadataCache(e.id,e.metadata);return{streams:t.streams.map((e=>new G1(e.id,this))),blockNumber:t.blockNumber}}async getStorageNodes(e){return this.streamStorageRegistry.getStorageNodes(e)}setStorageNodeMetadata(e){return this.storageNodeRegistry.setStorageNodeMetadata(e)}async getStorageNodeMetadata(e){return this.storageNodeRegistry.getStorageNodeMetadata(nb(e))}getSigner(){return this.identity.getTransactionSigner(this.rpcProviderSource)}async getUserId(){return await this.identity.getUserId()}getAddress(){return this.getUserId()}getNode(){return this.node}async inspect(e,t){const r=await this.streamIdBuilder.toStreamPartID(t);return this.node.inspect(e,r)}async setProxies(e,t,r,n){const i=await this.streamIdBuilder.toStreamPartID(e);await this.node.setProxies(i,t,r,n)}async setStreamPartitionEntryPoints(e,t){const r=await this.streamIdBuilder.toStreamPartID(e);await this.node.setStreamPartEntryPoints(r,t)}connect(){return this._connect()}_connect=_W((async()=>{await this.node.startNode()}));destroy(){return this._destroy()}_destroy=_W((async()=>{this.eventEmitter.removeAllListeners(),this._connect.reset();const e=[this.destroySignal.destroy().then((()=>{})),this.unsubscribe()];await Promise.allSettled(e),await Promise.all(e)}));async getPeerDescriptor(){return AW(await this.node.getPeerDescriptor())}async getNodeId(){return this.node.getNodeId()}async getDiagnosticInfo(){return this.node.getDiagnosticInfo()}getConfig(){return this.config}getTheGraphClient(){return this.theGraphClient}getEthersOverrides(){return nD(this.rpcProviderSource,this.config)}getOperator(e){return new T6(e,this.contractFactory,this.rpcProviderSource,this.chainEventPoller,this.theGraphClient,this.identity,this.destroySignal,this.loggerFactory,(()=>this.getEthersOverrides()))}async findProxyNodes(e,t=1,r=100,n=24){return this.proxyNodeFinder.find(e,t,r,n)}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.off(e,t)}},e.Subscription=j6,e._operatorContractUtils=Q6,e.convertBytesToStreamMessage=nW,e.convertStreamMessageToBytes=function(e){return aH.toBinary(rW.toProtobuf(e))},e.formStorageNodeAssignmentStreamId=wW,e.getStreamPartitionCount=eJ,e.parseStreamMetadata=XW,e.peerDescriptorTranslator=EW,window.StreamrClient=window.StreamrClient.StreamrClient}));
70
+ const DQ=256,BQ=3329,{mod:LQ,nttZetas:FQ,NTT:UQ,bitsCoder:jQ}=Gp({N:DQ,Q:BQ,F:3303,ROOT_OF_UNITY:17,newPoly:e=>new Uint16Array(e),brvBits:7,isKyber:!0}),qQ=e=>jQ(e,(e=>{if(e>=12)return{encode:e=>e,decode:e=>e};const t=2**(e-1);return{encode:t=>((t<<e)+BQ/2)/BQ,decode:r=>r*BQ+t>>>e}})(e));function zQ(e,t){for(let r=0;r<DQ;r++)e[r]=LQ(e[r]+t[r])}function KQ(e,t){for(let o=0;o<128;o++){let a=FQ[64+(o>>1)];1&o&&(a=-a);const{c0:c,c1:u}=(r=e[2*o+0],n=e[2*o+1],i=t[2*o+0],s=t[2*o+1],{c0:LQ(n*s*a+r*i),c1:LQ(r*s+n*i)});e[2*o+0]=c,e[2*o+1]=u}var r,n,i,s;return e}function GQ(e){const t=new Uint16Array(DQ);for(let r=0;r<DQ;){const n=e();if(n.length%3)throw new Error("SampleNTT: unaligned block");for(let e=0;r<DQ&&e+3<=n.length;e+=3){const i=4095&(n[e+0]|n[e+1]<<8),s=4095&(n[e+1]>>4|n[e+2]<<4);i<BQ&&(t[r++]=i),r<DQ&&s<BQ&&(t[r++]=s)}}return t}function VQ(e,t,r,n){const i=e(n*DQ/4,t,r),s=new Uint16Array(DQ),o=Ci(i);let a=0;for(let e=0,t=0,r=0,i=0;e<o.length;e++){let c=o[e];for(let e=0;e<32;e++)r+=1&c,c>>=1,a+=1,a===n?(i=r,r=0):a===2*n&&(s[t++]=LQ(i-r),r=0,a=0)}if(a)throw new Error(`sampleCBD: leftover bits: ${a}`);return s}const HQ=e=>{const{K:t,PRF:r,XOF:n,HASH512:i,ETA1:s,ETA2:o,du:a,dv:c}=e,u=qQ(1),l=qQ(c),h=qQ(a),d=ao(co(qQ(12),t),32),f=co(qQ(12),t),p=ao(co(h,t),l),g=ao(32,32);return{secretCoder:f,secretKeyLen:f.bytesLen,publicKeyLen:d.bytesLen,cipherTextLen:p.bytesLen,keygen:e=>{io(e,32);const o=new Uint8Array(33);o.set(e),o[32]=t;const a=i(o),[c,u]=g.decode(a),l=[],h=[];for(let e=0;e<t;e++)l.push(UQ.encode(VQ(r,u,e,s)));const p=n(c);for(let e=0;e<t;e++){const n=UQ.encode(VQ(r,u,t+e,s));for(let r=0;r<t;r++){zQ(n,KQ(GQ(p.get(r,e)),l[r]))}h.push(n)}p.clean();const m={publicKey:d.encode([h,c]),secretKey:f.encode(l)};return uo(c,u,l,h,o,a),m},encrypt:(e,i,a)=>{const[c,l]=d.decode(e),h=[];for(let e=0;e<t;e++)h.push(UQ.encode(VQ(r,a,e,s)));const f=n(l),g=new Uint16Array(DQ),m=[];for(let e=0;e<t;e++){const n=VQ(r,a,t+e,o),i=new Uint16Array(DQ);for(let r=0;r<t;r++){zQ(i,KQ(GQ(f.get(e,r)),h[r]))}zQ(n,UQ.decode(i)),m.push(n),zQ(g,KQ(c[e],h[e])),i.fill(0)}f.clean();const y=VQ(r,a,2*t,o);zQ(y,UQ.decode(g));const b=u.decode(i);return zQ(b,y),uo(c,h,g,y),p.encode([m,b])},decrypt:(e,r)=>{const[n,i]=p.decode(e),s=f.decode(r),o=new Uint16Array(DQ);for(let e=0;e<t;e++)zQ(o,KQ(s[e],UQ.encode(n[e])));return function(e,t){for(let r=0;r<DQ;r++)e[r]=LQ(e[r]-t[r])}(i,UQ.decode(o)),uo(o,s,n),u.encode(i)}}};function $Q(e){const t=HQ(e),{HASH256:r,HASH512:n,KDF:i}=e,{secretCoder:s,cipherTextLen:o}=t,a=t.publicKeyLen,c=ao(t.secretKeyLen,t.publicKeyLen,32,32),u=c.bytesLen;return{publicKeyLen:a,msgLen:32,keygen:(e=so(64))=>{io(e,64);const{publicKey:n,secretKey:i}=t.keygen(e.subarray(0,32)),s=r(n),o=c.encode([i,n,s,e.subarray(32)]);return uo(i,s),{publicKey:n,secretKey:o}},encapsulate:(i,o=so(32))=>{io(i,a),io(o,32);const c=i.subarray(0,384*e.K),u=s.encode(s.decode(c.slice()));if(!oo(u,c))throw uo(u),new Error("ML-KEM.encapsulate: wrong publicKey modulus");uo(u);const l=n.create().update(o).update(r(i)).digest(),h=t.encrypt(i,o,l.subarray(32,64));return l.subarray(32).fill(0),{cipherText:h,sharedSecret:l.subarray(0,32)}},decapsulate:(e,r)=>{io(r,u),io(e,o);const[s,a,l,h]=c.decode(r),d=t.decrypt(e,s),f=n.create().update(d).update(l).digest(),p=f.subarray(0,32),g=t.encrypt(a,d,f.subarray(32,64)),m=oo(e,g),y=i.create({dkLen:32}).update(h).update(e).digest();return uo(d,g,m?y:p),m?p:y}}}const WQ={HASH256:Ys,HASH512:eo,KDF:no,XOF:Hp,PRF:function(e,t,r){return no.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}},JQ=$Q({...WQ,...{N:DQ,Q:BQ,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}}),QQ=Buffer.from("streamr-key-exchange"),ZQ=1568;class YQ{static async encryptForPublicKey(e,t,r){if(r===PH.ML_KEM)return this.encryptWithMLKEMPublicKey(e,t);if(r===PH.RSA)return this.encryptWithRSAPublicKey(e,t);throw new Error(`Unexpected encryption type: ${r}`)}static async decryptWithPrivateKey(e,t,r){if(r===PH.ML_KEM)return this.decryptWithMLKEMPrivateKey(e,t);if(r===PH.RSA)return this.decryptWithRSAPrivateKey(e,t);throw new Error(`Unexpected encryption type: ${r}`)}static toRSAPublicKeyString(e){const t=fw(e);if(!t.startsWith("-----BEGIN PUBLIC KEY-----")||!t.endsWith("-----END PUBLIC KEY-----\n"))throw new Error('"publicKey" must be an RSA public key (SPKI) in PEM format, encoded in UTF-8');return t}static toRSAPrivateKeyString(e){const t=fw(e);if(!t.startsWith("-----BEGIN PRIVATE KEY-----")||!t.endsWith("-----END PRIVATE KEY-----\n"))throw new Error('"privateKey" must be a PKCS#8 RSA private key in PEM format, encoded in UTF-8');return t}static encryptWithRSAPublicKey(e,t){const r=function(e,t){return Pv.publicEncrypt(e,t)}(this.toRSAPublicKeyString(t),e);return r}static decryptWithRSAPrivateKey(e,t){return function(e,t){return Pv.privateDecrypt(e,t)}(this.toRSAPrivateKeyString(t),e)}static async deriveAESWrapperKey(e,t){const r=Tv(),n=await r.importKey("raw",e,{name:"HKDF"},!1,["deriveKey"]),i=await r.deriveKey({name:"HKDF",hash:"SHA-512",salt:t,info:QQ},n,{name:"AES-CTR",length:256},!0,["encrypt","decrypt"]),s=await r.exportKey("raw",i);return new Uint8Array(s)}static async encryptWithMLKEMPublicKey(e,t){const{cipherText:r,sharedSecret:n}=JQ.encapsulate(t);if(r.length!==ZQ)throw new Error(`Expected KEM cipher to be 1568, but it was ${r.length} bytes`);const i=so(64),s=await this.deriveAESWrapperKey(n,i),o=this.encryptWithAES(e,Buffer.from(s));return Buffer.concat([r,i,o])}static async decryptWithMLKEMPrivateKey(e,t){let r=0;const n=e.slice(0,ZQ);r+=ZQ;const i=e.slice(r,r+64);r+=64;const s=e.slice(r),o=JQ.decapsulate(n,t),a=await this.deriveAESWrapperKey(o,i);return this.decryptWithAES(s,Buffer.from(a))}static encryptWithAES(e,t){const r=so(16),n=function(e,t,r){const n=e.toLowerCase();if(dw[n])return hw.createCipheriv(n,t,r);throw new TypeError(`Invalid suite type. In browser only AES is supported but got ${e}.`)}("aes-256-ctr",t,r);return Buffer.concat([r,n.update(e),n.final()])}static decryptWithAES(e,t){const r=function(e,t,r){const n=e.toLowerCase();if(dw[n])return hw.createDecipheriv(n,t,r);throw new TypeError(`Invalid suite type. In browser only AES is supported but got ${e}.`)}("aes-256-ctr",t,e.slice(0,16));return Buffer.concat([r.update(e.slice(16)),r.final()])}static decryptStreamMessage(e,t){let r,n;try{r=this.decryptWithAES(e.content,t.data)}catch{throw new uA("AES decryption failed","DECRYPT_ERROR",e)}if(e.newGroupKey)try{n=t.decryptNextGroupKey(e.newGroupKey)}catch{throw new uA("Could not decrypt new encryption key","DECRYPT_ERROR",e)}return[r,n]}}class XQ extends Error{groupKey;constructor(e,t){super(e),this.groupKey=t}}class eZ{id;data;constructor(e,t){if(this.id=e,!e)throw new XQ(`groupKeyId must not be falsey ${e}`);if(!t)throw new XQ(`groupKeyBufferOrHexString must not be falsey ${t}`);this.data=t,eZ.validate(this)}static validate(e){if(!e)throw new XQ(`value must be a ${this.name}: ${e}`,e);if(!(e instanceof this))throw new XQ(`value must be a ${this.name}: ${e}`,e);if(!e.id||"string"!=typeof e.id)throw new XQ(`${this.name} id must be a string: ${e}`,e);if(e.id.includes("---BEGIN"))throw new XQ(`${this.name} public/private key is not a valid group key id: ${e}`,e);if(!e.data||!Buffer.isBuffer(e.data))throw new XQ(`${this.name} data must be a Buffer: ${e}`,e);if(32!==e.data.length)throw new XQ("Group key must have a size of 256 bits, not "+8*e.data.length,e)}static generate(e=KW("GroupKey")){const t=so(32);return new eZ(e,Buffer.from(t))}encryptNextGroupKey(e){return{id:e.id,data:YQ.encryptWithAES(e.data,this.data)}}decryptNextGroupKey(e){return new eZ(e.id,YQ.decryptWithAES(e.data,this.data))}}const tZ=(e,t)=>t.some((t=>e instanceof t));let rZ,nZ;const iZ=new WeakMap,sZ=new WeakMap,oZ=new WeakMap;let aZ={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return iZ.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return hZ(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function cZ(e){aZ=e(aZ)}function uZ(e){return(nZ||(nZ=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(dZ(this),t),hZ(this.request)}:function(...t){return hZ(e.apply(dZ(this),t))}}function lZ(e){return"function"==typeof e?uZ(e):(e instanceof IDBTransaction&&function(e){if(iZ.has(e))return;const t=new Promise(((t,r)=>{const n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),n()},s=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)}));iZ.set(e,t)}(e),tZ(e,rZ||(rZ=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,aZ):e)}function hZ(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,r)=>{const n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t(hZ(e.result)),n()},s=()=>{r(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",s)}));return oZ.set(t,e),t}(e);if(sZ.has(e))return sZ.get(e);const t=lZ(e);return t!==e&&(sZ.set(e,t),oZ.set(t,e)),t}const dZ=e=>oZ.get(e);const fZ=["get","getKey","getAll","getAllKeys","count"],pZ=["put","add","delete","clear"],gZ=new Map;function mZ(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(gZ.get(t))return gZ.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,i=pZ.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!i&&!fZ.includes(r))return;const s=async function(e,...t){const s=this.transaction(e,i?"readwrite":"readonly");let o=s.store;return n&&(o=o.index(t.shift())),(await Promise.all([o[r](...t),i&&s.done]))[0]};return gZ.set(t,s),s}cZ((e=>({...e,get:(t,r,n)=>mZ(t,r)||e.get(t,r,n),has:(t,r)=>!!mZ(t,r)||e.has(t,r)})));const yZ=["continue","continuePrimaryKey","advance"],bZ={},wZ=new WeakMap,vZ=new WeakMap,EZ={get(e,t){if(!yZ.includes(t))return e[t];let r=bZ[t];return r||(r=bZ[t]=function(...e){wZ.set(this,vZ.get(this)[t](...e))}),r}};async function*AZ(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,EZ);for(vZ.set(r,t),oZ.set(r,dZ(t));t;)yield r,t=await(wZ.get(r)||t.continue()),wZ.delete(r)}function SZ(e,t){return t===Symbol.asyncIterator&&tZ(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&tZ(e,[IDBIndex,IDBObjectStore])}cZ((e=>({...e,get:(t,r,n)=>SZ(t,r)?AZ:e.get(t,r,n),has:(t,r)=>SZ(t,r)||e.has(t,r)})));class kZ{db;static async createInstance(e){const t=await function(e,t,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){const o=indexedDB.open(e,t),a=hZ(o);return n&&o.addEventListener("upgradeneeded",(e=>{n(hZ(o.result),e.oldVersion,e.newVersion,hZ(o.transaction),e)})),r&&o.addEventListener("blocked",(e=>r(e.oldVersion,e.newVersion,e))),a.then((e=>{s&&e.addEventListener("close",(()=>s())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}(`streamr-sdk::${e.ownerId}`,1,{upgrade(t){e.namespaces.forEach((e=>t.createObjectStore(e)))}});return new kZ(t)}constructor(e){this.db=e}async exists(){throw new Error("Method not implemented in browser Persistence.")}async get(e,t){return this.db.get(t,e)}async set(e,t,r){await this.db.put(r,t,e)}async close(){}}var RZ=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},CZ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},IZ=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const PZ={ENCRYPTION_KEYS:"EncryptionKeys",LATEST_ENCRYPTION_KEY_IDS:"LatestEncryptionKeyIds"};let TZ=class{persistence;identity;loggerFactory;constructor(e,t,r){this.identity=e,this.loggerFactory=r,t.onDestroy.listen((()=>{if(void 0!==this.persistence)return this.persistence.close()}))}async ensureInitialized(){this.persistence??=await kZ.createInstance({loggerFactory:this.loggerFactory,ownerId:await this.identity.getUserId(),namespaces:Object.values(PZ),migrationsUrl:new URL("./encryption/migrations","undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:t&&"SCRIPT"===t.tagName.toUpperCase()&&t.src||new URL("exports-umd.min.js",document.baseURI).href)})}async getPersistence(e){return await this.ensureInitialized(),{get:t=>this.persistence.get(t,e),set:(t,r)=>this.persistence.set(t,r,e)}}};TZ=RZ([q(d.ContainerScoped),IZ(0,U(kA)),CZ("design:paramtypes",[RA,dJ,uD])],TZ);var _Z=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},NZ=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};function MZ(e,t){return`${t}::${e}`}function xZ(e,t){return`${e}::${t}`}let OZ=class{persistenceManager;eventEmitter;logger;constructor(e,t,r){this.persistenceManager=e,this.eventEmitter=t,this.logger=r.createLogger("LocalGroupKeyStore")}async get(e,t){const r=await this.persistenceManager.getPersistence(PZ.ENCRYPTION_KEYS),n=await r.get(MZ(e,t));return void 0!==n?new eZ(e,Buffer.from(n,"hex")):void 0}async set(e,t,r){const n=await this.persistenceManager.getPersistence(PZ.ENCRYPTION_KEYS);await n.set(MZ(e,t),Buffer.from(r).toString("hex")),this.logger.debug("Set key",{keyId:e,publisherId:t}),this.eventEmitter.emit("encryptionKeyStoredToLocalStore",e)}async setLatestEncryptionKeyId(e,t,r){const n=await this.persistenceManager.getPersistence(PZ.LATEST_ENCRYPTION_KEY_IDS);this.logger.debug("Set latest encryptionKeyId",{keyId:e,publisherId:t,streamId:r}),await n.set(xZ(t,r),e)}async getLatestEncryptionKeyId(e,t){const r=await this.persistenceManager.getPersistence(PZ.LATEST_ENCRYPTION_KEY_IDS);return await r.get(xZ(e,t))}};var DZ,BZ,LZ,FZ,UZ,jZ,qZ,zZ,KZ,GZ,VZ,HZ,$Z,WZ,JZ,QZ,ZZ,YZ,XZ,eY,tY,rY,nY,iY,sY,oY,aY,cY,uY,lY,hY,dY,fY,pY,gY,mY,yY,bY,wY,vY,EY,AY,SY,kY,RY,CY;function IY(){if(GZ)return KZ;GZ=1;var e=$B(),t=Nh(),r=QB(),n=JB(),i=Object.getOwnPropertySymbols?function(n){for(var i=[];n;)e(i,r(n)),n=t(n);return i}:n;return KZ=i}function PY(){if(WZ)return $Z;WZ=1;var e=WB(),t=IY(),r=Id();return $Z=function(n){return e(n,r,t)},$Z}function TY(){if(iY)return nY;iY=1;var e=Ih(),t=function(){if(YZ)return ZZ;YZ=1;var e=Ih();return ZZ=function(t,r){var n=r?e(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)},ZZ}(),r=function(){if(eY)return XZ;eY=1;var e=/\w*$/;return XZ=function(t){var r=new t.constructor(t.source,e.exec(t));return r.lastIndex=t.lastIndex,r}}(),n=function(){if(rY)return tY;rY=1;var e=Oe(),t=e?e.prototype:void 0,r=t?t.valueOf:void 0;return tY=function(e){return r?Object(r.call(e)):{}}}(),i=Ph();return nY=function(s,o,a){var c=s.constructor;switch(o){case"[object ArrayBuffer]":return e(s);case"[object Boolean]":case"[object Date]":return new c(+s);case"[object DataView]":return t(s,a);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return i(s,a);case"[object Map]":case"[object Set]":return new c;case"[object Number]":case"[object String]":return new c(s);case"[object RegExp]":return r(s);case"[object Symbol]":return n(s)}},nY}function _Y(){if(cY)return aY;cY=1;var e=function(){if(oY)return sY;oY=1;var e=XB(),t=Be();return sY=function(r){return t(r)&&"[object Map]"==e(r)}}(),t=Qc(),r=Ed(),n=r&&r.isMap,i=n?t(n):e;return aY=i}function NY(){if(dY)return hY;dY=1;var e=function(){if(lY)return uY;lY=1;var e=XB(),t=Be();return uY=function(r){return t(r)&&"[object Set]"==e(r)}}(),t=Qc(),r=Ed(),n=r&&r.isSet,i=n?t(n):e;return hY=i}function MY(){if(pY)return fY;pY=1;var e=Yl(),t=(BZ||(BZ=1,DZ=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e}),DZ),r=Rl(),n=function(){if(FZ)return LZ;FZ=1;var e=kd(),t=rA();return LZ=function(r,n){return r&&e(n,t(n),r)},LZ}(),i=function(){if(jZ)return UZ;jZ=1;var e=kd(),t=Id();return UZ=function(r,n){return r&&e(n,t(n),r)},UZ}(),s=Rh(),o=Th(),a=function(){if(zZ)return qZ;zZ=1;var e=kd(),t=QB();return qZ=function(r,n){return e(r,t(r),n)},qZ}(),c=function(){if(HZ)return VZ;HZ=1;var e=kd(),t=IY();return VZ=function(r,n){return e(r,t(r),n)},VZ}(),u=ZB(),l=PY(),h=XB(),d=function(){if(QZ)return JZ;QZ=1;var e=Object.prototype.hasOwnProperty;return JZ=function(t){var r=t.length,n=new t.constructor(r);return r&&"string"==typeof t[0]&&e.call(t,"index")&&(n.index=t.index,n.input=t.input),n},JZ}(),f=TY(),p=xh(),g=qu(),m=Kh(),y=_Y(),b=Ne(),w=NY(),v=rA(),E=Id(),A="[object Arguments]",S="[object Function]",k="[object Object]",R={};return R[A]=R["[object Array]"]=R["[object ArrayBuffer]"]=R["[object DataView]"]=R["[object Boolean]"]=R["[object Date]"]=R["[object Float32Array]"]=R["[object Float64Array]"]=R["[object Int8Array]"]=R["[object Int16Array]"]=R["[object Int32Array]"]=R["[object Map]"]=R["[object Number]"]=R[k]=R["[object RegExp]"]=R["[object Set]"]=R["[object String]"]=R["[object Symbol]"]=R["[object Uint8Array]"]=R["[object Uint8ClampedArray]"]=R["[object Uint16Array]"]=R["[object Uint32Array]"]=!0,R["[object Error]"]=R[S]=R["[object WeakMap]"]=!1,fY=function C(I,P,T,_,N,M){var x,O=1&P,D=2&P,B=4&P;if(T&&(x=N?T(I,_,N,M):T(I)),void 0!==x)return x;if(!b(I))return I;var L=g(I);if(L){if(x=d(I),!O)return o(I,x)}else{var F=h(I),U=F==S||"[object GeneratorFunction]"==F;if(m(I))return s(I,O);if(F==k||F==A||U&&!N){if(x=D||U?{}:p(I),!O)return D?c(I,i(x,I)):a(I,n(x,I))}else{if(!R[F])return N?I:{};x=f(I,F,O)}}M||(M=new e);var j=M.get(I);if(j)return j;M.set(I,x),w(I)?I.forEach((function(e){x.add(C(e,P,T,e,I,M))})):y(I)&&I.forEach((function(e,t){x.set(t,C(e,P,T,t,I,M))}));var q=L?void 0:(B?D?l:u:D?E:v)(I);return t(q||I,(function(e,t){q&&(e=I[t=e]),r(x,t,C(e,P,T,t,I,M))})),x},fY}function xY(){if(vY)return wY;vY=1;var e=$B(),t=function(){if(bY)return yY;bY=1;var e=Oe(),t=Oh(),r=qu(),n=e?e.isConcatSpreadable:void 0;return yY=function(e){return r(e)||t(e)||!!(n&&e&&e[n])}}();return wY=function r(n,i,s,o,a){var c=-1,u=n.length;for(s||(s=t),a||(a=[]);++c<u;){var l=n[c];i>0&&s(l)?i>1?r(l,i-1,s,o,a):e(a,l):o||(a[a.length]=l)}return a},wY}function OY(){if(kY)return SY;kY=1;var e=function(){if(AY)return EY;AY=1;var e=xY();return EY=function(t){return null!=t&&t.length?e(t,1):[]},EY}(),t=Xc(),r=ru();return SY=function(n){return r(t(n,void 0,e),n+"")}}OZ=_Z([q(d.ContainerScoped),NZ("design:paramtypes",[TZ,sD,uD])],OZ);var DY=function(){if(CY)return RY;CY=1;var e=Jc(),t=MY(),r=VJ(),n=Pl(),i=kd(),s=function(){if(mY)return gY;mY=1;var e=Gh();return gY=function(t){return e(t)?void 0:t}}(),o=OY(),a=PY(),c=o((function(o,c){var u={};if(null==o)return u;var l=!1;c=e(c,(function(e){return e=n(e,o),l||(l=e.length>1),e})),i(o,a(o),u),l&&(u=t(u,7,s));for(var h=c.length;h--;)r(u,c[h]);return u}));return RY=c}(),BY=n(DY),LY=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},FY=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let UY=class{theGraphClient;logger;constructor(e,t){this.theGraphClient=e,this.logger=t.createLogger("OperatorRegistry")}async findRandomNetworkEntrypoints(e,t,r){const n=this.theGraphClient.queryEntities((()=>({query:`{\n operators(\n orderBy: latestHeartbeatTimestamp\n orderDirection: desc\n first: ${t}\n where: {\n latestHeartbeatMetadata_contains: "\\"tls\\":true", \n latestHeartbeatTimestamp_gt: "${Math.floor(Date.now()/1e3)-60*r*60}"\n }\n ) {\n id\n latestHeartbeatMetadata\n }\n }`}))),i=[];for await(const e of n)i.push(JSON.parse(e.latestHeartbeatMetadata));const s=JU(i).slice(0,e);return this.logger.debug(`Found ${i.length} network entrypoints, picked ${s.length}`,{picked:s}),s}async findOperatorsOnStream(e,t,r){const n={query:`{\n stream(id: "${e}") {\n sponsorships(where: { isRunning: true }) {\n stakes(first: ${t}, orderBy: updateTimestamp, orderDirection: desc) {\n operator (\n where: {\n latestHeartbeatMetadata_contains: "\\"tls\\":true", \n latestHeartbeatTimestamp_gt: "${Math.floor(Date.now()/1e3)-60*r*60}"\n }\n ) {\n id\n latestHeartbeatMetadata\n }\n }\n }\n }\n }`},i=(await this.theGraphClient.queryEntity(n)).stream.sponsorships.flatMap((e=>e.stakes.map((e=>({operatorId:nb(e.operator.id),peerDescriptor:JSON.parse(e.operator.latestHeartbeatMetadata)})))));return i}};UY=LY([q(d.ContainerScoped),FY("design:paramtypes",[lE,uD])],UY);const jY=new class extends wF{constructor(){super("google.protobuf.Empty",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();{let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};const qY=new class extends wF{constructor(){super("google.protobuf.Any",[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}])}pack(e,t){return{typeUrl:this.typeNameToUrl(t.typeName),value:t.toBinary(e)}}unpack(e,t,r){if(!this.contains(e,t))throw new Error("Cannot unpack google.protobuf.Any with typeUrl '"+e.typeUrl+"' as "+t.typeName+".");return t.fromBinary(e.value,r)}contains(e,t){if(!e.typeUrl.length)return!1;return("string"==typeof t?t:t.typeName)===this.typeUrlToName(e.typeUrl)}internalJsonWrite(e,t){if(""===e.typeUrl)return{};let r=this.typeUrlToName(e.typeUrl),n=QL(t),i=n.typeRegistry?.find((e=>e.typeName===r));if(!i)throw new globalThis.Error("Unable to convert google.protobuf.Any with typeUrl '"+e.typeUrl+"' to JSON. The specified type "+r+" is not available in the type registry.");let s=i.fromBinary(e.value,{readUnknownField:!1}),o=i.internalJsonWrite(s,n);return!r.startsWith("google.protobuf.")&&wL(o)||(o={value:o}),o["@type"]=e.typeUrl,o}internalJsonRead(e,t,r){if(!wL(e))throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON "+bL(e)+".");if("string"!=typeof e["@type"]||""==e["@type"])return this.create();let n,i=this.typeUrlToName(e["@type"]),s=t?.typeRegistry?.find((e=>e.typeName==i));if(!s)throw new globalThis.Error("Unable to parse google.protobuf.Any from JSON. The specified type "+i+" is not available in the type registry.");if(i.startsWith("google.protobuf.")&&e.hasOwnProperty("value"))n=s.fromJson(e.value,t);else{let r=Object.assign({},e);delete r["@type"],n=s.fromJson(r,t)}return void 0===r&&(r=this.create()),r.typeUrl=e["@type"],r.value=s.toBinary(n),r}typeNameToUrl(e){if(!e.length)throw new Error("invalid type name: "+e);return"type.googleapis.com/"+e}typeUrlToName(e){if(!e.length)throw new Error("invalid type url: "+e);let t=e.lastIndexOf("/"),r=t>0?e.substring(t+1):e;if(!r.length)throw new Error("invalid type url: "+e);return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.typeUrl="",t.value=new Uint8Array(0),void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.typeUrl=e.string();break;case 2:i.value=e.bytes();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){""!==e.typeUrl&&t.tag(1,SL.LengthDelimited).string(e.typeUrl),e.value.length&&t.tag(2,SL.LengthDelimited).bytes(e.value);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var zY;!function(e){e[e.SERVER_TIMEOUT=0]="SERVER_TIMEOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.UNKNOWN_RPC_METHOD=2]="UNKNOWN_RPC_METHOD",e[e.CLIENT_ERROR=3]="CLIENT_ERROR",e[e.SERVER_ERROR=4]="SERVER_ERROR"}(zY||(zY={}));const KY=new class extends wF{constructor(){super("protorpc.RpcMessage",[{no:1,name:"header",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:2,name:"body",kind:"message",T:()=>qY},{no:3,name:"requestId",kind:"scalar",T:9},{no:4,name:"errorType",kind:"enum",opt:!0,T:()=>["protorpc.RpcErrorType",zY]},{no:5,name:"errorClassName",kind:"scalar",opt:!0,T:9},{no:6,name:"errorCode",kind:"scalar",opt:!0,T:9},{no:7,name:"errorMessage",kind:"scalar",opt:!0,T:9}])}};new class extends wF{constructor(){super("protorpc.Mnfo2uhnf92hvqi2nviouq2hv9puhq",[{no:1,name:"empty",kind:"message",T:()=>jY}])}};const GY=new class extends wF{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:2},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=UL.from(Math.floor(t/1e3)).toNumber(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(1e3*UL.from(e.seconds).toNumber()+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=UL.from(Math.floor(r/1e3)).toNumber(),t.nanos=1e6*(r%1e3+(r<0&&r%1e3!=0?1e3:0)),t}internalJsonWrite(e,t){let r=1e3*UL.from(e.seconds).toNumber();if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if("string"!=typeof e)throw new Error("Unable to parse Timestamp from JSON "+bL(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=UL.from(i/1e3).toNumber(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0,t.nanos=0,void 0!==e&&dF(this,t,e),t}internalBinaryRead(e,t,r,n){let i=n??this.create(),s=e.pos+t;for(;e.pos<s;){let[t,n]=e.tag();switch(t){case 1:i.seconds=e.int64().toNumber();break;case 2:i.nanos=e.int32();break;default:let s=r.readUnknownField;if("throw"===s)throw new globalThis.Error(`Unknown field ${t} (wire type ${n}) for ${this.typeName}`);let o=e.skip(n);!1!==s&&(!0===s?AL.onRead:s)(this.typeName,i,t,n,o)}}return i}internalBinaryWrite(e,t,r){0!==e.seconds&&t.tag(1,SL.Varint).int64(e.seconds),0!==e.nanos&&t.tag(2,SL.Varint).int32(e.nanos);let n=r.writeUnknownFields;return!1!==n&&(1==n?AL.onWrite:n)(this.typeName,e,t),t}};var VY,HY,$Y,WY,JY,QY;!function(e){e[e.FIND_CLOSEST_NODES=0]="FIND_CLOSEST_NODES",e[e.FETCH_DATA=1]="FETCH_DATA",e[e.DELETE_DATA=2]="DELETE_DATA"}(VY||(VY={})),function(e){e[e.NODEJS=0]="NODEJS",e[e.BROWSER=1]="BROWSER"}(HY||(HY={})),function(e){e[e.SERVER_TIMOUT=0]="SERVER_TIMOUT",e[e.CLIENT_TIMEOUT=1]="CLIENT_TIMEOUT",e[e.SERVER_ERROR=2]="SERVER_ERROR",e[e.UNKNOWN_RPC_METHOD=3]="UNKNOWN_RPC_METHOD"}($Y||($Y={})),function(e){e[e.NO_TARGETS=0]="NO_TARGETS",e[e.DUPLICATE=1]="DUPLICATE",e[e.STOPPED=2]="STOPPED"}(WY||(WY={})),function(e){e[e.DUPLICATE_CONNECTION=0]="DUPLICATE_CONNECTION",e[e.INVALID_TARGET_PEER_DESCRIPTOR=1]="INVALID_TARGET_PEER_DESCRIPTOR",e[e.UNSUPPORTED_PROTOCOL_VERSION=2]="UNSUPPORTED_PROTOCOL_VERSION"}(JY||(JY={})),function(e){e[e.NORMAL=0]="NORMAL",e[e.LEAVING=1]="LEAVING"}(QY||(QY={}));const ZY=new class extends wF{constructor(){super("dht.StoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>qY},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>GY},{no:5,name:"ttl",kind:"scalar",T:13}])}};const YY=new class extends wF{constructor(){super("dht.StoreDataResponse",[])}};const XY=new class extends wF{constructor(){super("dht.ExternalStoreDataRequest",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>qY}])}};const eX=new class extends wF{constructor(){super("dht.ExternalStoreDataResponse",[{no:1,name:"storers",kind:"message",repeat:2,T:()=>dX}])}};const tX=new class extends wF{constructor(){super("dht.ReplicateDataRequest",[{no:1,name:"entry",kind:"message",T:()=>rX}])}};const rX=new class extends wF{constructor(){super("dht.DataEntry",[{no:1,name:"key",kind:"scalar",T:12},{no:2,name:"data",kind:"message",T:()=>qY},{no:3,name:"creator",kind:"scalar",T:12},{no:4,name:"createdAt",kind:"message",T:()=>GY},{no:5,name:"storedAt",kind:"message",T:()=>GY},{no:6,name:"ttl",kind:"scalar",T:13},{no:7,name:"stale",kind:"scalar",T:8},{no:8,name:"deleted",kind:"scalar",T:8}])}};const nX=new class extends wF{constructor(){super("dht.ClosestPeersRequest",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const iX=new class extends wF{constructor(){super("dht.ClosestPeersResponse",[{no:1,name:"peers",kind:"message",repeat:2,T:()=>dX},{no:2,name:"requestId",kind:"scalar",T:9}])}};const sX=new class extends wF{constructor(){super("dht.ClosestRingPeersRequest",[{no:1,name:"ringId",kind:"scalar",T:12},{no:2,name:"requestId",kind:"scalar",T:9}])}};const oX=new class extends wF{constructor(){super("dht.ClosestRingPeersResponse",[{no:1,name:"leftPeers",kind:"message",repeat:2,T:()=>dX},{no:2,name:"rightPeers",kind:"message",repeat:2,T:()=>dX},{no:3,name:"requestId",kind:"scalar",T:9}])}};const aX=new class extends wF{constructor(){super("dht.RecursiveOperationRequest",[{no:1,name:"sessionId",kind:"scalar",T:9},{no:2,name:"operation",kind:"enum",T:()=>["dht.RecursiveOperation",VY]}])}};const cX=new class extends wF{constructor(){super("dht.RecursiveOperationResponse",[{no:1,name:"closestConnectedNodes",kind:"message",repeat:2,T:()=>dX},{no:2,name:"dataEntries",kind:"message",repeat:2,T:()=>rX},{no:3,name:"noCloserNodesFound",kind:"scalar",T:8},{no:4,name:"routingPath",kind:"message",repeat:2,T:()=>dX}])}};const uX=new class extends wF{constructor(){super("dht.PingRequest",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const lX=new class extends wF{constructor(){super("dht.PingResponse",[{no:1,name:"requestId",kind:"scalar",T:9}])}};const hX=new class extends wF{constructor(){super("dht.LeaveNotice",[])}};const dX=new class extends wF{constructor(){super("dht.PeerDescriptor",[{no:1,name:"nodeId",kind:"scalar",T:12},{no:2,name:"type",kind:"enum",T:()=>["dht.NodeType",HY]},{no:3,name:"udp",kind:"message",T:()=>fX},{no:4,name:"tcp",kind:"message",T:()=>fX},{no:5,name:"websocket",kind:"message",T:()=>fX},{no:6,name:"region",kind:"scalar",opt:!0,T:13},{no:7,name:"ipAddress",kind:"scalar",opt:!0,T:13},{no:8,name:"publicKey",kind:"scalar",opt:!0,T:12},{no:9,name:"signature",kind:"scalar",opt:!0,T:12}])}};const fX=new class extends wF{constructor(){super("dht.ConnectivityMethod",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"host",kind:"scalar",T:9},{no:3,name:"tls",kind:"scalar",T:8}])}};const pX=new class extends wF{constructor(){super("dht.RouteMessageWrapper",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"sourcePeer",kind:"message",T:()=>dX},{no:3,name:"target",kind:"scalar",T:12},{no:4,name:"message",kind:"message",T:()=>vX},{no:5,name:"reachableThrough",kind:"message",repeat:2,T:()=>dX},{no:6,name:"routingPath",kind:"message",repeat:2,T:()=>dX},{no:7,name:"parallelRootNodeIds",kind:"scalar",repeat:2,T:9}])}};const gX=new class extends wF{constructor(){super("dht.RouteMessageAck",[{no:1,name:"requestId",kind:"scalar",T:9},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.RouteMessageError",WY]}])}};const mX=new class extends wF{constructor(){super("dht.ConnectivityRequest",[{no:1,name:"port",kind:"scalar",T:13},{no:2,name:"tls",kind:"scalar",T:8},{no:3,name:"host",kind:"scalar",opt:!0,T:9},{no:4,name:"allowSelfSignedCertificate",kind:"scalar",T:8}])}};const yX=new class extends wF{constructor(){super("dht.ConnectivityResponse",[{no:1,name:"host",kind:"scalar",T:9},{no:2,name:"natType",kind:"scalar",T:9},{no:3,name:"websocket",kind:"message",T:()=>fX},{no:4,name:"ipAddress",kind:"scalar",T:13},{no:5,name:"protocolVersion",kind:"scalar",T:9},{no:6,name:"latitude",kind:"scalar",opt:!0,T:1},{no:7,name:"longitude",kind:"scalar",opt:!0,T:1}])}};const bX=new class extends wF{constructor(){super("dht.HandshakeRequest",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>dX},{no:2,name:"targetPeerDescriptor",kind:"message",T:()=>dX},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const wX=new class extends wF{constructor(){super("dht.HandshakeResponse",[{no:1,name:"sourcePeerDescriptor",kind:"message",T:()=>dX},{no:2,name:"error",kind:"enum",opt:!0,T:()=>["dht.HandshakeError",JY]},{no:3,name:"protocolVersion",kind:"scalar",T:9},{no:4,name:"applicationVersion",kind:"scalar",T:9}])}};const vX=new class extends wF{constructor(){super("dht.Message",[{no:1,name:"messageId",kind:"scalar",T:9},{no:2,name:"sourceDescriptor",kind:"message",T:()=>dX},{no:3,name:"targetDescriptor",kind:"message",T:()=>dX},{no:4,name:"serviceId",kind:"scalar",T:9},{no:5,name:"rpcMessage",kind:"message",oneof:"body",T:()=>KY},{no:6,name:"connectivityRequest",kind:"message",oneof:"body",T:()=>mX},{no:7,name:"connectivityResponse",kind:"message",oneof:"body",T:()=>yX},{no:8,name:"handshakeRequest",kind:"message",oneof:"body",T:()=>bX},{no:9,name:"handshakeResponse",kind:"message",oneof:"body",T:()=>wX},{no:10,name:"recursiveOperationRequest",kind:"message",oneof:"body",T:()=>aX}])}};const EX=new class extends wF{constructor(){super("dht.WebsocketConnectionRequest",[])}};const AX=new class extends wF{constructor(){super("dht.WebrtcConnectionRequest",[])}};const SX=new class extends wF{constructor(){super("dht.RtcOffer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const kX=new class extends wF{constructor(){super("dht.RtcAnswer",[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"connectionId",kind:"scalar",T:9}])}};const RX=new class extends wF{constructor(){super("dht.IceCandidate",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"connectionId",kind:"scalar",T:9}])}};const CX=new class extends wF{constructor(){super("dht.LockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const IX=new class extends wF{constructor(){super("dht.UnlockRequest",[{no:1,name:"lockId",kind:"scalar",T:9}])}};const PX=new class extends wF{constructor(){super("dht.LockResponse",[{no:1,name:"accepted",kind:"scalar",T:8}])}};const TX=new class extends wF{constructor(){super("dht.DisconnectNotice",[{no:1,name:"disconnectMode",kind:"enum",T:()=>["dht.DisconnectMode",QY]}])}};const _X=new class extends wF{constructor(){super("dht.SetPrivateRequest",[{no:1,name:"isPrivate",kind:"scalar",T:8}])}};const NX=new class extends wF{constructor(){super("dht.ExternalFetchDataRequest",[{no:1,name:"key",kind:"scalar",T:12}])}};const MX=new class extends wF{constructor(){super("dht.ExternalFetchDataResponse",[{no:1,name:"entries",kind:"message",repeat:2,T:()=>rX}])}};const xX=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesRequest",[{no:1,name:"nodeId",kind:"scalar",T:12}])}};const OX=new class extends wF{constructor(){super("dht.ExternalFindClosestNodesResponse",[{no:1,name:"closestNodes",kind:"message",repeat:2,T:()=>dX}])}};new vF("dht.DhtNodeRpc",[{name:"getClosestPeers",options:{},I:nX,O:iX},{name:"getClosestRingPeers",options:{},I:sX,O:oX},{name:"ping",options:{},I:uX,O:lX},{name:"leaveNotice",options:{},I:hX,O:jY}]),new vF("dht.RouterRpc",[{name:"routeMessage",options:{},I:pX,O:gX},{name:"forwardMessage",options:{},I:pX,O:gX}]),new vF("dht.RecursiveOperationRpc",[{name:"routeRequest",options:{},I:pX,O:gX}]),new vF("dht.StoreRpc",[{name:"storeData",options:{},I:ZY,O:YY},{name:"replicateData",options:{},I:tX,O:jY}]),new vF("dht.RecursiveOperationSessionRpc",[{name:"sendResponse",options:{},I:cX,O:jY}]),new vF("dht.WebsocketClientConnectorRpc",[{name:"requestConnection",options:{},I:EX,O:jY}]),new vF("dht.WebrtcConnectorRpc",[{name:"requestConnection",options:{},I:AX,O:jY},{name:"rtcOffer",options:{},I:SX,O:jY},{name:"rtcAnswer",options:{},I:kX,O:jY},{name:"iceCandidate",options:{},I:RX,O:jY}]),new vF("dht.ConnectionLockRpc",[{name:"lockRequest",options:{},I:CX,O:PX},{name:"unlockRequest",options:{},I:IX,O:jY},{name:"gracefulDisconnect",options:{},I:TX,O:jY},{name:"setPrivate",options:{},I:_X,O:jY}]),new vF("dht.ExternalApiRpc",[{name:"externalFetchData",options:{},I:NX,O:MX},{name:"externalStoreData",options:{},I:XY,O:eX},{name:"externalFindClosestNodes",options:{},I:xX,O:OX}]);const DX=new class extends wF{constructor(){super("OperatorDiscoveryRequest",[{no:1,name:"streamPartId",kind:"scalar",T:9}])}};const BX=new class extends wF{constructor(){super("OperatorDiscoveryResponse",[{no:1,name:"operators",kind:"message",repeat:2,T:()=>dX}])}},LX=new vF("OperatorDiscovery",[{name:"discoverOperators",options:{},I:DX,O:BX}]);class FX{_transport;typeName=LX.typeName;methods=LX.methods;options=LX.options;constructor(e){this._transport=e}discoverOperators(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return IF(0,this._transport,r,n,e)}}var UX=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},jX=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},qX=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let zX=class{createNetworkNode(e){return(e=>new EW(new vW(e)))(e)}};zX=UX([q(d.ContainerScoped)],zX);const KX=new Bv("NetworkNodeFacade");let GX=class{cachedNode;startNodeCalled=!1;startNodeComplete=!1;messageListeners=[];networkNodeFactory;operatorRegistry;config;identity;eventEmitter;destroySignal;constructor(e,t,r,n,i){this.networkNodeFactory=e,this.operatorRegistry=t,this.config=r,this.identity=n,this.eventEmitter=new Sl,this.destroySignal=i,i.onDestroy.listen(this.destroy)}async getNetworkOptions(){const e=await this.getEntryPoints(),t=this.config.network.controlLayer.peerDescriptor?WW(this.config.network.controlLayer.peerDescriptor):void 0;return{layer0:{...this.config.network.controlLayer,entryPoints:e.map(WW),peerDescriptor:t,websocketPortRange:null!==this.config.network.controlLayer.websocketPortRange?this.config.network.controlLayer.websocketPortRange:void 0},networkNode:{...BY(this.config.network.node,"contentDeliveryBufferWhileConnecting"),bufferWhileConnecting:this.config.network.node.contentDeliveryBufferWhileConnecting},metricsContext:new $v}}destroy=nJ((async()=>{const e=this.cachedNode;if(this.cachedNode=void 0,e&&this.startNodeCalled){if(!this.startNodeComplete){const e=this.startNodeTask();this.startNodeTask.reset(),await e}await e.stop()}this.startNodeTask.reset()}));startNodeTask=nJ((async(e=!0)=>{this.startNodeCalled=!0;try{const t=await this.initNode();return this.destroySignal.isDestroyed()||await t.start(e),t.addMessageListener((e=>{if(this.messageListeners.length>0)try{const t=TW.toClientProtocol(e);for(const e of this.messageListeners)e(t)}catch(e){KX.trace("Could not translate message",{err:e})}})),this.destroySignal.isDestroyed()?await t.stop():this.eventEmitter.emit("start"),this.destroySignal.assertNotDestroyed(),t}finally{this.startNodeComplete=!0}}));async initNode(){if(this.destroySignal.assertNotDestroyed(),this.cachedNode)return this.cachedNode;const e=this.networkNodeFactory.createNetworkNode(await this.getNetworkOptions());return this.destroySignal.isDestroyed()||(this.cachedNode=e),e}startNode=this.startNodeTask;getNode(){return this.destroySignal.assertNotDestroyed(),this.startNodeTask()}async getNodeId(){return(await this.getNode()).getNodeId()}async join(e,t,r){const n=await this.getNode();await n.join(e,t,r)}async leave(e){const t=await this.getNode();await t.leave(e)}async broadcast(e,t){(await this.getNode()).broadcast(TW.toProtobuf(e),t)}addMessageListener(e){this.messageListeners.push(e)}removeMessageListener(e){Ej(this.messageListeners,e)}async isProxiedStreamPart(e){return(await this.getNode()).isProxiedStreamPart(e)}async getMetricsContext(){return(await this.getNode()).getMetricsContext()}async getPeerDescriptor(){return(await this.getNode()).getPeerDescriptor()}async getDiagnosticInfo(){return(await this.getNode()).getDiagnosticInfo()}async getStreamParts(){return(await this.getNode()).getStreamParts()}async getNeighbors(e){return(await this.getNode()).getNeighbors(e)}async getOptions(){return(await this.getNode()).getOptions()}async inspect(e,t){this.isStarting()&&await this.startNodeTask(!1);const r=WW(e);return this.cachedNode.inspect(r,t)}async setProxies(e,t,r,n){this.isStarting()&&await this.startNodeTask(!1);const i=t.map(WW);await this.cachedNode.setProxies(e,i,await this.identity.getUserId(),r,n)}async setStreamPartEntryPoints(e,t){this.isStarting()&&await this.startNodeTask(!1);const r=t.map(WW);this.cachedNode.setStreamPartEntryPoints(e,r)}async discoverOperators(e,t){const r=await this.createExternalRpcClient(FX);return(await r.discoverOperators(DX.create({streamPartId:t}),{sourceDescriptor:await this.getPeerDescriptor(),targetDescriptor:WW(e)})).operators.map((e=>JW(e)))}async createExternalRpcClient(e){return this.isStarting()&&await this.startNodeTask(!1),this.cachedNode.createExternalRpcClient(e)}async registerOperator(e){(await this.getNode()).registerExternalNetworkRpcMethod(DX,BX,"discoverOperators",(async t=>{const r=AE.parse(t.streamPartId),n=e.getAssignedNodesForStreamPart(r);return BX.create({operators:n.map((e=>WW(e)))})}))}isStarting(){return!this.cachedNode||!this.startNodeComplete}once(e,t){this.eventEmitter.once(e,t)}async getEntryPoints(){const e=this.config.network.controlLayer.entryPointDiscovery,t=e?.enabled?await this.operatorRegistry.findRandomNetworkEntrypoints(e.maxEntryPoints,e.maxQueryResults,e.maxHeartbeatAgeHours):[];return[...this.config.network.controlLayer.entryPoints,...t]}};GX=UX([q(d.ContainerScoped),qX(2,U(cA)),qX(3,U(kA)),jX("design:paramtypes",[zX,UY,Object,RA,dJ])],GX);const VX=()=>Wv(20),HX=t=>{const r=Buffer.concat([Buffer.from(`${t.messageId.streamId}${t.messageId.streamPartition}${t.messageId.timestamp}${t.messageId.sequenceNumber}${t.messageId.publisherId}${t.messageId.msgChainId}`),void 0!==t.prevMsgRef?Buffer.from(`${t.prevMsgRef.timestamp}${t.prevMsgRef.sequenceNumber}`):new Uint8Array(0)]);if(t.messageType===e.StreamMessageType.MESSAGE){const e=t.newGroupKey?Buffer.from(t.newGroupKey.id):void 0;return Buffer.concat([r,t.content,e??new Uint8Array(0),t.newGroupKey?.data??new Uint8Array(0)])}if(t.messageType===e.StreamMessageType.GROUP_KEY_REQUEST){const e=DH.fromBinary(t.content);return Buffer.concat([r,pw(e.requestId),e.recipientId,e.publicKey,Buffer.concat(e.groupKeyIds.map((e=>pw(e))))])}if(t.messageType===e.StreamMessageType.GROUP_KEY_RESPONSE){const e=BH.fromBinary(t.content);return Buffer.concat([r,pw(e.requestId),e.recipientId,Buffer.concat(e.groupKeys.map((e=>Buffer.concat([pw(e.id),e.data]))))])}throw new Error(`Assertion failed: unknown message type ${t.messageType}`)};var $X=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},WX=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},JX=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};e.MessageSigner=class{identity;constructor(e){this.identity=e}async createSignedMessage(e,t){const r=await this.identity.createMessageSignature(HX(e));return new PW({...e,signature:r,signatureType:t})}},e.MessageSigner=$X([q(d.ContainerScoped),JX(0,U(kA)),WX("design:paramtypes",[RA])],e.MessageSigner);var QX=["function isValidSignature(bytes32 hash, bytes signature) view returns (bytes4 magicValue)"],ZX=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},YX=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const XX=new TE;let e0=class{contractsByAddress;publisherCache=new yE((()=>6e5));constructor(e,t){this.contractsByAddress=BJ({valueFactory:async r=>e.createReadContract(r,QX,t.getProvider(),"erc1271Contract")})}async isValidSignature(e,t,r){const n=function(e,t){return`${e}_${t}`}(e,kE(XX.recoverSignerUserId(r,t))),i=this.publisherCache.get(n);if(void 0!==i)return i;{const i=await this.contractsByAddress.get(e),s="0x1626ba7e"===await i.isValidSignature(XX.keccakHash(t),r);return this.publisherCache.set(n,s),s}}};e0=ZX([q(d.ContainerScoped),YX("design:paramtypes",[SD,e.RpcProviderSource])],e0);const t0=t=>{const r=void 0!==t.prevMsgRef?`${t.prevMsgRef.timestamp}${t.prevMsgRef.sequenceNumber}`:"",n=void 0!==t.newGroupKey?(({id:e,data:t})=>JSON.stringify([e,gw(t)]))(t.newGroupKey):"",i=t.encryptionType===e.EncryptionType.NONE?fw(t.content):gw(t.content);return Buffer.from(`${t.messageId.streamId}${t.messageId.streamPartition}${t.messageId.timestamp}${t.messageId.sequenceNumber}${t.messageId.publisherId}${t.messageId.msgChainId}${r}${i}${n}`)};class r0 extends RA{publicKeyString;publicKey;privateKey;constructor(e,t){super(),this.publicKey=e,this.privateKey=t,this.publicKeyString=kE(this.publicKey),this.assertValidKeyPair()}async getUserIdRaw(){return this.publicKey}async getUserId(){return this.publicKeyString}async getPrivateKey(){return this.privateKey}async getTransactionSigner(e){throw new Error("This key pair can not sign transactions!")}static getKeyPairFromConfig(e){const t=e.auth;if(!t.privateKey)throw new Error("A privateKey was expected in the config, but none is defined!");return t}}const n0=new TE;class i0 extends r0{assertValidKeyPair(){n0.assertValidKeyPair(this.publicKey,this.privateKey)}getSignatureType(){return e.SignatureType.ECDSA_SECP256K1_EVM}async createMessageSignature(e){return n0.createSignature(e,this.privateKey)}async getTransactionSigner(e){const t=e.getProvider();return new GO(gw(this.privateKey),t)}static fromConfig(e){const t=e.auth.privateKey,r=e.auth.publicKey;return i0.fromPrivateKey(t,r)}static fromPrivateKey(e,t){return new i0(mw(t??new GO(e).address),mw(e))}static generate(){const e=n0.generateKeyPair();return new i0(e.publicKey,e.privateKey)}}class s0 extends RA{provider;expectedChainId;signer;cachedUserIdString;cachedUserIdBytes;rateLimitedSigner;constructor(e,t){super(),this.provider=e,this.expectedChainId=t,this.signer=e.getSigner(),this.rateLimitedSigner=rJ((async e=>{const t=await(await this.signer).signMessage(e);return await Qv(50),mw(t)}),1)}async getUserIdRaw(){return this.cachedUserIdBytes??=RE(await this.getUserId()),this.cachedUserIdBytes}async getUserId(){return this.cachedUserIdString??=kE(await(await this.signer).getAddress()),this.cachedUserIdString}getSignatureType(){return e.SignatureType.ECDSA_SECP256K1_EVM}async createMessageSignature(e){return this.rateLimitedSigner(e)}async getTransactionSigner(){if(void 0===this.expectedChainId)throw new Error("Streamr chainId not configuredin the StreamrClient options!");const e=(await this.provider.getNetwork()).chainId;if(e!==BigInt(this.expectedChainId))throw new Error(`Connect your wallet to the chain with chainId ${this.expectedChainId} (chainId of currently selected chain is ${e})`);return this.signer}static fromConfig(e){const t=e.auth?.ethereum,r=new Ex(t);return new s0(r,e.contracts.ethereumNetwork.chainId)}}const o0=PE.getInstance("ML_DSA_87");class a0 extends r0{assertValidKeyPair(){o0.assertValidKeyPair(this.publicKey,this.privateKey)}getSignatureType(){return e.SignatureType.ML_DSA_87}async createMessageSignature(e){return o0.createSignature(e,this.privateKey)}static fromConfig(e){const t=r0.getKeyPairFromConfig(e);if(!t.publicKey)throw new Error("ML-DSA identity requires a publicKey to be given in the config!");return new a0(mw(t.publicKey),mw(t.privateKey))}static generate(){const e=o0.generateKeyPair();return new a0(e.publicKey,e.privateKey)}}const c0=new _E;class u0 extends r0{cachedJWK;assertValidKeyPair(){c0.assertValidKeyPair(this.publicKey,this.privateKey)}getSignatureType(){return e.SignatureType.ECDSA_SECP256R1}async createMessageSignature(e){return this.cachedJWK??=c0.privateKeyToJWK(this.privateKey),c0.createSignature(e,this.cachedJWK)}static fromConfig(e){const t=r0.getKeyPairFromConfig(e),r=mw(t.privateKey),n=t.publicKey?mw(t.publicKey):c0.getPublicKeyFromPrivateKey(r);return new u0(n,r)}static generate(){const e=c0.generateKeyPair();return new u0(e.publicKey,e.privateKey)}}const l0=[{keyType:"ECDSA_SECP256K1_EVM",fromConfig:i0.fromConfig,signatureType:e.SignatureType.ECDSA_SECP256K1_EVM},{keyType:"ECDSA_SECP256R1",fromConfig:u0.fromConfig,signatureType:e.SignatureType.ECDSA_SECP256R1},{keyType:"ML_DSA_87",fromConfig:a0.fromConfig,signatureType:e.SignatureType.ML_DSA_87}],h0="ECDSA_SECP256K1_EVM";["ECDSA_SECP256K1_EVM","ECDSA_SECP256R1","ML_DSA_87"].forEach((e=>{if(!l0.find((t=>t.keyType===e)))throw new Error(`keyType missing from IDENTITIES: ${e}`)}));var d0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},f0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const p0=Object.fromEntries(l0.map((e=>[e.signatureType,PE.getInstance(e.keyType)]))),g0=PE.getInstance("ECDSA_SECP256K1_EVM");let m0=class{erc1271ContractFacade;constructor(e){this.erc1271ContractFacade=e}async assertSignatureIsValid(e){let t;try{t=await this.validate(e)}catch(t){throw new uA(`An error occurred during address recovery from signature: ${t}`,"INVALID_SIGNATURE",e)}if(!t)throw new uA("Signature validation failed","INVALID_SIGNATURE",e)}async validate(t){const r=p0[t.signatureType];if(r)return r.verifySignature(RE(t.getPublisherId()),HX(t),t.signature);if(t.signatureType===e.SignatureType.ECDSA_SECP256K1_LEGACY)return g0.verifySignature(RE(t.getPublisherId()),t0(t),t.signature);if(t.signatureType===e.SignatureType.ERC_1271)return this.erc1271ContractFacade.isValidSignature(nb(t.getPublisherId()),HX(t),t.signature);throw new Error(`Cannot validate message signature, unsupported signatureType: "${t.signatureType}"`)}};m0=d0([q(d.ContainerScoped),f0("design:paramtypes",[e0])],m0);const y0=async(e,t,r,n)=>{await b0(e,t,r,n).catch((t=>{throw t.streamMessage??=e,t}))},b0=async(t,r,n,i)=>{switch(await n.assertSignatureIsValid(t),t.messageType){case e.StreamMessageType.MESSAGE:return w0(t,r,i);case e.StreamMessageType.GROUP_KEY_REQUEST:return v0(t,kE(DH.fromBinary(t.content).recipientId),t.getPublisherId(),r,i);case e.StreamMessageType.GROUP_KEY_RESPONSE:return v0(t,t.getPublisherId(),kE(BH.fromBinary(t.content).recipientId),r,i);default:throw new uA(`Unknown message type: ${t.messageType}!`,"ASSERTION_FAILED",t)}},w0=async(e,t,r)=>{const n=e.getStreamId();if(r.validation.partitions){const r=await t.getStreamMetadata(n),i=IJ(r);if(e.getStreamPartition()<0||e.getStreamPartition()>=i)throw new uA(`Partition ${e.getStreamPartition()} is out of range (0..${i-1})`,"INVALID_PARTITION",e)}if(r.validation.permissions){const r=e.getPublisherId();if(!await t.isStreamPublisher(n,r))throw new uA(`${r} is not a publisher on stream ${n}`,"MISSING_PERMISSION",e)}},v0=async(e,t,r,n,i)=>{if(i.validation.permissions){const i=e.getStreamId();if(!await n.isStreamPublisher(i,t))throw new uA(`${t} is not a publisher on stream ${i}`,"MISSING_PERMISSION",e);if(!await n.isStreamSubscriber(i,r))throw new uA(`${r} is not a subscriber on stream ${i}`,"MISSING_PERMISSION",e)}};async function E0(e,{isPrivate:t=!1}={}){const r=t?"pkcs8":"spki",n=function(e){return String.fromCharCode.apply(null,[...new Uint8Array(e)])}(await Tv().exportKey(r,e)),i=t?"PRIVATE":"PUBLIC";return`-----BEGIN ${i} KEY-----\n${btoa(n)}\n-----END ${i} KEY-----\n`}class A0{privateKey;publicKey;constructor(e,t){this.privateKey=e,this.publicKey=t}getPublicKey(){return pw(this.publicKey)}getPrivateKey(){return pw(this.privateKey)}getEncryptionType(){return PH.RSA}static async create(e){const{privateKey:t,publicKey:r}=await async function(e){const{publicKey:t,privateKey:r}=await Tv().generateKey({name:"RSA-OAEP",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),[n,i]=await Promise.all([E0(r,{isPrivate:!0}),E0(t,{isPrivate:!1})]);return{privateKey:n,publicKey:i}}(e);return new A0(t,r)}}class S0{privateKey;publicKey;constructor(e,t){this.privateKey=e,this.publicKey=t}getPublicKey(){return this.publicKey}getPrivateKey(){return this.privateKey}getEncryptionType(){return PH.ML_KEM}static create(){const e=JQ.keygen();return new S0(Buffer.from(e.secretKey),Buffer.from(e.publicKey))}}const k0=new Set([e.SignatureType.ML_DSA_87]),R0=new Set([PH.ML_KEM]),C0=new Set([e.EncryptionType.AES]);function I0(e,t){const r=C0.has(e),n=t.encryption?.requireQuantumResistantEncryption;return r||!n}function P0(e){return k0.has(e.getSignatureType())}const T0={Resends:Symbol("Resends"),Subscriber:Symbol("Subscriber")};var _0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},N0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},M0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let x0=class{keyPair;pendingRequests=new $W(5e4);networkNodeFacade;streamRegistry;signatureValidator;messageSigner;store;subscriber;identity;logger;ensureStarted;config;requestGroupKey;constructor(e,t,r,n,i,s,o,a,c){var u,l;this.networkNodeFacade=e,this.streamRegistry=t,this.signatureValidator=r,this.messageSigner=n,this.store=i,this.subscriber=s,this.identity=a,this.logger=c.createLogger("SubscriberKeyExchange"),this.config=o,void 0===o.encryption.keys?(this.ensureStarted=nJ((async()=>{this.keyPair=await async function(e,t){return t.encryption.requireQuantumResistantKeyExchange||P0(e)?S0.create():A0.create(t.encryption.rsaKeyLength)}(a,o),e.addMessageListener((e=>this.onMessage(e))),this.logger.debug("Started")})),this.requestGroupKey=(u=(e,t,r)=>this.doRequestGroupKey(e,t,r),l=o.encryption.maxKeyRequestsPerSecond,tJ({limit:l,interval:1e3})(u))):(this.ensureStarted=async()=>{throw new uA("Assertion failed","ASSERTION_FAILED")},this.requestGroupKey=async()=>{throw new uA("Assertion failed","ASSERTION_FAILED")})}async doRequestGroupKey(e,t,r){await this.ensureStarted();const n=xF(),{message:i,request:s}=await this.createRequest(e,r,t,n);await this.networkNodeFacade.broadcast(i),this.pendingRequests.add(n),this.logger.debug("Sent group key request (waiting for response)",{groupKeyId:e,requestId:n,publisherId:t,keyEncryptionType:PH[s.encryptionType]})}async createRequest(t,r,n,i){const s={recipientId:RE(n),requestId:i,publicKey:this.keyPair.getPublicKey(),groupKeyIds:[t],encryptionType:this.keyPair.getEncryptionType()},o=this.subscriber.getERC1271ContractAddress(r);return{message:await this.messageSigner.createSignedMessage({messageId:new CW(AE.getStreamID(r),AE.getStreamPartition(r),Date.now(),0,void 0===o?await this.identity.getUserId():kE(o),VX()),content:DH.toBinary(s),contentType:e.ContentType.BINARY,messageType:e.StreamMessageType.GROUP_KEY_REQUEST,encryptionType:e.EncryptionType.NONE},void 0===o?this.identity.getSignatureType():e.SignatureType.ERC_1271),request:s}}async onMessage(t){if(t.messageType===e.StreamMessageType.GROUP_KEY_RESPONSE)try{const{requestId:e,recipientId:r,groupKeys:n,encryptionType:i}=BH.fromBinary(t.content),s=kE(r);await this.isAssignedToMe(t.getStreamPartID(),s,e)&&(this.logger.debug("Handle group key response",{requestId:e}),this.pendingRequests.delete(e),await y0(t,this.streamRegistry,this.signatureValidator,this.config),await Promise.all(n.map((async e=>{const r=await YQ.decryptWithPrivateKey(e.data,this.keyPair.getPrivateKey(),i);await this.store.set(e.id,t.getPublisherId(),r)}))))}catch(e){this.logger.debug("Failed to handle group key response",{err:e})}}async isAssignedToMe(e,t,r){if(this.pendingRequests.has(r)){const r=await this.identity.getUserId(),n=this.subscriber.getERC1271ContractAddress(e);return t===r||void 0!==n&&t===kE(n)}return!1}};x0=_0([q(d.ContainerScoped),M0(1,U(k((()=>EQ)))),M0(5,U(T0.Subscriber)),M0(6,U(cA)),M0(7,U(kA)),N0("design:paramtypes",[GX,EQ,m0,e.MessageSigner,OZ,Function,Object,RA,uD])],x0);var O0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},D0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},B0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const L0=async(e,t,r)=>{if(void 0!==r.keys)for(const n of Object.entries(r.keys))if(await t.toStreamID(n[0])===e)return new eZ(n[1].id,Buffer.from(mw(n[1].data)))};let F0=class{subscriberKeyExchange;localGroupKeyStore;explicitKeys;config;identity;eventEmitter;destroySignal;constructor(e,t,r,n,i,s,o){this.subscriberKeyExchange=e,this.localGroupKeyStore=t,this.config=n,this.identity=i,this.eventEmitter=s,this.destroySignal=o,void 0!==n.encryption.keys&&(this.explicitKeys=BJ({valueFactory:async e=>L0(e,r,n.encryption)}))}async fetchKey(e,t,r){if(void 0!==this.explicitKeys){const r=await this.explicitKeys.get(AE.getStreamID(e));if(void 0!==r)return r;throw new uA(`No encryption key available for stream part ID: groupKeyId=${t}, streamPartId=${e}`,"UNEXPECTED_INPUT")}let n=await this.localGroupKeyStore.get(t,r);if(void 0!==n)return n;await this.subscriberKeyExchange.requestGroupKey(t,r,e);const i=await eE(this.eventEmitter,"encryptionKeyStoredToLocalStore",this.config.encryption.keyRequestTimeout,(e=>e===t),this.destroySignal.abortSignal);return n=await this.localGroupKeyStore.get(i[0],r),n}async fetchLatestEncryptionKey(e,t){if(e!==await this.identity.getUserId())throw new Error("storeKey: fetching latest encryption keys for other publishers not supported.");const r=await this.localGroupKeyStore.getLatestEncryptionKeyId(e,t);return void 0!==r?this.localGroupKeyStore.get(r,e):void 0}async storeKey(e,t,r){if(t!==await this.identity.getUserId())throw new Error("storeKey: storing latest encryption keys for other publishers not supported.");if(void 0===e){const t=Buffer.from(so(32));e=new eZ(KW("GroupKey"),t)}return await this.localGroupKeyStore.set(e.id,t,e.data),await this.localGroupKeyStore.setLatestEncryptionKeyId(e.id,t,r),e}addKeyToLocalStore(e,t){return this.localGroupKeyStore.set(e.id,t,e.data)}};F0=O0([q(d.ContainerScoped),B0(3,U(cA)),B0(4,U(kA)),D0("design:paramtypes",[x0,OZ,RJ,Object,RA,sD,dJ])],F0);class U0{busy=new uE(!0);inputBuffer=[];outputBuffer;processMessageFn;onError;constructor(e,t,r){this.outputBuffer=e,this.processMessageFn=t,this.onError=r}async addMessage(e){if(this.inputBuffer.push(e),this.busy.isOpen()){for(this.busy.close();this.inputBuffer.length>0;){const e=this.inputBuffer.shift();try{const t=await this.processMessageFn(e);this.outputBuffer.push(t)}catch(e){this.onError.trigger(e)}}this.busy.open()}}}class j0{outputBuffer=new DW;processors=new Map;processMessageFn;onError;constructor(e,t){this.processMessageFn=e,this.onError=t}addMessage(e){const t=`${e.getPublisherId()}-${e.getMsgChainId()}`;let r=this.processors.get(t);void 0===r&&(r=new U0(this.outputBuffer,this.processMessageFn,this.onError),this.processors.set(t,r)),r.addMessage(e)}async flush(){await Promise.all(Array.from(this.processors.values()).map((e=>e.busy.waitUntilOpen())))}stop(e){this.outputBuffer.endWrite(e)}[Symbol.asyncIterator](){return this.outputBuffer}}const q0=new Bv("GapFiller"),z0=async e=>{try{await e()}catch(e){if("AbortError"!==e.code)throw e}};class K0{currentTask=void 0;chain;resend;getStorageNodeAddresses;strategy;initialWaitTime;retryWaitTime;maxRequestsPerGap;constructor(e){this.chain=e.chain,this.resend=e.resend,this.getStorageNodeAddresses=e.getStorageNodeAddresses,this.strategy=e.strategy,this.initialWaitTime=e.initialWaitTime,this.retryWaitTime=e.retryWaitTime,this.maxRequestsPerGap=e.maxRequestsPerGap,e.abortSignal.addEventListener("abort",(()=>{this.currentTask?.abortController.abort()}))}start(){this.chain.on("gapFound",(e=>this.onGapFound(e))),this.chain.on("gapResolved",(()=>this.onGapResolved()))}async onGapFound(e){const t=new AbortController;this.currentTask={gap:e,abortController:t};try{await z0((async()=>{if(await Qv(this.initialWaitTime,t.signal),this.maxRequestsPerGap>0&&await this.fetchFromStorageNode(e,t.signal),"full"===this.strategy)this.chain.resolveMessages(e.to.getMessageRef(),!0);else{if("light"!==this.strategy)throw new Error(`Assertion failed: unexpected gap fill strategy "${this.strategy}"`);this.chain.resolveMessages(void 0,!1)}}))}catch(t){this.onError(t,e)}}onGapResolved(){void 0!==this.currentTask&&(this.currentTask.abortController.abort(),this.currentTask=void 0)}async fetchFromStorageNode(e,t){const r=await this.getStorageNodeAddresses();if(r.length>0)for(let n=0;n<this.maxRequestsPerGap;n++){try{await z0((async()=>{const n=this.resend(e,oA(r),t);for await(const e of n)this.chain.addMessage(e)}))}catch(t){this.onError(t,e)}n!==this.maxRequestsPerGap-1&&await Qv(this.retryWaitTime,t)}}onError(e,t){q0.debug("Unable to fill gap",{error:{message:e?.message,code:e?.code},context:this.chain.getContext(),from:t.from.getMessageRef(),to:t.to.getMessageRef()})}}const G0=new Bv("OrderedMessageChain"),V0=(e,t)=>0===e.compareTo(t);class H0{lastOrderedMsg;currentGap;pendingMsgs;eventEmitter;context;abortSignal;constructor(e,t){this.context=e,this.pendingMsgs=new fE(((e,t)=>e.getMessageRef().compareTo(t.getMessageRef()))),this.eventEmitter=new Sl,this.abortSignal=t,t.addEventListener("abort",(()=>{this.eventEmitter.removeAllListeners()}))}addMessage(e){this.isStaleMessage(e)||(this.pendingMsgs.push(e),this.consumePendingOrderedMessages((e=>this.isNextOrderedMessage(e))))}resolveMessages(e,t){this.consumePendingOrderedMessages((t=>{if(this.isNextOrderedMessage(t))return!0;if(void 0===e||t.getMessageRef().compareTo(e)<=0){const e={from:this.lastOrderedMsg,to:t};return this.eventEmitter.emit("unfillableGap",e),!0}return!1}),t)}async waitUntilIdle(){const e=()=>this.pendingMsgs.isEmpty()||this.abortSignal.aborted;if(!e()){const t=new uE(!1),r=()=>{e()&&t.open()};this.on("orderedMessageAdded",r),this.abortSignal.addEventListener("abort",r),await t.waitUntilOpen(),this.off("orderedMessageAdded",r),this.abortSignal.removeEventListener("abort",r)}}consumePendingOrderedMessages(e,t=!0){for(;!this.pendingMsgs.isEmpty()&&e(this.pendingMsgs.peek());){const e=this.pendingMsgs.pop();this.lastOrderedMsg=e,this.eventEmitter.emit("orderedMessageAdded",e),this.checkGapResolved()}t&&this.checkGapFound()}checkGapFound(){this.pendingMsgs.isEmpty()||void 0!==this.currentGap||(this.currentGap={from:this.lastOrderedMsg,to:this.pendingMsgs.peek()},G0.debug("Gap found",{context:this.context,from:this.currentGap.from.getMessageRef(),to:this.currentGap.to.getMessageRef()}),this.eventEmitter.emit("gapFound",this.currentGap))}checkGapResolved(){if(void 0!==this.currentGap&&V0(this.lastOrderedMsg.getMessageRef(),this.currentGap.to.getMessageRef())){const e=this.currentGap;this.currentGap=void 0,G0.debug("Gap resolved",{context:this.context,from:e.from.getMessageRef(),to:e.to.getMessageRef()}),this.eventEmitter.emit("gapResolved")}}isNextOrderedMessage(e){const t=e.prevMsgRef;return void 0===this.lastOrderedMsg||void 0===t||V0(t,this.lastOrderedMsg.getMessageRef())}isStaleMessage(e){return void 0!==this.lastOrderedMsg&&e.getMessageRef().compareTo(this.lastOrderedMsg.getMessageRef())<=0||this.pendingMsgs.contains(e)}getContext(){return this.context}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}}class $0{chains;outBuffer=new DW;abortController=new AbortController;constructor(e,t,r,n,i){this.chains=BJ({valueFactory:async([s,o])=>{const a=((e,t,r,n,i,s)=>{const o=new H0(e,s);return o.on("unfillableGap",(e=>r(e))),new K0({chain:o,resend:async function*(t,r,i){const s=await n.resend(e.streamPartId,{from:{timestamp:t.from.getMessageRef().timestamp,sequenceNumber:t.from.getMessageRef().sequenceNumber+1},to:t.to.prevMsgRef,publisherId:e.publisherId,msgChainId:e.msgChainId,raw:!0},(async()=>[r]),i);yield*s},getStorageNodeAddresses:()=>t(AE.getStreamID(e.streamPartId)),strategy:i.gapFillStrategy,initialWaitTime:i.gapFillTimeout,retryWaitTime:i.retryResendAfter,maxRequestsPerGap:i.gapFill?i.maxGapRequests:0,abortSignal:s}).start(),o})({streamPartId:e,publisherId:s,msgChainId:o},t,r,n,i,this.abortController.signal);return a.on("orderedMessageAdded",(e=>this.onOrdered(e))),a}})}onOrdered(e){this.outBuffer.isDone()||pE((()=>this.outBuffer.push(e)))}destroy(){this.outBuffer.endWrite(),this.abortController.abort()}async addMessages(e){try{for await(const t of e){if(this.abortController.signal.aborted)return;(await this.chains.get([t.getPublisherId(),t.getMsgChainId()])).addMessage(t)}await Promise.all([...this.chains.values()].map((e=>e.waitUntilIdle()))),this.outBuffer.endWrite()}catch(e){this.outBuffer.endWrite(e)}}[Symbol.asyncIterator](){return this.outBuffer}}const W0=t=>{const r=t.loggerFactory.createLogger("messagePipeline"),n=new uJ,i=new j0((async n=>{if(await y0(n,t.streamRegistry,t.signatureValidator,t.config),n.encryptionType!==e.EncryptionType.NONE&&!I0(n.encryptionType,t.config))throw new uA(`A message in stream ${n.getStreamId()} was rejected because the encryption type violates configured requirements (encryptionType: ${n.encryptionType})!`,"ENCRYPTION_POLICY_VIOLATION",n);if(!function(e,t){const r=k0.has(e),n=t.encryption?.requireQuantumResistantSignatures;return r||!n}(n.signatureType,t.config))throw new uA(`A message in stream ${n.getStreamId()} was rejected because the signature type violates configured requirements (signatureType: ${n.encryptionType})!`,"SIGNATURE_POLICY_VIOLATION",n);let i;if(PW.isAESEncrypted(n))try{i=await(async(t,r,n)=>{if(n.isDestroyed())return t;let i;try{i=await r.fetchKey(t.getStreamPartID(),t.groupKeyId,t.getPublisherId())}catch{if(n.isDestroyed())return t;throw new uA(`Could not get encryption key ${t.groupKeyId}`,"DECRYPT_ERROR",t)}if(n.isDestroyed())return t;const[s,o]=YQ.decryptStreamMessage(t,i);return void 0!==o&&await r.addKeyToLocalStore(o,t.getPublisherId()),new PW({...t,content:s,encryptionType:e.EncryptionType.NONE})})(n,t.groupKeyManager,t.destroySignal)}catch(e){throw r.debug("Failed to decrypt",{messageId:n.messageId,err:e}),t.streamRegistry.invalidatePermissionCaches(n.getStreamId()),e}else i=n;return i.getParsedContent(),i}),n.onError),s=new WeakSet;if(n.onError.listen(((e,t)=>{throw t&&s.add(t.messageId),e&&"messageId"in e&&e.messageId&&s.add(e.messageId),e})),t.config.orderMessages){const e=new $0(t.streamPartId,t.getStorageNodes,(()=>{}),t.resends,t.config);n.pipe((async function*(t){setImmediate((()=>{e.addMessages(t)})),yield*e})),n.onBeforeFinally.listen((()=>{e.destroy()}))}return n.pipe((async function*(e){setImmediate((async()=>{let t;try{for await(const t of e)i.addMessage(t)}catch(e){t=e}await i.flush(),i.stop(t)})),yield*i})).filter((e=>!s.has(e.messageId))),n};var J0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},Q0=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},Z0=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let Y0=class{resends;streamStorageRegistry;streamRegistry;signatureValidator;groupKeyManager;config;destroySignal;loggerFactory;constructor(e,t,r,n,i,s,o,a){this.resends=e,this.streamStorageRegistry=t,this.streamRegistry=r,this.signatureValidator=n,this.groupKeyManager=i,this.config=s,this.destroySignal=o,this.loggerFactory=a}createMessagePipeline(e){return W0({...e,getStorageNodes:e.getStorageNodes??(e=>this.streamStorageRegistry.getStorageNodes(e)),resends:this.resends,streamRegistry:this.streamRegistry,signatureValidator:this.signatureValidator,groupKeyManager:this.groupKeyManager,config:e.config??this.config,destroySignal:this.destroySignal,loggerFactory:this.loggerFactory})}};Y0=J0([q(d.ContainerScoped),Z0(0,U(T0.Resends)),Z0(2,U(k((()=>EQ)))),Z0(4,U(k((()=>F0)))),Z0(5,U(cA)),Q0("design:paramtypes",[Function,OQ,EQ,m0,F0,Object,dJ,uD])],Y0);var X0=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},e1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},t1=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const r1=(e,t,r,n={})=>{const i={...n,format:"raw"},[s,o]=AE.getStreamIDAndPartition(r),a=(e=>{const t=Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)));return new URLSearchParams(t).toString()})(i);return`${e}/streams/${encodeURIComponent(s)}/data/partitions/${o}/${t}?${a}`},n1=e=>({...e,publisherId:"publisherId"in e&&void 0!==e.publisherId?kE(e.publisherId):void 0});let i1=class{storageNodeRegistry;messagePipelineFactory;config;logger;constructor(e,t,r,n){this.storageNodeRegistry=e,this.messagePipelineFactory=t,this.config=r,this.logger=n.createLogger("Resends")}async resend(e,t,r,n){const i=t.raw??!1;if(function(e){return e&&"object"==typeof e&&"last"in e&&null!=e.last}(t)){if(t.last<=0){const e=new uJ;return e.endWrite(),e}return this.fetchStream("last",e,{count:t.last},i,r,n)}if(function(e){return e&&"object"==typeof e&&"from"in e&&"to"in e&&e.to&&null!=e.from}(t))return this.fetchStream("range",e,{fromTimestamp:new Date(t.from.timestamp).getTime(),fromSequenceNumber:t.from.sequenceNumber,toTimestamp:new Date(t.to.timestamp).getTime(),toSequenceNumber:t.to.sequenceNumber,publisherId:t.publisherId,msgChainId:t.msgChainId},i,r,n);if(function(e){return e&&"object"==typeof e&&"from"in e&&!("to"in e)&&null!=e.from}(t))return this.fetchStream("from",e,{fromTimestamp:new Date(t.from.timestamp).getTime(),fromSequenceNumber:t.from.sequenceNumber,publisherId:t.publisherId},i,r,n);throw new uA(`can not resend without valid resend options: ${JSON.stringify({streamPartId:e,options:t})}`,"INVALID_ARGUMENT")}async fetchStream(e,t,r,n,i,s){const o=Wv(5);this.logger.debug("Fetch resend data",{loggerIdx:o,resendType:e,streamPartId:t,query:r});const a=AE.getStreamID(t),c=await i(a);if(!c.length)throw new uA(`no storage assigned: ${a}`,"NO_STORAGE_NODES");const u=c[XE(0,c.length-1)],l=(await this.storageNodeRegistry.getStorageNodeMetadata(u)).urls,h=r1(oA(l),e,t,r),d=n?new uJ:this.messagePipelineFactory.createMessagePipeline({streamPartId:t,getStorageNodes:async()=>ju(c,u),config:1===c.length?{...this.config,orderMessages:!1}:this.config}),f=async function*(e,t){try{for await(const t of e)yield t}catch(e){throw await t(e)}}(async function*(e,t){GW.debug("Send HTTP request",{url:e});const r=new AbortController,n=rE(r.signal,t);try{const t=await fetch(e,{signal:n});if(GW.debug("Received HTTP response",{url:e,status:t.status}),!t.ok)throw new ZW(t);if(!t.body)throw new Error("No Response Body");let i;try{const e=UW(t.body);i=e.pipe(new gE),e.on("error",(e=>i.destroy(e))),i.once("close",(()=>{r.abort()})),yield*i}catch(e){throw r.abort(),e}finally{i?.destroy()}}finally{n.destroy()}}(h,s),(async e=>{let t;if(e instanceof ZW){const r=await e.response.text();let n;try{n=`: ${JSON.parse(r).error}`}catch{n=""}t=`Storage node fetch failed${n}, httpStatus=${e.response.status}, url=${e.response.url}`}else t=e?.message??"Unknown error";return new uA(t,"STORAGE_NODE_ERROR")}));return setImmediate((async()=>{let e=0;const t=MW(f,(e=>_W(e)));await async function(e,t){if(!e)throw new Error("no source");try{for await(const r of e)if(!await t.push(r))break}catch(e){t.endWrite(e)}finally{t.endWrite()}}(NW(t,(()=>e++)),d),this.logger.debug("Finished resend",{loggerIdx:o,messageCount:e})})),d}};function s1(e){return e.filter(Boolean).join("\n")}function o1(e){return e.flatMap((e=>function(e){return e instanceof a1?[e.ownStack,...[...e.errors].map((({stack:e})=>e))]:[e.stack]}(e))).filter(Boolean).join("\n")}i1=X0([j(),t1(0,U(k((()=>ID)))),t1(1,U(k((()=>Y0)))),t1(2,U(cA)),e1("design:paramtypes",[ID,Y0,Object,uD])],i1);class a1 extends Error{errors;ownMessage;ownStack;constructor(e=[],t=""){const r=s1([t,...e.map((e=>e.message))]);super(r),e.forEach((e=>{Object.assign(this,e)})),this.message=r,this.ownMessage=t,this.errors=new Set(e),this.ownStack=this.stack,this.stack=o1([this,...e])}static fromAllSettled(e=[],t=""){const r=e.map((({reason:e})=>e)).filter(Boolean);if(r.length)return new this(r,t)}static throwAllSettled(e=[],t=""){const r=this.fromAllSettled(e,t);if(r)throw r}static from(e,t,r){return t?e?e instanceof a1?e.extend(t,r,this):new this([e]).extend(t,r):(t&&r&&(t.message=s1([t.message,r])),t):(e&&r&&(e.message=s1([e.message,r])),e)}extend(e,t="",r=this.constructor){if(e===this||this.errors.has(e))return this;return new r([e,...this.errors],s1([t,this.ownMessage]))}}const c1=()=>{};function u1(e=[],t,{id:r="",onError:n,onDone:i,onChange:s}={}){let o;const a=e.slice().reverse().map((e=>async()=>{const t=await e();return"function"==typeof t?t:c1})),c=[],u=[],l=gD(1);let h=!1,d=!1;function f(e){try{if("function"!=typeof n)throw e;n(e)}catch(e){o=a1.from(o,e,`ScaffoldError:${r}`)}}let p=!1,g=!1;const m=gD(1);async function y(){p=await(async()=>{if(o)return!1;try{return await t()}catch(e){f(e)}return!1})();const e=g!==p;if(g=p,e&&"function"==typeof s){try{await s(p)}catch(e){f(e)}return y()}if(p){if(a.length){let e;h=!1,d=!0;const t=a.pop();c.push(t);try{e=await t()}catch(e){f(e)}return u.push(e??(()=>{})),void await y()}}else{if(u.length){h=!1,d=!0;const e=u.pop();try{await e()}catch(e){f(e)}return a.push(c.pop()),void await y()}if(o){const e=o;throw o=void 0,h=!0,e}}return h=!0,Promise.resolve()}function b(){return!(d&&h&&!l.activeCount&&!l.pendingCount)}const w=async()=>{await m((()=>y()))};let v;return Object.assign((async()=>{let e;try{v=l((()=>w())),await v}catch(t){throw e=t,t}finally{if(!b()&&(d=!1,"function"==typeof i)){const t=e;e=void 0,await i(p,t)}}}),{next:w,isActive:b,getCurrentStep:()=>v,get activeCount(){return l.activeCount},get pendingCount(){return l.pendingCount},setError(e){o=a1.from(o,e)},getError:()=>o,clearError(){const e=o;return o=void 0,e}})}class l1{streamPartId;onRetired=sJ.once();isRetired=!1;isStopped=!1;subscriptions=new Set;pendingRemoval=new WeakSet;pipeline;node;constructor(e,t,r){this.streamPartId=e,this.distributeMessage=this.distributeMessage.bind(this),this.node=r,this.onError=this.onError.bind(this),this.pipeline=t.createMessagePipeline({streamPartId:e}),this.pipeline.onError.listen(this.onError),this.pipeline.pipe(this.distributeMessage).onBeforeFinally.listen((async()=>{this.isStopped||await this.stop()})),this.pipeline.flow()}async retire(){this.isRetired||(this.isRetired=!0,await this.onRetired.trigger())}async onError(e){await Promise.allSettled([...this.subscriptions].map((async t=>{await t.handleError(e)})))}async*distributeMessage(e){for await(const t of e)await Promise.all([...this.subscriptions].map((async e=>{await e.push(t)}))),yield t}onMessageInput=async t=>{if(!t||this.isStopped||this.isRetired)return;if(t.getStreamPartID()!==this.streamPartId)return;if(t.messageType!==e.StreamMessageType.MESSAGE)return;const r=[];let n=!1;for(const e of this.subscriptions.values())e.isRaw?r.push(e.push(t)):n=!0;n&&r.push(this.pipeline.push(t)),await Promise.all(r)};async subscribe(){if(this.node.addMessageListener(this.onMessageInput),!await this.node.isProxiedStreamPart(this.streamPartId)){const e=(e=>e.values().next().value)(this.subscriptions).deliveryOptions;await this.node.join(this.streamPartId,void 0,e)}}async unsubscribe(){this.pipeline.end(),this.pipeline.return(),this.pipeline.onError.end(new Error("done")),this.node.removeMessageListener(this.onMessageInput),await this.node.leave(this.streamPartId)}updateNodeSubscriptions=(()=>u1([async()=>(await this.subscribe(),async()=>{await this.unsubscribe(),await this.stop()})],(()=>this.shouldBeSubscribed())))();async updateSubscriptions(){await this.updateNodeSubscriptions(),this.shouldBeSubscribed()||this.isStopped||await this.stop()}shouldBeSubscribed(){return!this.isRetired&&!this.isStopped&&!!this.count()}async stop(){this.isStopped=!0,this.pipeline.end(),await this.retire(),await this.pipeline.return()}has(e){return this.subscriptions.has(e)}async add(e){if(!e||this.subscriptions.has(e)||this.pendingRemoval.has(e))return;const t=this.getERC1271ContractAddress();if(this.subscriptions.size>0&&t!==e.erc1271ContractAddress)throw new Error("Subscription ERC-1271 mismatch");this.subscriptions.add(e),e.onBeforeFinally.listen((()=>this.remove(e))),await this.updateSubscriptions()}async remove(e){if(e&&!this.pendingRemoval.has(e)&&this.subscriptions.has(e)){this.pendingRemoval.add(e),this.subscriptions.delete(e);try{e.isDone()||await e.unsubscribe()}finally{await this.updateSubscriptions()}}}getERC1271ContractAddress(){for(const e of this.subscriptions)if(void 0!==e.erc1271ContractAddress)return e.erc1271ContractAddress}count(){return this.subscriptions.size}}var h1=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},d1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},f1=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let p1=class{subSessions=new Map;node;messagePipelineFactory;logger;constructor(e,t,r){this.node=e,this.messagePipelineFactory=t,this.logger=r.createLogger("Subscriber")}getOrCreateSubscriptionSession(e){if(this.subSessions.has(e))return this.getSubscriptionSession(e);const t=new l1(e,this.messagePipelineFactory,this.node);return this.subSessions.set(e,t),t.onRetired.listen((()=>{this.subSessions.delete(e)})),this.logger.debug("Created new SubscriptionSession",{streamPartId:e}),t}async add(e){const t=this.getOrCreateSubscriptionSession(e.streamPartId);try{await t.add(e)}catch(t){throw this.logger.debug("Failed to add Subscription to SubscriptionSession",t),await this.remove(e),t}}async remove(e){const t=this.subSessions.get(e.streamPartId);t&&await t.remove(e)}getSubscriptions(){return[...this.subSessions.values()].reduce(((e,t)=>(e.push(...t.subscriptions),e)),[])}getERC1271ContractAddress(e){return this.subSessions.get(e)?.getERC1271ContractAddress()}getSubscriptionSession(e){return this.subSessions.get(e)}countSubscriptionSessions(){return this.subSessions.size}};p1=h1([j(),f1(1,U(k((()=>Y0)))),d1("design:paramtypes",[GX,Y0,uD])],p1),F.register(T0.Resends,{useClass:i1},{lifecycle:d.ContainerScoped}),F.register(T0.Subscriber,{useClass:p1},{lifecycle:d.ContainerScoped});var g1,m1,y1={},b1={};var w1,v1=function(){if(m1)return y1;m1=1,Object.defineProperty(y1,"__esModule",{value:!0}),y1.isConstructorToken=y1.isTransformDescriptor=y1.isTokenDescriptor=y1.isNormalToken=void 0;const e=function(){if(g1)return b1;g1=1,Object.defineProperty(b1,"__esModule",{value:!0}),b1.delay=b1.DelayedConstructor=void 0;class e{constructor(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}createProxy(e){let t,r=!1;return new Proxy({},this.createHandler((()=>(r||(t=e(this.wrap()),r=!0),t))))}createHandler(e){const t={};return this.reflectMethods.forEach((r=>{t[r]=(...t)=>(t[0]=e(),(0,Reflect[r])(...t))})),t}}return b1.DelayedConstructor=e,b1.delay=function(t){if(void 0===t)throw new Error("Attempt to `delay` undefined. Constructor must be wrapped in a callback");return new e(t)},b1}();return y1.isNormalToken=function(e){return"string"==typeof e||"symbol"==typeof e},y1.isTokenDescriptor=function(e){return"object"==typeof e&&"token"in e&&"multiple"in e},y1.isTransformDescriptor=function(e){return"object"==typeof e&&"token"in e&&"transform"in e},y1.isConstructorToken=function(t){return"function"==typeof t||t instanceof e.DelayedConstructor},y1}(),E1={};var A1,S1,k1=(w1||(w1=1,Object.defineProperty(E1,"__esModule",{value:!0}),E1.formatErrorCtor=void 0,E1.formatErrorCtor=function(e,t,r){const[,n=null]=e.toString().match(/constructor\(([\w, ]+)\)/)||[];return function(e,t,r=" "){return[e,...t.message.split("\n").map((e=>r+e))].join("\n")}(`Cannot inject the dependency ${function(e,t){return null===e?`at position #${t}`:`"${e.split(",")[t].trim()}" at position #${t}`}(n,t)} of "${e.name}" constructor. Reason:`,r)}),E1);F.constructor.prototype.resolveParams=function(e,t){return(r,n)=>{try{return v1.isTokenDescriptor(r)?v1.isTransformDescriptor(r)?r.multiple?this.resolve(r.transform).transform(this.resolveAll(r.token),...r.transformArgs):this.resolve(r.transform).transform(this.resolve(r.token,e),...r.transformArgs):r.multiple?this.resolveAll(r.token):this.resolve(r.token,e):v1.isTransformDescriptor(r)?this.resolve(r.transform,e).transform(this.resolve(r.token,e),...r.transformArgs):this.resolve(r,e)}catch(e){throw e.message=k1.formatErrorCtor(t,n,e),e}}};var R1,C1,I1=function(){if(S1)return A1;S1=1;var e=Td(),t=Nd()((function(t,r,n){e(t,r,n)}));return A1=t}(),P1=n(I1);var T1=function(){if(C1)return R1;C1=1;var e=De(),t=qu(),r=Be();return R1=function(n){return"string"==typeof n||!t(n)&&r(n)&&"[object String]"==e(n)}}(),_1=n(T1);class N1{currentGroupKey;queuedGroupKey;streamId;identity;groupKeyManager;static async createInstance(e,t,r,n){const i=new N1(e,t,r);return i.currentGroupKey=n??await i.groupKeyManager.fetchLatestEncryptionKey(await t.getUserId(),e)??void 0,i}constructor(e,t,r){this.streamId=e,this.identity=t,this.groupKeyManager=r}async useGroupKey(){this.currentGroupKey||(this.currentGroupKey=this.queuedGroupKey??await this.rekey(),this.queuedGroupKey=void 0);const e={current:this.currentGroupKey,next:this.queuedGroupKey};return this.queuedGroupKey&&(this.currentGroupKey=this.queuedGroupKey,this.queuedGroupKey=void 0),e}async rotate(e){const t=await this.identity.getUserId();return e=await this.groupKeyManager.storeKey(e,t,this.streamId),this.queuedGroupKey=e,e}async rekey(e){const t=await this.identity.getUserId();return e=await this.groupKeyManager.storeKey(e,t,this.streamId),this.currentGroupKey=e,this.queuedGroupKey=void 0,e}}class M1{streamId;identity;defaultPartition;defaultMessageChainIds;prevMsgRefs=new Map;streamRegistry;groupKeyQueue;signatureValidator;messageSigner;config;firstMessage=!0;constructor(e){this.streamId=e.streamId,this.identity=e.identity,this.streamRegistry=e.streamRegistry,this.groupKeyQueue=e.groupKeyQueue,this.signatureValidator=e.signatureValidator,this.messageSigner=e.messageSigner,this.config=e.config,this.defaultMessageChainIds=BJ({valueFactory:async()=>VX()})}async createMessage(t,r,n){const i=await this.getPublisherId(r);if(this.config.validation.permissions){if(!await this.streamRegistry.isStreamPublisher(this.streamId,i))throw this.streamRegistry.invalidatePermissionCaches(this.streamId),new uA(`You don't have permission to publish to this stream. Using address: ${i}`,"MISSING_PERMISSION")}let s;if(this.config.validation.partitions){const e=await this.streamRegistry.getStreamMetadata(this.streamId),t=IJ(e);if(void 0!==n){if(n<0||n>=t)throw new Error(`Partition ${n} is out of range (0..${t-1})`);if(void 0!==r.partitionKey)throw new Error('Invalid combination of "partition" and "partitionKey"');s=n}else s=void 0!==r.partitionKey?function(e,t){if(!(Number.isSafeInteger(e)&&e>0))throw new Error(`lengthOfArray is not a safe positive integer! ${e}`);if(1===e)return 0;if("number"==typeof t)return Math.abs(t)%e;const r=_v(t).readInt32LE(0);return Math.abs(r)%e}(t,r.partitionKey):this.getDefaultPartition(t)}else{if(void 0===n)throw new Error("Explicit partition must be set when partition validation is disabled");s=n}const o=r.msgChainId??await this.defaultMessageChainIds.get(s),a=QW([s,o]),c=this.prevMsgRefs.get(a),u=((e,t)=>{if(void 0!==t&&e<t.timestamp)throw new Error("prevMessageRef must come before current");const r=t?.timestamp===e?t.sequenceNumber+1:0;return new RW(e,r)})(r.timestamp,c);this.prevMsgRefs.set(a,u);const l=new CW(this.streamId,s,u.timestamp,u.sequenceNumber,i,o),h=this.config.validation.permissions&&await this.streamRegistry.hasPublicSubscribePermission(this.streamId)?e.EncryptionType.NONE:e.EncryptionType.AES;if(!I0(h,this.config))throw new uA(`Publishing to stream ${this.streamId} was prevented because configuration requires encryption!`,"ENCRYPTION_POLICY_VIOLATION");let d,f,p,g;if(t instanceof Uint8Array?(g=e.ContentType.BINARY,p=t):(g=e.ContentType.JSON,p=pw(JSON.stringify(t))),h===e.EncryptionType.AES){const e=await this.groupKeyQueue.useGroupKey();p=YQ.encryptWithAES(p,e.current.data),d=e.current.id,void 0!==e.next&&(f=e.current.encryptNextGroupKey(e.next))}const m=await this.messageSigner.createSignedMessage({messageId:l,messageType:e.StreamMessageType.MESSAGE,content:p,prevMsgRef:c,encryptionType:h,groupKeyId:d,newGroupKey:f,contentType:g},void 0!==r.erc1271Contract?e.SignatureType.ERC_1271:this.identity.getSignatureType());return this.firstMessage&&(this.firstMessage=!1,void 0!==r.erc1271Contract&&await this.signatureValidator.assertSignatureIsValid(m)),m}async getPublisherId(e){return void 0!==e.erc1271Contract?kE(nb(e.erc1271Contract)):this.identity.getUserId()}getDefaultPartition(e){return(void 0===this.defaultPartition||this.defaultPartition>=e)&&(this.defaultPartition=XE(e-1)),this.defaultPartition}}var x1=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},O1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},D1=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let B1=class{messageFactories;groupKeyQueues;concurrencyLimit=gD(1);node;streamRegistry;streamIdBuilder;identity;signatureValidator;messageSigner;config;constructor(e,t,r,n,i,s,o,a){this.node=e,this.streamRegistry=t,this.streamIdBuilder=n,this.identity=i,this.signatureValidator=s,this.messageSigner=o,this.config=a,this.messageFactories=BJ({valueFactory:async e=>this.createMessageFactory(e)}),this.groupKeyQueues=BJ({valueFactory:async e=>{const t=await L0(e,this.streamIdBuilder,this.config.encryption);return await N1.createInstance(e,this.identity,r,t)}})}async publish(e,t,r,n){const i=(e=>void 0===e?.timestamp?Date.now():e.timestamp instanceof Date?e.timestamp.getTime():_1(e.timestamp)?new Date(e.timestamp).getTime():e.timestamp)(r);return this.concurrencyLimit((async()=>{const[s,o]=await this.streamIdBuilder.toStreamPartElements(e);try{const e=await this.messageFactories.get(s),a=await e.createMessage(t,{...r,timestamp:i},o);return await this.node.broadcast(a,n),a}catch(e){const t=e instanceof uA?e.code:"UNKNOWN_ERROR";throw new uA(`Failed to publish to stream ${s}. Cause: ${e.message}`,t)}}))}getGroupKeyQueue(e){return this.groupKeyQueues.get(e)}async createMessageFactory(e){return new M1({streamId:e,identity:this.identity,streamRegistry:this.streamRegistry,groupKeyQueue:await this.groupKeyQueues.get(e),signatureValidator:this.signatureValidator,messageSigner:this.messageSigner,config:this.config})}};var L1,F1;B1=x1([q(d.ContainerScoped),D1(4,U(kA)),D1(7,U(cA)),O1("design:paramtypes",[GX,EQ,F0,RJ,RA,m0,e.MessageSigner,Object])],B1);var U1,j1=n(function(){if(F1)return L1;F1=1;var e=MY();return L1=function(t){return e(t,5)}}()),q1={exports:{}};var z1=function(){if(U1)return q1.exports;U1=1,q1.exports=u,q1.exports.default=u;const e={properties:{environment:{type:"string",enum:["polygon","polygonAmoy","peaq","iotex","dev2"],description:"applies all environment-specific defaults for the given environment"},id:{type:"string"},logLevel:{type:"string",enum:["silent","fatal","error","warn","info","debug","trace"],default:"info"},auth:{type:"object",additionalProperties:!1,properties:{publicKey:{type:"string",format:"hex-string"},privateKey:{type:"string",format:"hex-string"},keyType:{type:"string",default:"ECDSA_SECP256K1_EVM"},ethereum:{type:"object"},identity:{type:"object"}}},orderMessages:{type:"boolean",default:!0},gapFill:{type:"boolean",default:!0},maxGapRequests:{type:"number",default:5},retryResendAfter:{type:"number",default:5e3},gapFillTimeout:{type:"number",default:5e3},gapFillStrategy:{type:"string",enum:["light","full"],default:"light"},network:{type:"object",additionalProperties:!1,required:[],properties:{controlLayer:{type:"object",additionalProperties:!1,properties:{entryPoints:{type:"array",items:{$ref:"#/definitions/peerDescriptor"}},entryPointDiscovery:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"},maxEntryPoints:{type:"number"},maxQueryResults:{type:"number"},maxHeartbeatAgeHours:{type:"number"}},default:{enabled:!0,maxEntryPoints:5,maxQueryResults:50,maxHeartbeatAgeHours:24}},websocketPortRange:{anyOf:[{type:"null"},{$ref:"#/definitions/portRange"}],default:{min:32200,max:32250}},websocketHost:{type:"string",format:"hostname"},peerDescriptor:{$ref:"#/definitions/peerDescriptor"},maxConnections:{type:"number",default:80},tlsCertificate:{description:"Files to use for TLS",type:"object",required:["certFileName","privateKeyFileName"],additionalProperties:!1,properties:{certFileName:{type:"string",description:"Path of certificate file"},privateKeyFileName:{type:"string",description:"Path of private key file"}}},iceServers:{type:"array",items:{type:"object",required:["url","port"],additionalProperties:!1,properties:{url:{type:"string"},port:{type:"number"},username:{type:"string"},password:{type:"string"},tcp:{type:"boolean"}}},default:[{url:"stun:stun.streamr.network",port:5349},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q=="},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q==",tcp:!0}]},webrtcAllowPrivateAddresses:{type:"boolean",default:!1},webrtcDatachannelBufferThresholdLow:{type:"number",default:32768},webrtcDatachannelBufferThresholdHigh:{type:"number",default:131072},maxMessageSize:{type:"number",default:1048576},externalIp:{type:"string",format:"ipv4"},webrtcPortRange:{$ref:"#/definitions/portRange",default:{min:5e4,max:64e3}},networkConnectivityTimeout:{type:"number",default:1e4},websocketServerEnableTls:{type:"boolean",default:!0},autoCertifierUrl:{type:"string",default:"https://ns1.streamr-nodes.xyz:59833"},autoCertifierConfigFile:{type:"string",default:"~/.streamr/certificate.json"},geoIpDatabaseFolder:{type:"string"}},default:{}},node:{type:"object",additionalProperties:!1,properties:{streamPartitionNeighborTargetCount:{type:"number",default:4},streamPartitionMinPropagationTargets:{type:"number",default:2},streamPartitionMaxPropagationBufferSize:{type:"number",default:150},contentDeliveryBufferWhileConnecting:{type:"boolean",default:!0},acceptProxyConnections:{type:"boolean",default:!1}},default:{}}},default:{}},contracts:{type:"object",additionalProperties:!1,properties:{ethereumNetwork:{type:"object",additionalProperties:!1,properties:{chainId:{type:"number"},overrides:{type:"object"},highGasPriceStrategy:{type:"boolean"}},default:{}},streamRegistryChainAddress:{type:"string",format:"ethereum-address"},streamStorageRegistryChainAddress:{type:"string",format:"ethereum-address"},storageNodeRegistryChainAddress:{type:"string",format:"ethereum-address"},sponsorshipFactoryChainAddress:{type:"string",format:"ethereum-address"},rpcs:{type:"array",items:{type:"object",$ref:"#/definitions/rpcProviderConfig"},minItems:1},rpcQuorum:{type:"number",default:2},theGraphUrl:{type:"string",format:"uri"},maxConcurrentCalls:{type:"number",default:10},pollInterval:{type:"number",default:4e3}},default:{}},encryption:{type:"object",additionalProperties:!1,properties:{keyRequestTimeout:{type:"number",default:3e4},maxKeyRequestsPerSecond:{type:"number",default:20},rsaKeyLength:{type:"number",default:4096},requireQuantumResistantKeyExchange:{type:"boolean",default:!1},requireQuantumResistantSignatures:{type:"boolean",default:!1},requireQuantumResistantEncryption:{type:"boolean",default:!1},keys:{type:"object",propertyNames:{$ref:"#/definitions/streamIdOrPath"},additionalProperties:{$ref:"#/definitions/encryptionKey"}}},default:{}},validation:{type:"object",additionalProperties:!1,properties:{permissions:{type:"boolean",default:!0},partitions:{type:"boolean",default:!0}},default:{}},metrics:{anyOf:[{type:"boolean"},{type:"object",additionalProperties:!1,properties:{periods:{type:"array",items:{type:"object",required:["streamId","duration"],properties:{id:{type:"string"},duration:{type:"number"}}}},maxPublishDelay:{type:"number"}}}]},cache:{type:"object",additionalProperties:!1,properties:{maxSize:{type:"number",default:1e4},maxAge:{type:"number",default:864e5}},default:{}},_timeouts:{type:"object",additionalProperties:!1,properties:{theGraph:{type:"object",additionalProperties:!1,properties:{indexTimeout:{type:"number",default:6e4},indexPollInterval:{type:"number",default:1e3},fetchTimeout:{type:"number",default:3e4}},default:{}},storageNode:{type:"object",additionalProperties:!1,properties:{timeout:{type:"number",default:3e4},retryInterval:{type:"number",default:1e3}},default:{}},ensStreamCreation:{type:"object",additionalProperties:!1,properties:{timeout:{type:"number",default:18e4},retryInterval:{type:"number",default:1e3}},default:{}},jsonRpcTimeout:{type:"number",default:3e4}},default:{}}}},t=Object.prototype.hasOwnProperty,r=/^(0x)?[a-fA-F0-9]+$/,n=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,i=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,s=/^0x[a-fA-F0-9]{40}$/,o=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,a={enum:["browser","nodejs"]};function c(e,{instancePath:t="",parentData:r,parentDataProperty:n,rootData:i=e}={}){if(!e||"object"!=typeof e||Array.isArray(e))return c.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;for(const r in e)if("nodeId"!==r&&"id"!==r&&"type"!==r&&"websocket"!==r)return c.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"}],!1;if(void 0!==e.nodeId){const r=0;if("string"!=typeof e.nodeId)return c.errors=[{instancePath:t+"/nodeId",schemaPath:"#/properties/nodeId/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var s=0===r}else s=!0;if(s){if(void 0!==e.id){const r=0;if("string"!=typeof e.id)return c.errors=[{instancePath:t+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;s=0===r}else s=!0;if(s){if(void 0!==e.type){let r=e.type;const n=0;if("string"!=typeof r)return c.errors=[{instancePath:t+"/type",schemaPath:"#/definitions/nodeType/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("browser"!==r&&"nodejs"!==r)return c.errors=[{instancePath:t+"/type",schemaPath:"#/definitions/nodeType/enum",keyword:"enum",params:{allowedValues:a.enum},message:"must be equal to one of the allowed values"}],!1;s=0===n}else s=!0;if(s)if(void 0!==e.websocket){let r=e.websocket;const n=0;if(!r||"object"!=typeof r||Array.isArray(r))return c.errors=[{instancePath:t+"/websocket",schemaPath:"#/definitions/connectivityMethod/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let e;if(void 0===r.host&&(e="host")||void 0===r.port&&(e="port")||void 0===r.tls&&(e="tls"))return c.errors=[{instancePath:t+"/websocket",schemaPath:"#/definitions/connectivityMethod/required",keyword:"required",params:{missingProperty:e},message:"must have required property '"+e+"'"}],!1;for(const e in r)if("host"!==e&&"port"!==e&&"tls"!==e)return c.errors=[{instancePath:t+"/websocket",schemaPath:"#/definitions/connectivityMethod/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(void 0!==r.host){const e=0;if("string"!=typeof r.host)return c.errors=[{instancePath:t+"/websocket/host",schemaPath:"#/definitions/connectivityMethod/properties/host/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var o=0===e}else o=!0;if(o){if(void 0!==r.port){let e=r.port;const n=0;if("number"!=typeof e||!isFinite(e))return c.errors=[{instancePath:t+"/websocket/port",schemaPath:"#/definitions/connectivityMethod/properties/port/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;o=0===n}else o=!0;if(o)if(void 0!==r.tls){const e=0;if("boolean"!=typeof r.tls)return c.errors=[{instancePath:t+"/websocket/tls",schemaPath:"#/definitions/connectivityMethod/properties/tls/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;o=0===e}else o=!0}}s=0===n}else s=!0}}return c.errors=null,!0}function u(a,{instancePath:l="",parentData:h,parentDataProperty:d,rootData:f=a}={}){let p=null,g=0;if(0===g){if(!a||"object"!=typeof a||Array.isArray(a))return u.errors=[{instancePath:l,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===a.logLevel&&(a.logLevel="info"),void 0===a.orderMessages&&(a.orderMessages=!0),void 0===a.gapFill&&(a.gapFill=!0),void 0===a.maxGapRequests&&(a.maxGapRequests=5),void 0===a.retryResendAfter&&(a.retryResendAfter=5e3),void 0===a.gapFillTimeout&&(a.gapFillTimeout=5e3),void 0===a.gapFillStrategy&&(a.gapFillStrategy="light"),void 0===a.network&&(a.network={}),void 0===a.contracts&&(a.contracts={}),void 0===a.encryption&&(a.encryption={}),void 0===a.validation&&(a.validation={}),void 0===a.cache&&(a.cache={}),void 0===a._timeouts&&(a._timeouts={});const h=g;for(const r in a)if(!t.call(e.properties,r))return u.errors=[{instancePath:l,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"}],!1;if(h===g){if(void 0!==a.environment){let t=a.environment;const r=g;if("string"!=typeof t)return u.errors=[{instancePath:l+"/environment",schemaPath:"#/properties/environment/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("polygon"!==t&&"polygonAmoy"!==t&&"peaq"!==t&&"iotex"!==t&&"dev2"!==t)return u.errors=[{instancePath:l+"/environment",schemaPath:"#/properties/environment/enum",keyword:"enum",params:{allowedValues:e.properties.environment.enum},message:"must be equal to one of the allowed values"}],!1;var m=r===g}else m=!0;if(m){if(void 0!==a.id){const e=g;if("string"!=typeof a.id)return u.errors=[{instancePath:l+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;m=e===g}else m=!0;if(m){let h=a.logLevel;const d=g;if("string"!=typeof h)return u.errors=[{instancePath:l+"/logLevel",schemaPath:"#/properties/logLevel/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("silent"!==h&&"fatal"!==h&&"error"!==h&&"warn"!==h&&"info"!==h&&"debug"!==h&&"trace"!==h)return u.errors=[{instancePath:l+"/logLevel",schemaPath:"#/properties/logLevel/enum",keyword:"enum",params:{allowedValues:e.properties.logLevel.enum},message:"must be equal to one of the allowed values"}],!1;if(m=d===g){if(void 0!==a.auth){let e=a.auth;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/auth",schemaPath:"#/properties/auth/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.keyType&&(e.keyType="ECDSA_SECP256K1_EVM");const t=g;for(const t in e)if("publicKey"!==t&&"privateKey"!==t&&"keyType"!==t&&"ethereum"!==t&&"identity"!==t)return u.errors=[{instancePath:l+"/auth",schemaPath:"#/properties/auth/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.publicKey){let t=e.publicKey;const n=g;if(g===n&&g===n){if("string"!=typeof t)return u.errors=[{instancePath:l+"/auth/publicKey",schemaPath:"#/properties/auth/properties/publicKey/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!r.test(t))return u.errors=[{instancePath:l+"/auth/publicKey",schemaPath:"#/properties/auth/properties/publicKey/format",keyword:"format",params:{format:"hex-string"},message:'must match format "hex-string"'}],!1}var y=n===g}else y=!0;if(y){if(void 0!==e.privateKey){let t=e.privateKey;const n=g;if(g===n&&g===n){if("string"!=typeof t)return u.errors=[{instancePath:l+"/auth/privateKey",schemaPath:"#/properties/auth/properties/privateKey/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!r.test(t))return u.errors=[{instancePath:l+"/auth/privateKey",schemaPath:"#/properties/auth/properties/privateKey/format",keyword:"format",params:{format:"hex-string"},message:'must match format "hex-string"'}],!1}y=n===g}else y=!0;if(y){const t=g;if("string"!=typeof e.keyType)return u.errors=[{instancePath:l+"/auth/keyType",schemaPath:"#/properties/auth/properties/keyType/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(y=t===g){if(void 0!==e.ethereum){let t=e.ethereum;const r=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/auth/ethereum",schemaPath:"#/properties/auth/properties/ethereum/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;y=r===g}else y=!0;if(y)if(void 0!==e.identity){let t=e.identity;const r=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/auth/identity",schemaPath:"#/properties/auth/properties/identity/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;y=r===g}else y=!0}}}}}}m=t===g}else m=!0;if(m){const h=g;if("boolean"!=typeof a.orderMessages)return u.errors=[{instancePath:l+"/orderMessages",schemaPath:"#/properties/orderMessages/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(m=h===g){const h=g;if("boolean"!=typeof a.gapFill)return u.errors=[{instancePath:l+"/gapFill",schemaPath:"#/properties/gapFill/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(m=h===g){let h=a.maxGapRequests;const d=g;if("number"!=typeof h||!isFinite(h))return u.errors=[{instancePath:l+"/maxGapRequests",schemaPath:"#/properties/maxGapRequests/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(m=d===g){let h=a.retryResendAfter;const d=g;if("number"!=typeof h||!isFinite(h))return u.errors=[{instancePath:l+"/retryResendAfter",schemaPath:"#/properties/retryResendAfter/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(m=d===g){let h=a.gapFillTimeout;const d=g;if("number"!=typeof h||!isFinite(h))return u.errors=[{instancePath:l+"/gapFillTimeout",schemaPath:"#/properties/gapFillTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(m=d===g){let h=a.gapFillStrategy;const d=g;if("string"!=typeof h)return u.errors=[{instancePath:l+"/gapFillStrategy",schemaPath:"#/properties/gapFillStrategy/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if("light"!==h&&"full"!==h)return u.errors=[{instancePath:l+"/gapFillStrategy",schemaPath:"#/properties/gapFillStrategy/enum",keyword:"enum",params:{allowedValues:e.properties.gapFillStrategy.enum},message:"must be equal to one of the allowed values"}],!1;if(m=d===g){let h=a.network;const d=g;if(g===d){if(!h||"object"!=typeof h||Array.isArray(h))return u.errors=[{instancePath:l+"/network",schemaPath:"#/properties/network/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===h.controlLayer&&(h.controlLayer={}),void 0===h.node&&(h.node={});const r=g;for(const e in h)if("controlLayer"!==e&&"node"!==e)return u.errors=[{instancePath:l+"/network",schemaPath:"#/properties/network/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(r===g){let r=h.controlLayer;const s=g;if(g===s){if(!r||"object"!=typeof r||Array.isArray(r))return u.errors=[{instancePath:l+"/network/controlLayer",schemaPath:"#/properties/network/properties/controlLayer/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===r.entryPointDiscovery&&(r.entryPointDiscovery={enabled:!0,maxEntryPoints:5,maxQueryResults:50,maxHeartbeatAgeHours:24}),void 0===r.websocketPortRange&&(r.websocketPortRange={min:32200,max:32250}),void 0===r.maxConnections&&(r.maxConnections=80),void 0===r.iceServers&&(r.iceServers=[{url:"stun:stun.streamr.network",port:5349},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q=="},{url:"turn:turn.streamr.network",port:5349,username:"BrubeckTurn1",password:"MIlbgtMw4nhpmbgqRrht1Q==",tcp:!0}]),void 0===r.webrtcAllowPrivateAddresses&&(r.webrtcAllowPrivateAddresses=!1),void 0===r.webrtcDatachannelBufferThresholdLow&&(r.webrtcDatachannelBufferThresholdLow=32768),void 0===r.webrtcDatachannelBufferThresholdHigh&&(r.webrtcDatachannelBufferThresholdHigh=131072),void 0===r.maxMessageSize&&(r.maxMessageSize=1048576),void 0===r.webrtcPortRange&&(r.webrtcPortRange={min:5e4,max:64e3}),void 0===r.networkConnectivityTimeout&&(r.networkConnectivityTimeout=1e4),void 0===r.websocketServerEnableTls&&(r.websocketServerEnableTls=!0),void 0===r.autoCertifierUrl&&(r.autoCertifierUrl="https://ns1.streamr-nodes.xyz:59833"),void 0===r.autoCertifierConfigFile&&(r.autoCertifierConfigFile="~/.streamr/certificate.json");const s=g;for(const n in r)if(!t.call(e.properties.network.properties.controlLayer.properties,n))return u.errors=[{instancePath:l+"/network/controlLayer",schemaPath:"#/properties/network/properties/controlLayer/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:n},message:"must NOT have additional properties"}],!1;if(s===g){if(void 0!==r.entryPoints){let e=r.entryPoints;const t=g;if(g===t){if(!Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/entryPoints",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPoints/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{const t=e.length;for(let r=0;r<t;r++){const t=g;if(c(e[r],{instancePath:l+"/network/controlLayer/entryPoints/"+r,parentData:e,parentDataProperty:r,rootData:f})||(p=null===p?c.errors:p.concat(c.errors),g=p.length),!(t===g))break}}}var b=t===g}else b=!0;if(b){let e=r.entryPointDiscovery;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{const t=g;for(const t in e)if("enabled"!==t&&"maxEntryPoints"!==t&&"maxQueryResults"!==t&&"maxHeartbeatAgeHours"!==t)return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.enabled){const t=g;if("boolean"!=typeof e.enabled)return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/enabled",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/enabled/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;var w=t===g}else w=!0;if(w){if(void 0!==e.maxEntryPoints){let t=e.maxEntryPoints;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/maxEntryPoints",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/maxEntryPoints/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;w=r===g}else w=!0;if(w){if(void 0!==e.maxQueryResults){let t=e.maxQueryResults;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/maxQueryResults",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/maxQueryResults/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;w=r===g}else w=!0;if(w)if(void 0!==e.maxHeartbeatAgeHours){let t=e.maxHeartbeatAgeHours;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/entryPointDiscovery/maxHeartbeatAgeHours",schemaPath:"#/properties/network/properties/controlLayer/properties/entryPointDiscovery/properties/maxHeartbeatAgeHours/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;w=r===g}else w=!0}}}}}if(b=t===g){let e=r.websocketPortRange;const t=g,s=g;let o=!1;const a=g;if(null!==e){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketPortRange/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};null===p?p=[e]:p.push(e),g++}var v=a===g;if(o=o||v,!o){const t=g;if(g===g)if(e&&"object"==typeof e&&!Array.isArray(e)){let t;if(void 0===e.min&&(t="min")||void 0===e.max&&(t="max")){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/definitions/portRange/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"};null===p?p=[e]:p.push(e),g++}else{const t=g;for(const t in e)if("min"!==t&&"max"!==t){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/definitions/portRange/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"};null===p?p=[e]:p.push(e),g++;break}if(t===g){if(void 0!==e.min){let t=e.min;const r=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/network/controlLayer/websocketPortRange/min",schemaPath:"#/definitions/portRange/properties/min/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}var E=r===g}else E=!0;if(E)if(void 0!==e.max){let t=e.max;const r=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/network/controlLayer/websocketPortRange/max",schemaPath:"#/definitions/portRange/properties/max/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}E=r===g}else E=!0}}}else{const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/definitions/portRange/type",keyword:"type",params:{type:"object"},message:"must be object"};null===p?p=[e]:p.push(e),g++}v=t===g;o=o||v}if(!o){const e={instancePath:l+"/network/controlLayer/websocketPortRange",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketPortRange/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};return null===p?p=[e]:p.push(e),g++,u.errors=p,!1}if(g=s,null!==p&&(s?p.length=s:p=null),b=t===g){if(void 0!==r.websocketHost){let e=r.websocketHost;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/network/controlLayer/websocketHost",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketHost/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!n.test(e))return u.errors=[{instancePath:l+"/network/controlLayer/websocketHost",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketHost/format",keyword:"format",params:{format:"hostname"},message:'must match format "hostname"'}],!1}b=t===g}else b=!0;if(b){if(void 0!==r.peerDescriptor){const e=g;c(r.peerDescriptor,{instancePath:l+"/network/controlLayer/peerDescriptor",parentData:r,parentDataProperty:"peerDescriptor",rootData:f})||(p=null===p?c.errors:p.concat(c.errors),g=p.length);b=e===g}else b=!0;if(b){let e=r.maxConnections;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/maxConnections",schemaPath:"#/properties/network/properties/controlLayer/properties/maxConnections/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){if(void 0!==r.tlsCertificate){let e=r.tlsCertificate;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let t;if(void 0===e.certFileName&&(t="certFileName")||void 0===e.privateKeyFileName&&(t="privateKeyFileName"))return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"}],!1;{const t=g;for(const t in e)if("certFileName"!==t&&"privateKeyFileName"!==t)return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.certFileName){const t=g;if("string"!=typeof e.certFileName)return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate/certFileName",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/properties/certFileName/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var A=t===g}else A=!0;if(A)if(void 0!==e.privateKeyFileName){const t=g;if("string"!=typeof e.privateKeyFileName)return u.errors=[{instancePath:l+"/network/controlLayer/tlsCertificate/privateKeyFileName",schemaPath:"#/properties/network/properties/controlLayer/properties/tlsCertificate/properties/privateKeyFileName/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;A=t===g}else A=!0}}}}b=t===g}else b=!0;if(b){let e=r.iceServers;const t=g;if(g===t){if(!Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;{const t=e.length;for(let r=0;r<t;r++){let t=e[r];const n=g;if(g===n){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r,schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let e;if(void 0===t.url&&(e="url")||void 0===t.port&&(e="port"))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r,schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/required",keyword:"required",params:{missingProperty:e},message:"must have required property '"+e+"'"}],!1;{const e=g;for(const e in t)if("url"!==e&&"port"!==e&&"username"!==e&&"password"!==e&&"tcp"!==e)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r,schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){if(void 0!==t.url){const e=g;if("string"!=typeof t.url)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/url",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var S=e===g}else S=!0;if(S){if(void 0!==t.port){let e=t.port;const n=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/port",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/port/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;S=n===g}else S=!0;if(S){if(void 0!==t.username){const e=g;if("string"!=typeof t.username)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/username",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/username/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;S=e===g}else S=!0;if(S){if(void 0!==t.password){const e=g;if("string"!=typeof t.password)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/password",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/password/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;S=e===g}else S=!0;if(S)if(void 0!==t.tcp){const e=g;if("boolean"!=typeof t.tcp)return u.errors=[{instancePath:l+"/network/controlLayer/iceServers/"+r+"/tcp",schemaPath:"#/properties/network/properties/controlLayer/properties/iceServers/items/properties/tcp/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;S=e===g}else S=!0}}}}}}}if(!(n===g))break}}}if(b=t===g){const e=g;if("boolean"!=typeof r.webrtcAllowPrivateAddresses)return u.errors=[{instancePath:l+"/network/controlLayer/webrtcAllowPrivateAddresses",schemaPath:"#/properties/network/properties/controlLayer/properties/webrtcAllowPrivateAddresses/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(b=e===g){let e=r.webrtcDatachannelBufferThresholdLow;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcDatachannelBufferThresholdLow",schemaPath:"#/properties/network/properties/controlLayer/properties/webrtcDatachannelBufferThresholdLow/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){let e=r.webrtcDatachannelBufferThresholdHigh;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcDatachannelBufferThresholdHigh",schemaPath:"#/properties/network/properties/controlLayer/properties/webrtcDatachannelBufferThresholdHigh/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){let e=r.maxMessageSize;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/maxMessageSize",schemaPath:"#/properties/network/properties/controlLayer/properties/maxMessageSize/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){if(void 0!==r.externalIp){let e=r.externalIp;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/network/controlLayer/externalIp",schemaPath:"#/properties/network/properties/controlLayer/properties/externalIp/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!i.test(e))return u.errors=[{instancePath:l+"/network/controlLayer/externalIp",schemaPath:"#/properties/network/properties/controlLayer/properties/externalIp/format",keyword:"format",params:{format:"ipv4"},message:'must match format "ipv4"'}],!1}b=t===g}else b=!0;if(b){let e=r.webrtcPortRange;const t=g;if(g===g){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange",schemaPath:"#/definitions/portRange/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let t;if(void 0===e.min&&(t="min")||void 0===e.max&&(t="max"))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange",schemaPath:"#/definitions/portRange/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"}],!1;{const t=g;for(const t in e)if("min"!==t&&"max"!==t)return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange",schemaPath:"#/definitions/portRange/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.min){let t=e.min;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange/min",schemaPath:"#/definitions/portRange/properties/min/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;var k=r===g}else k=!0;if(k)if(void 0!==e.max){let t=e.max;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/controlLayer/webrtcPortRange/max",schemaPath:"#/definitions/portRange/properties/max/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;k=r===g}else k=!0}}}}if(b=t===g){let e=r.networkConnectivityTimeout;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/network/controlLayer/networkConnectivityTimeout",schemaPath:"#/properties/network/properties/controlLayer/properties/networkConnectivityTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(b=t===g){const e=g;if("boolean"!=typeof r.websocketServerEnableTls)return u.errors=[{instancePath:l+"/network/controlLayer/websocketServerEnableTls",schemaPath:"#/properties/network/properties/controlLayer/properties/websocketServerEnableTls/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(b=e===g){const e=g;if("string"!=typeof r.autoCertifierUrl)return u.errors=[{instancePath:l+"/network/controlLayer/autoCertifierUrl",schemaPath:"#/properties/network/properties/controlLayer/properties/autoCertifierUrl/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(b=e===g){const e=g;if("string"!=typeof r.autoCertifierConfigFile)return u.errors=[{instancePath:l+"/network/controlLayer/autoCertifierConfigFile",schemaPath:"#/properties/network/properties/controlLayer/properties/autoCertifierConfigFile/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(b=e===g)if(void 0!==r.geoIpDatabaseFolder){const e=g;if("string"!=typeof r.geoIpDatabaseFolder)return u.errors=[{instancePath:l+"/network/controlLayer/geoIpDatabaseFolder",schemaPath:"#/properties/network/properties/controlLayer/properties/geoIpDatabaseFolder/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;b=e===g}else b=!0}}}}}}}}}}}}}}}}}}}}if(s===g){let e=h.node;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/network/node",schemaPath:"#/properties/network/properties/node/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.streamPartitionNeighborTargetCount&&(e.streamPartitionNeighborTargetCount=4),void 0===e.streamPartitionMinPropagationTargets&&(e.streamPartitionMinPropagationTargets=2),void 0===e.streamPartitionMaxPropagationBufferSize&&(e.streamPartitionMaxPropagationBufferSize=150),void 0===e.contentDeliveryBufferWhileConnecting&&(e.contentDeliveryBufferWhileConnecting=!0),void 0===e.acceptProxyConnections&&(e.acceptProxyConnections=!1);const t=g;for(const t in e)if("streamPartitionNeighborTargetCount"!==t&&"streamPartitionMinPropagationTargets"!==t&&"streamPartitionMaxPropagationBufferSize"!==t&&"contentDeliveryBufferWhileConnecting"!==t&&"acceptProxyConnections"!==t)return u.errors=[{instancePath:l+"/network/node",schemaPath:"#/properties/network/properties/node/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.streamPartitionNeighborTargetCount;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/node/streamPartitionNeighborTargetCount",schemaPath:"#/properties/network/properties/node/properties/streamPartitionNeighborTargetCount/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let t=e.streamPartitionMinPropagationTargets;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/node/streamPartitionMinPropagationTargets",schemaPath:"#/properties/network/properties/node/properties/streamPartitionMinPropagationTargets/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let t=e.streamPartitionMaxPropagationBufferSize;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/network/node/streamPartitionMaxPropagationBufferSize",schemaPath:"#/properties/network/properties/node/properties/streamPartitionMaxPropagationBufferSize/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){const t=g;if("boolean"!=typeof e.contentDeliveryBufferWhileConnecting)return u.errors=[{instancePath:l+"/network/node/contentDeliveryBufferWhileConnecting",schemaPath:"#/properties/network/properties/node/properties/contentDeliveryBufferWhileConnecting/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){if("boolean"!=typeof e.acceptProxyConnections)return u.errors=[{instancePath:l+"/network/node/acceptProxyConnections",schemaPath:"#/properties/network/properties/node/properties/acceptProxyConnections/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1}}}}}}}}}}}if(m=d===g){let n=a.contracts;const i=g;if(g===i){if(!n||"object"!=typeof n||Array.isArray(n))return u.errors=[{instancePath:l+"/contracts",schemaPath:"#/properties/contracts/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===n.ethereumNetwork&&(n.ethereumNetwork={}),void 0===n.rpcQuorum&&(n.rpcQuorum=2),void 0===n.maxConcurrentCalls&&(n.maxConcurrentCalls=10),void 0===n.pollInterval&&(n.pollInterval=4e3);const r=g;for(const r in n)if(!t.call(e.properties.contracts.properties,r))return u.errors=[{instancePath:l+"/contracts",schemaPath:"#/properties/contracts/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:r},message:"must NOT have additional properties"}],!1;if(r===g){let e=n.ethereumNetwork;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/contracts/ethereumNetwork",schemaPath:"#/properties/contracts/properties/ethereumNetwork/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{const t=g;for(const t in e)if("chainId"!==t&&"overrides"!==t&&"highGasPriceStrategy"!==t)return u.errors=[{instancePath:l+"/contracts/ethereumNetwork",schemaPath:"#/properties/contracts/properties/ethereumNetwork/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){if(void 0!==e.chainId){let t=e.chainId;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/contracts/ethereumNetwork/chainId",schemaPath:"#/properties/contracts/properties/ethereumNetwork/properties/chainId/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;var R=r===g}else R=!0;if(R){if(void 0!==e.overrides){let t=e.overrides;const r=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/contracts/ethereumNetwork/overrides",schemaPath:"#/properties/contracts/properties/ethereumNetwork/properties/overrides/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;R=r===g}else R=!0;if(R)if(void 0!==e.highGasPriceStrategy){const t=g;if("boolean"!=typeof e.highGasPriceStrategy)return u.errors=[{instancePath:l+"/contracts/ethereumNetwork/highGasPriceStrategy",schemaPath:"#/properties/contracts/properties/ethereumNetwork/properties/highGasPriceStrategy/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;R=t===g}else R=!0}}}}if(C=t===g){if(void 0!==n.streamRegistryChainAddress){let e=n.streamRegistryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/streamRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamRegistryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/streamRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamRegistryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}var C=t===g}else C=!0;if(C){if(void 0!==n.streamStorageRegistryChainAddress){let e=n.streamStorageRegistryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/streamStorageRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamStorageRegistryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/streamStorageRegistryChainAddress",schemaPath:"#/properties/contracts/properties/streamStorageRegistryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}C=t===g}else C=!0;if(C){if(void 0!==n.storageNodeRegistryChainAddress){let e=n.storageNodeRegistryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/storageNodeRegistryChainAddress",schemaPath:"#/properties/contracts/properties/storageNodeRegistryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/storageNodeRegistryChainAddress",schemaPath:"#/properties/contracts/properties/storageNodeRegistryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}C=t===g}else C=!0;if(C){if(void 0!==n.sponsorshipFactoryChainAddress){let e=n.sponsorshipFactoryChainAddress;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/sponsorshipFactoryChainAddress",schemaPath:"#/properties/contracts/properties/sponsorshipFactoryChainAddress/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!s.test(e))return u.errors=[{instancePath:l+"/contracts/sponsorshipFactoryChainAddress",schemaPath:"#/properties/contracts/properties/sponsorshipFactoryChainAddress/format",keyword:"format",params:{format:"ethereum-address"},message:'must match format "ethereum-address"'}],!1}C=t===g}else C=!0;if(C){if(void 0!==n.rpcs){let e=n.rpcs;const t=g;if(g===t){if(!Array.isArray(e))return u.errors=[{instancePath:l+"/contracts/rpcs",schemaPath:"#/properties/contracts/properties/rpcs/type",keyword:"type",params:{type:"array"},message:"must be array"}],!1;if(e.length<1)return u.errors=[{instancePath:l+"/contracts/rpcs",schemaPath:"#/properties/contracts/properties/rpcs/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"}],!1;{const t=e.length;for(let r=0;r<t;r++){let t=e[r];const n=g;if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r,schemaPath:"#/properties/contracts/properties/rpcs/items/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;if(g===g){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r,schemaPath:"#/definitions/rpcProviderConfig/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let e;if(void 0===t.url&&(e="url"))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r,schemaPath:"#/definitions/rpcProviderConfig/required",keyword:"required",params:{missingProperty:e},message:"must have required property '"+e+"'"}],!1;if(void 0!==t.url){let e=t.url;if(g===g&&g===g){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/rpcs/"+r+"/url",schemaPath:"#/definitions/rpcProviderConfig/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!o.test(e))return u.errors=[{instancePath:l+"/contracts/rpcs/"+r+"/url",schemaPath:"#/definitions/rpcProviderConfig/properties/url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'}],!1}}}}if(!(n===g))break}}}C=t===g}else C=!0;if(C){let e=n.rpcQuorum;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/contracts/rpcQuorum",schemaPath:"#/properties/contracts/properties/rpcQuorum/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(C=t===g){if(void 0!==n.theGraphUrl){let e=n.theGraphUrl;const t=g;if(g===t&&g===t){if("string"!=typeof e)return u.errors=[{instancePath:l+"/contracts/theGraphUrl",schemaPath:"#/properties/contracts/properties/theGraphUrl/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!o.test(e))return u.errors=[{instancePath:l+"/contracts/theGraphUrl",schemaPath:"#/properties/contracts/properties/theGraphUrl/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'}],!1}C=t===g}else C=!0;if(C){let e=n.maxConcurrentCalls;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/contracts/maxConcurrentCalls",schemaPath:"#/properties/contracts/properties/maxConcurrentCalls/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(C=t===g){let e=n.pollInterval;const t=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/contracts/pollInterval",schemaPath:"#/properties/contracts/properties/pollInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;C=t===g}}}}}}}}}}}}if(m=i===g){let e=a.encryption;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/encryption",schemaPath:"#/properties/encryption/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.keyRequestTimeout&&(e.keyRequestTimeout=3e4),void 0===e.maxKeyRequestsPerSecond&&(e.maxKeyRequestsPerSecond=20),void 0===e.rsaKeyLength&&(e.rsaKeyLength=4096),void 0===e.requireQuantumResistantKeyExchange&&(e.requireQuantumResistantKeyExchange=!1),void 0===e.requireQuantumResistantSignatures&&(e.requireQuantumResistantSignatures=!1),void 0===e.requireQuantumResistantEncryption&&(e.requireQuantumResistantEncryption=!1);const t=g;for(const t in e)if("keyRequestTimeout"!==t&&"maxKeyRequestsPerSecond"!==t&&"rsaKeyLength"!==t&&"requireQuantumResistantKeyExchange"!==t&&"requireQuantumResistantSignatures"!==t&&"requireQuantumResistantEncryption"!==t&&"keys"!==t)return u.errors=[{instancePath:l+"/encryption",schemaPath:"#/properties/encryption/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.keyRequestTimeout;const n=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/encryption/keyRequestTimeout",schemaPath:"#/properties/encryption/properties/keyRequestTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(n===g){let t=e.maxKeyRequestsPerSecond;const n=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/encryption/maxKeyRequestsPerSecond",schemaPath:"#/properties/encryption/properties/maxKeyRequestsPerSecond/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(n===g){let t=e.rsaKeyLength;const n=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/encryption/rsaKeyLength",schemaPath:"#/properties/encryption/properties/rsaKeyLength/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(n===g){const t=g;if("boolean"!=typeof e.requireQuantumResistantKeyExchange)return u.errors=[{instancePath:l+"/encryption/requireQuantumResistantKeyExchange",schemaPath:"#/properties/encryption/properties/requireQuantumResistantKeyExchange/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){const t=g;if("boolean"!=typeof e.requireQuantumResistantSignatures)return u.errors=[{instancePath:l+"/encryption/requireQuantumResistantSignatures",schemaPath:"#/properties/encryption/properties/requireQuantumResistantSignatures/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){const t=g;if("boolean"!=typeof e.requireQuantumResistantEncryption)return u.errors=[{instancePath:l+"/encryption/requireQuantumResistantEncryption",schemaPath:"#/properties/encryption/properties/requireQuantumResistantEncryption/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g)if(void 0!==e.keys){let t=e.keys;const n=g;if(g===n){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/encryption/keys",schemaPath:"#/properties/encryption/properties/keys/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;for(const e in t){const t=g;if("string"!=typeof e){const t={instancePath:l+"/encryption/keys",schemaPath:"#/definitions/streamIdOrPath/type",keyword:"type",params:{type:"string"},message:"must be string",propertyName:e};null===p?p=[t]:p.push(t),g++}var I=t===g;if(!I){const t={instancePath:l+"/encryption/keys",schemaPath:"#/properties/encryption/properties/keys/propertyNames",keyword:"propertyNames",params:{propertyName:e},message:"property name must be valid"};return null===p?p=[t]:p.push(t),g++,u.errors=p,!1}}if(I)for(const e in t){let n=t[e];const i=g;if(g===g){if(!n||"object"!=typeof n||Array.isArray(n))return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/definitions/encryptionKey/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{let t;if(void 0===n.id&&(t="id")||void 0===n.data&&(t="data"))return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1"),schemaPath:"#/definitions/encryptionKey/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"}],!1;if(void 0!==n.id){const t=g;if("string"!=typeof n.id)return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/id",schemaPath:"#/definitions/encryptionKey/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;var P=t===g}else P=!0;if(P)if(void 0!==n.data){let t=n.data;const i=g;if(g===i&&g===i){if("string"!=typeof t)return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/data",schemaPath:"#/definitions/encryptionKey/properties/data/type",keyword:"type",params:{type:"string"},message:"must be string"}],!1;if(!r.test(t))return u.errors=[{instancePath:l+"/encryption/keys/"+e.replace(/~/g,"~0").replace(/\//g,"~1")+"/data",schemaPath:"#/definitions/encryptionKey/properties/data/format",keyword:"format",params:{format:"hex-string"},message:'must match format "hex-string"'}],!1}P=i===g}else P=!0}}if(!(i===g))break}}}else;}}}}}}}}if(m=t===g){let e=a.validation;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/validation",schemaPath:"#/properties/validation/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.permissions&&(e.permissions=!0),void 0===e.partitions&&(e.partitions=!0);const t=g;for(const t in e)if("permissions"!==t&&"partitions"!==t)return u.errors=[{instancePath:l+"/validation",schemaPath:"#/properties/validation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){const t=g;if("boolean"!=typeof e.permissions)return u.errors=[{instancePath:l+"/validation/permissions",schemaPath:"#/properties/validation/properties/permissions/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1;if(t===g){if("boolean"!=typeof e.partitions)return u.errors=[{instancePath:l+"/validation/partitions",schemaPath:"#/properties/validation/properties/partitions/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"}],!1}}}}if(m=t===g){if(void 0!==a.metrics){let e=a.metrics;const t=g,r=g;let n=!1;const i=g;if("boolean"!=typeof e){const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf/0/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};null===p?p=[e]:p.push(e),g++}var T=i===g;if(n=n||T,!n){const t=g;if(g===t)if(e&&"object"==typeof e&&!Array.isArray(e)){const t=g;for(const t in e)if("periods"!==t&&"maxPublishDelay"!==t){const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"};null===p?p=[e]:p.push(e),g++;break}if(t===g){if(void 0!==e.periods){let t=e.periods;const r=g;if(g===r)if(Array.isArray(t)){const e=t.length;for(let r=0;r<e;r++){let e=t[r];const n=g;if(g===n)if(e&&"object"==typeof e&&!Array.isArray(e)){let t;if(void 0===e.streamId&&(t="streamId")||void 0===e.duration&&(t="duration")){const e={instancePath:l+"/metrics/periods/"+r,schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/required",keyword:"required",params:{missingProperty:t},message:"must have required property '"+t+"'"};null===p?p=[e]:p.push(e),g++}else{if(void 0!==e.id){const t=g;if("string"!=typeof e.id){const e={instancePath:l+"/metrics/periods/"+r+"/id",schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};null===p?p=[e]:p.push(e),g++}var _=t===g}else _=!0;if(_)if(void 0!==e.duration){let t=e.duration;const n=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/metrics/periods/"+r+"/duration",schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/properties/duration/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}_=n===g}else _=!0}}else{const e={instancePath:l+"/metrics/periods/"+r,schemaPath:"#/properties/metrics/anyOf/1/properties/periods/items/type",keyword:"type",params:{type:"object"},message:"must be object"};null===p?p=[e]:p.push(e),g++}if(!(n===g))break}}else{const e={instancePath:l+"/metrics/periods",schemaPath:"#/properties/metrics/anyOf/1/properties/periods/type",keyword:"type",params:{type:"array"},message:"must be array"};null===p?p=[e]:p.push(e),g++}var N=r===g}else N=!0;if(N)if(void 0!==e.maxPublishDelay){let t=e.maxPublishDelay;const r=g;if("number"!=typeof t||!isFinite(t)){const e={instancePath:l+"/metrics/maxPublishDelay",schemaPath:"#/properties/metrics/anyOf/1/properties/maxPublishDelay/type",keyword:"type",params:{type:"number"},message:"must be number"};null===p?p=[e]:p.push(e),g++}N=r===g}else N=!0}}else{const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};null===p?p=[e]:p.push(e),g++}T=t===g;n=n||T}if(!n){const e={instancePath:l+"/metrics",schemaPath:"#/properties/metrics/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};return null===p?p=[e]:p.push(e),g++,u.errors=p,!1}g=r,null!==p&&(r?p.length=r:p=null);m=t===g}else m=!0;if(m){let e=a.cache;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/cache",schemaPath:"#/properties/cache/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.maxSize&&(e.maxSize=1e4),void 0===e.maxAge&&(e.maxAge=864e5);const t=g;for(const t in e)if("maxSize"!==t&&"maxAge"!==t)return u.errors=[{instancePath:l+"/cache",schemaPath:"#/properties/cache/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.maxSize;const r=g;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/cache/maxSize",schemaPath:"#/properties/cache/properties/maxSize/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let t=e.maxAge;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/cache/maxAge",schemaPath:"#/properties/cache/properties/maxAge/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}if(m=t===g){let e=a._timeouts;const t=g;if(g===t){if(!e||"object"!=typeof e||Array.isArray(e))return u.errors=[{instancePath:l+"/_timeouts",schemaPath:"#/properties/_timeouts/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===e.theGraph&&(e.theGraph={}),void 0===e.storageNode&&(e.storageNode={}),void 0===e.ensStreamCreation&&(e.ensStreamCreation={}),void 0===e.jsonRpcTimeout&&(e.jsonRpcTimeout=3e4);const t=g;for(const t in e)if("theGraph"!==t&&"storageNode"!==t&&"ensStreamCreation"!==t&&"jsonRpcTimeout"!==t)return u.errors=[{instancePath:l+"/_timeouts",schemaPath:"#/properties/_timeouts/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:t},message:"must NOT have additional properties"}],!1;if(t===g){let t=e.theGraph;const r=g;if(g===r){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/_timeouts/theGraph",schemaPath:"#/properties/_timeouts/properties/theGraph/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===t.indexTimeout&&(t.indexTimeout=6e4),void 0===t.indexPollInterval&&(t.indexPollInterval=1e3),void 0===t.fetchTimeout&&(t.fetchTimeout=3e4);const e=g;for(const e in t)if("indexTimeout"!==e&&"indexPollInterval"!==e&&"fetchTimeout"!==e)return u.errors=[{instancePath:l+"/_timeouts/theGraph",schemaPath:"#/properties/_timeouts/properties/theGraph/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){let e=t.indexTimeout;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/theGraph/indexTimeout",schemaPath:"#/properties/_timeouts/properties/theGraph/properties/indexTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.indexPollInterval;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/theGraph/indexPollInterval",schemaPath:"#/properties/_timeouts/properties/theGraph/properties/indexPollInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.fetchTimeout;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/theGraph/fetchTimeout",schemaPath:"#/properties/_timeouts/properties/theGraph/properties/fetchTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}}if(r===g){let t=e.storageNode;const r=g;if(g===r){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/_timeouts/storageNode",schemaPath:"#/properties/_timeouts/properties/storageNode/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===t.timeout&&(t.timeout=3e4),void 0===t.retryInterval&&(t.retryInterval=1e3);const e=g;for(const e in t)if("timeout"!==e&&"retryInterval"!==e)return u.errors=[{instancePath:l+"/_timeouts/storageNode",schemaPath:"#/properties/_timeouts/properties/storageNode/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){let e=t.timeout;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/storageNode/timeout",schemaPath:"#/properties/_timeouts/properties/storageNode/properties/timeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.retryInterval;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/storageNode/retryInterval",schemaPath:"#/properties/_timeouts/properties/storageNode/properties/retryInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}if(r===g){let t=e.ensStreamCreation;const r=g;if(g===r){if(!t||"object"!=typeof t||Array.isArray(t))return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/type",keyword:"type",params:{type:"object"},message:"must be object"}],!1;{void 0===t.timeout&&(t.timeout=18e4),void 0===t.retryInterval&&(t.retryInterval=1e3);const e=g;for(const e in t)if("timeout"!==e&&"retryInterval"!==e)return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:e},message:"must NOT have additional properties"}],!1;if(e===g){let e=t.timeout;const r=g;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation/timeout",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/properties/timeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1;if(r===g){let e=t.retryInterval;if("number"!=typeof e||!isFinite(e))return u.errors=[{instancePath:l+"/_timeouts/ensStreamCreation/retryInterval",schemaPath:"#/properties/_timeouts/properties/ensStreamCreation/properties/retryInterval/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}if(r===g){let t=e.jsonRpcTimeout;if("number"!=typeof t||!isFinite(t))return u.errors=[{instancePath:l+"/_timeouts/jsonRpcTimeout",schemaPath:"#/properties/_timeouts/properties/jsonRpcTimeout/type",keyword:"type",params:{type:"number"},message:"must be number"}],!1}}}}}}m=t===g}}}}}}}}}}}}}}}}}}}return u.errors=p,0===g}return q1.exports}(),K1=n(z1);const G1={network:{controlLayer:{entryPointDiscovery:{enabled:!1},websocketPortRange:{min:32400,max:32800},iceServers:[],webrtcAllowPrivateAddresses:!0,websocketServerEnableTls:!1}},encryption:{rsaKeyLength:640},_timeouts:{theGraph:{indexTimeout:1e4,indexPollInterval:500},storageNode:{timeout:3e4,retryInterval:500},ensStreamCreation:{timeout:2e4,retryInterval:500}},metrics:!1};nb("0xde1112f631486CfC759A50196853011528bC5FA0");const V1=(e={})=>{let t=j1(e);const r=t.environment??aA;t=H1(r,t);const n=$1(t);return n.id??=VW("undefined"!=typeof process&&process.pid?`${process.pid}`:Wv(4),"/"),n},H1=(e,t)=>{const r=ZO.config[e];let n=aE({environment:e,network:{controlLayer:{entryPoints:r.entryPoints}},contracts:{ethereumNetwork:{chainId:r.id},streamRegistryChainAddress:r.contracts.StreamRegistry,streamStorageRegistryChainAddress:r.contracts.StreamStorageRegistry,storageNodeRegistryChainAddress:r.contracts.StorageNodeRegistry,sponsorshipFactoryChainAddress:r.contracts.SponsorshipFactory,rpcs:r.rpcEndpoints,theGraphUrl:r.theGraphUrl}},t);return"polygon"===e?n.contracts.ethereumNetwork={highGasPriceStrategy:!0,...n.contracts.ethereumNetwork}:"dev2"===e&&(n=aE(G1,n)),n},$1=e=>{if(!K1(e))throw new Error(K1.errors.map((e=>{let t=e.instancePath+" "+e.message;return e.params.additionalProperty&&(t+=`: ${e.params.additionalProperty}`),t})).join("\n"));return e},W1={...Object.fromEntries(l0.map((e=>[e.signatureType,e.keyType]))),[e.SignatureType.ECDSA_SECP256K1_LEGACY]:"ECDSA_SECP256K1_LEGACY",[e.SignatureType.ERC_1271]:"ERC_1271"};function J1(e){const t=W1[e];if(!t)throw new Error(`Unknown signature type: ${e}`);return t}const Q1=e=>({content:e.getParsedContent(),streamId:e.getStreamId(),streamPartition:e.getStreamPartition(),timestamp:e.getTimestamp(),sequenceNumber:e.getSequenceNumber(),signature:e.signature,signatureType:J1(e.signatureType),publisherId:e.getPublisherId(),msgChainId:e.getMsgChainId(),encryptionKeyId:e.groupKeyId,streamMessage:e});var Z1=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},Y1=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},X1=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};const e2={periods:[{duration:6e4,streamId:"streamr.eth/metrics/nodes/firehose/min"},{duration:36e5,streamId:"streamr.eth/metrics/nodes/firehose/hour"},{duration:864e5,streamId:"streamr.eth/metrics/nodes/firehose/day"}],maxPublishDelay:3e4};let t2=class{publisher;node;config;eventEmitter;destroySignal;constructor(e,t,r,n,i){this.publisher=e,this.node=t,this.config=(e=>{if(!0===e.metrics)return e2;if(!1===e.metrics)return{...e2,periods:[]};if(void 0!==e.metrics)return aE(e2,e.metrics);{const t=void 0!==e.auth?.ethereum;return{...e2,periods:t?[]:e2.periods}}})(r),this.eventEmitter=n,this.destroySignal=i;const s=nJ((async()=>{const e=await this.node.getMetricsContext(),t=await this.node.getNodeId();this.config.periods.forEach((r=>{e.createReportProducer((async e=>{await this.publish(e,r.streamId,t)}),r.duration,this.destroySignal.abortSignal)}))}));this.config.periods.length>0&&(this.eventEmitter.on("messagePublished",(()=>s())),this.eventEmitter.on("streamPartSubscribed",(()=>s())))}async publish(e,t,r){await Qv(Math.random()*this.config.maxPublishDelay);const n={...e,node:{...e.node,id:r}};try{await this.publisher.publish(t,n,{timestamp:e.period.end,partitionKey:r})}catch(e){console.warn(`Unable to publish metrics: ${e.message}`)}}};t2=Z1([q(d.ContainerScoped),X1(2,U(cA)),Y1("design:paramtypes",[B1,GX,Object,sD,dJ])],t2);var r2=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},n2=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let i2=class{streamIdBuilder;operatorRegistry;node;logger;constructor(e,t,r,n){this.streamIdBuilder=e,this.operatorRegistry=t,this.node=r,this.logger=n.createLogger("ProxyNodeFinder")}async find(e,t=1,r=100,n=24){const[i,s]=await this.streamIdBuilder.toStreamPartElements(e);this.logger.debug(`Trying to find ${t} proxy nodes for stream ${i} partition ${s}`);const o=await this.operatorRegistry.findOperatorsOnStream(i,r,n);if(this.logger.debug(`Found ${o.length} operators on stream ${i}`),o.length<t)throw new Error(`Not enough operators found for stream ${i}: found ${o.length} operators, but ${t} are required`);const a=JU(o),c=[];let u=()=>{};const l=new Promise((e=>{u=e}));let h=0;const d=async e=>{for(;h<a.length&&c.length<t;){const r=a[h];h++;const n=EE(i,s??0);try{const i=await this.node.discoverOperators(r.peerDescriptor,n);i.length>0?c.length<t&&(this.logger.debug(`(worker ${e}): found ${i.length} nodes for operator ${r.operatorId} and streamPartId ${n}`),c.push(oA(i)),c.length>=t&&u()):this.logger.debug(`(worker ${e}): no nodes found for operator ${r.operatorId} and streamPartId ${n}`)}catch(t){this.logger.error(`(worker ${e}): error discovering nodes for operator ${r.operatorId}: ${t.message}`)}}};if(await Promise.race([Promise.all(Array.from({length:t},((e,t)=>d(t)))),l]),c.length<t)throw new Error(`Not enough proxy nodes were resolved for stream ${i}: found ${c.length} nodes, but ${t} are required`);return c}};var s2,o2;i2=r2([q(d.ContainerScoped),n2("design:paramtypes",[RJ,UY,GX,uD])],i2);var a2,c2,u2,l2,h2,d2,f2=n(function(){if(o2)return s2;o2=1;var e=De(),t=Be();return s2=function(r){return"number"==typeof r||t(r)&&"[object Number]"==e(r)}}());function p2(){if(l2)return u2;l2=1;var e=function(){if(c2)return a2;c2=1;var e=Math.ceil,t=Math.max;return a2=function(r,n,i,s){for(var o=-1,a=t(e((n-r)/(i||1)),0),c=Array(a);a--;)c[s?a:++o]=r,r+=i;return c}}(),t=_d(),r=Fe();return u2=function(n){return function(i,s,o){return o&&"number"!=typeof o&&t(i,s,o)&&(s=o=void 0),i=r(i),void 0===s?(s=i,i=0):s=r(s),o=void 0===o?i<s?1:-1:r(o),e(i,s,o,n)}}}var g2=function(){if(d2)return h2;d2=1;var e=p2()();return h2=e}(),m2=n(g2);class y2{id;client;constructor(e,t){this.id=e,this.client=t}publish(e,t){return this.client.publish(this.id,e,t)}async hasPermission(e){return this.client.hasPermission({streamId:this.id,...e})}async getPermissions(){return this.client.getPermissions(this.id)}async grantPermissions(...e){return this.client.grantPermissions(this.id,...e.map(NJ))}async revokePermissions(...e){return this.client.revokePermissions(this.id,...e.map(NJ))}async addToStorageNode(e,t={wait:!1}){await this.client.addStreamToStorageNode(this.id,e,t)}async removeFromStorageNode(e){return this.client.removeStreamFromStorageNode(this.id,nb(e))}async getStorageNodes(){return this.client.getStorageNodes(this.id)}async getStreamParts(){return m2(0,await this.getPartitionCount()).map((e=>EE(this.id,e)))}async getPartitionCount(){return IJ(await this.getMetadata())}async getDescription(){const e=(await this.getMetadata()).description;return _1(e)?e:void 0}async setDescription(e){await this.setMetadata({...await this.getMetadata(),description:e})}async getStorageDayCount(){const e=(await this.getMetadata()).storageDays;return f2(e)?e:void 0}async setStorageDayCount(e){await this.setMetadata({...await this.getMetadata(),storageDays:e})}async getMetadata(){return this.client.getStreamMetadata(this.id)}async setMetadata(e){await this.client.setStreamMetadata(this.id,e)}}function b2(e,t,r){function n(r,n){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:n,constr:o,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,n);const i=o.prototype,s=Object.keys(i);for(let e=0;e<s.length;e++){const t=s[e];t in r||(r[t]=i[t].bind(r))}}const i=r?.Parent??Object;class s extends i{}function o(e){var t;const i=r?.Parent?new s:this;n(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(s,"name",{value:e}),Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}class w2 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class v2 extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const E2={};function A2(e){return E2}function S2(e,t){return"bigint"==typeof t?t.toString():t}function k2(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function R2(e){return null==e}function C2(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const I2=Symbol("evaluating");function P2(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==I2)return void 0===n&&(n=I2,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function T2(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function _2(...e){const t={};for(const r of e){const e=Object.getOwnPropertyDescriptors(r);Object.assign(t,e)}return Object.defineProperties({},t)}function N2(e){return JSON.stringify(e)}const M2="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function x2(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const O2=k2((()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}}));function D2(e){if(!1===x2(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const r=t.prototype;return!1!==x2(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function B2(e){return D2(e)?{...e}:Array.isArray(e)?[...e]:e}const L2=new Set(["string","number","symbol"]);function F2(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function U2(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const j2={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function q2(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function z2(e,t){return t.map((t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t}))}function K2(e){return"string"==typeof e?e:e?.message}function G2(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const i=K2(e.inst?._zod.def?.error?.(e))??K2(t?.error?.(e))??K2(r.customError?.(e))??K2(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function V2(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function H2(...e){const[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}const $2=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,S2,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},W2=b2("$ZodError",$2),J2=b2("$ZodError",$2,{Parent:Error});const Q2=e=>(t,r,n,i)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new w2;if(o.issues.length){const t=new(i?.Err??e)(o.issues.map((e=>G2(e,s,A2()))));throw M2(t,i?.callee),t}return o.value},Z2=e=>async(t,r,n,i)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const t=new(i?.Err??e)(o.issues.map((e=>G2(e,s,A2()))));throw M2(t,i?.callee),t}return o.value},Y2=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new w2;return s.issues.length?{success:!1,error:new(e??W2)(s.issues.map((e=>G2(e,i,A2()))))}:{success:!0,data:s.value}},X2=Y2(J2),e3=e=>async(t,r,n)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map((e=>G2(e,i,A2()))))}:{success:!0,data:s.value}},t3=e3(J2),r3=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Q2(e)(t,r,i)},n3=e=>(t,r,n)=>Q2(e)(t,r,n),i3=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Z2(e)(t,r,i)},s3=e=>async(t,r,n)=>Z2(e)(t,r,n),o3=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Y2(e)(t,r,i)},a3=e=>(t,r,n)=>Y2(e)(t,r,n),c3=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return e3(e)(t,r,i)},u3=e=>async(t,r,n)=>e3(e)(t,r,n),l3=/^-?\d+$/,h3=/^-?\d+(?:\.\d+)?/,d3=b2("$ZodCheck",((e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])})),f3={number:"number",bigint:"bigint",object:"date"},p3=b2("$ZodCheckLessThan",((e,t)=>{d3.init(e,t);const r=f3[typeof t.value];e._zod.onattach.push((e=>{const r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)})),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),g3=b2("$ZodCheckGreaterThan",((e,t)=>{d3.init(e,t);const r=f3[typeof t.value];e._zod.onattach.push((e=>{const r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)})),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),m3=b2("$ZodCheckMultipleOf",((e,t)=>{d3.init(e,t),e._zod.onattach.push((e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)})),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===function(e,t){const r=(e.toString().split(".")[1]||"").length,n=t.toString();let i=(n.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(n)){const e=n.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}const s=r>i?r:i;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}})),y3=b2("$ZodCheckNumberFormat",((e,t)=>{d3.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=j2[t.format];e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=s,r&&(n.pattern=l3)})),e._zod.check=o=>{const a=o.value;if(r){if(!Number.isInteger(a))return void o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}))}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}})),b3=b2("$ZodCheckMaxLength",((e,t)=>{var r;d3.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!R2(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=r=>{const n=r.value;if(n.length<=t.maximum)return;const i=V2(n);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}})),w3=b2("$ZodCheckMinLength",((e,t)=>{var r;d3.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!R2(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const i=V2(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}})),v3=b2("$ZodCheckLengthEquals",((e,t)=>{var r;d3.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!R2(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length})),e._zod.check=r=>{const n=r.value,i=n.length;if(i===t.length)return;const s=V2(n),o=i>t.length;r.issues.push({origin:s,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}})),E3=b2("$ZodCheckOverwrite",((e,t)=>{d3.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}));class A3{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter((e=>e)),r=Math.min(...t.map((e=>e.length-e.trimStart().length))),n=t.map((e=>e.slice(r))).map((e=>" ".repeat(2*this.indent)+e));for(const e of n)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map((e=>` ${e}`))].join("\n"))}}const S3={major:4,minor:1,patch:13},k3=b2("$ZodType",((e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=S3;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push((()=>{e._zod.run=e._zod.parse}));else{const t=(e,t,r)=>{let n,i=q2(e);for(const s of t){if(s._zod.def.when){if(!s._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,o=s._zod.check(e);if(o instanceof Promise&&!1===r?.async)throw new w2;if(n||o instanceof Promise)n=(n??Promise.resolve()).then((async()=>{await o;e.issues.length!==t&&(i||(i=q2(e,t)))}));else{if(e.issues.length===t)continue;i||(i=q2(e,t))}}return n?n.then((()=>e)):e},r=(r,i,s)=>{if(q2(r))return r.aborted=!0,r;const o=t(i,n,s);if(o instanceof Promise){if(!1===s.async)throw new w2;return o.then((t=>e._zod.parse(t,s)))}return e._zod.parse(o,s)};e._zod.run=(i,s)=>{if(s.skipChecks)return e._zod.parse(i,s);if("backward"===s.direction){const t=e._zod.parse({value:i.value,issues:[]},{...s,skipChecks:!0});return t instanceof Promise?t.then((e=>r(e,i,s))):r(t,i,s)}const o=e._zod.parse(i,s);if(o instanceof Promise){if(!1===s.async)throw new w2;return o.then((e=>t(e,n,s)))}return t(o,n,s)}}e["~standard"]={validate:t=>{try{const r=X2(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return t3(e,t).then((e=>e.success?{value:e.data}:{issues:e.error?.issues}))}},vendor:"zod",version:1}})),R3=b2("$ZodNumber",((e,t)=>{k3.init(e,t),e._zod.pattern=e._zod.bag.pattern??h3,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;const s="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}})),C3=b2("$ZodNumberFormat",((e,t)=>{y3.init(e,t),R3.init(e,t)})),I3=b2("$ZodUnknown",((e,t)=>{k3.init(e,t),e._zod.parse=e=>e})),P3=b2("$ZodNever",((e,t)=>{k3.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}));function T3(e,t,r){e.issues.length&&t.issues.push(...z2(r,e.issues)),t.value[r]=e.value}const _3=b2("$ZodArray",((e,t)=>{k3.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const s=[];for(let e=0;e<i.length;e++){const o=i[e],a=t.element._zod.run({value:o,issues:[]},n);a instanceof Promise?s.push(a.then((t=>T3(t,r,e)))):T3(a,r,e)}return s.length?Promise.all(s).then((()=>r)):r}}));function N3(e,t,r,n){e.issues.length&&t.issues.push(...z2(r,e.issues)),void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function M3(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=(n=e.shape,Object.keys(n).filter((e=>"optional"===n[e]._zod.optin&&"optional"===n[e]._zod.optout)));var n;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function x3(e,t,r,n,i,s){const o=[],a=i.keySet,c=i.catchall._zod,u=c.def.type;for(const i in t){if(a.has(i))continue;if("never"===u){o.push(i);continue}const s=c.run({value:t[i],issues:[]},n);s instanceof Promise?e.push(s.then((e=>N3(e,r,i,t)))):N3(s,r,i,t)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s}),e.length?Promise.all(e).then((()=>r)):r}const O3=b2("$ZodObject",((e,t)=>{k3.init(e,t);const r=Object.getOwnPropertyDescriptor(t,"shape");if(!r?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}const n=k2((()=>M3(t)));P2(e._zod,"propValues",(()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r}));const i=x2,s=t.catchall;let o;e._zod.parse=(t,r)=>{o??(o=n.value);const a=t.value;if(!i(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],u=o.shape;for(const e of o.keys){const n=u[e]._zod.run({value:a[e],issues:[]},r);n instanceof Promise?c.push(n.then((r=>N3(r,t,e,a)))):N3(n,t,e,a)}return s?x3(c,a,t,r,n.value,e):c.length?Promise.all(c).then((()=>t)):t}})),D3=b2("$ZodObjectJIT",((e,t)=>{O3.init(e,t);const r=e._zod.parse,n=k2((()=>M3(t)));let i;const s=x2,o=!E2.jitless,a=o&&O2.value,c=t.catchall;let u;e._zod.parse=(l,h)=>{u??(u=n.value);const d=l.value;return s(d)?o&&a&&!1===h?.async&&!0!==h.jitless?(i||(i=(e=>{const t=new A3(["shape","payload","ctx"]),r=n.value,i=e=>{const t=N2(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const s=Object.create(null);let o=0;for(const e of r.keys)s[e]="key_"+o++;t.write("const newResult = {};");for(const e of r.keys){const r=s[e],n=N2(e);t.write(`const ${r} = ${i(e)};`),t.write(`\n if (${r}.issues.length) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${n}, ...iss.path] : [${n}]\n })));\n }\n \n \n if (${r}.value === undefined) {\n if (${n} in input) {\n newResult[${n}] = undefined;\n }\n } else {\n newResult[${n}] = ${r}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,r)=>a(e,t,r)})(t.shape)),l=i(l,h),c?x3([],d,l,h,u,e):l):r(l,h):(l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l)}}));function B3(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;const i=e.filter((e=>!q2(e)));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((e=>e.issues.map((e=>G2(e,n,A2())))))}),t)}const L3=b2("$ZodUnion",((e,t)=>{k3.init(e,t),P2(e._zod,"optin",(()=>t.options.some((e=>"optional"===e._zod.optin))?"optional":void 0)),P2(e._zod,"optout",(()=>t.options.some((e=>"optional"===e._zod.optout))?"optional":void 0)),P2(e._zod,"values",(()=>{if(t.options.every((e=>e._zod.values)))return new Set(t.options.flatMap((e=>Array.from(e._zod.values))))})),P2(e._zod,"pattern",(()=>{if(t.options.every((e=>e._zod.pattern))){const e=t.options.map((e=>e._zod.pattern));return new RegExp(`^(${e.map((e=>C2(e.source))).join("|")})$`)}}));const r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(i,s)=>{if(r)return n(i,s);let o=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},s);if(t instanceof Promise)a.push(t),o=!0;else{if(0===t.issues.length)return t;a.push(t)}}return o?Promise.all(a).then((t=>B3(t,i,e,s))):B3(a,i,e,s)}})),F3=b2("$ZodIntersection",((e,t)=>{k3.init(e,t),e._zod.parse=(e,r)=>{const n=e.value,i=t.left._zod.run({value:n,issues:[]},r),s=t.right._zod.run({value:n,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then((([t,r])=>j3(e,t,r))):j3(e,i,s)}}));function U3(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(D2(e)&&D2(t)){const r=Object.keys(t),n=Object.keys(e).filter((e=>-1!==r.indexOf(e))),i={...e,...t};for(const r of n){const n=U3(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};i[r]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const i=U3(e[n],t[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function j3(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),q2(e))return e;const n=U3(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const q3=b2("$ZodEnum",((e,t)=>{k3.init(e,t);const r=function(e){const t=Object.values(e).filter((e=>"number"==typeof e));return Object.entries(e).filter((([e,r])=>-1===t.indexOf(+e))).map((([e,t])=>t))}(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((e=>L2.has(typeof e))).map((e=>"string"==typeof e?e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e.toString())).join("|")})$`),e._zod.parse=(t,i)=>{const s=t.value;return n.has(s)||t.issues.push({code:"invalid_value",values:r,input:s,inst:e}),t}})),z3=b2("$ZodTransform",((e,t)=>{k3.init(e,t),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new v2(e.constructor.name);const i=t.transform(r.value,r);if(n.async){return(i instanceof Promise?i:Promise.resolve(i)).then((e=>(r.value=e,r)))}if(i instanceof Promise)throw new w2;return r.value=i,r}}));function K3(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const G3=b2("$ZodOptional",((e,t)=>{k3.init(e,t),e._zod.optin="optional",e._zod.optout="optional",P2(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0)),P2(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${C2(e.source)})?$`):void 0})),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then((t=>K3(t,e.value))):K3(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}})),V3=b2("$ZodNullable",((e,t)=>{k3.init(e,t),P2(e._zod,"optin",(()=>t.innerType._zod.optin)),P2(e._zod,"optout",(()=>t.innerType._zod.optout)),P2(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${C2(e.source)}|null)$`):void 0})),P2(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0)),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)})),H3=b2("$ZodDefault",((e,t)=>{k3.init(e,t),e._zod.optin="optional",P2(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);if(void 0===e.value)return e.value=t.defaultValue,e;const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then((e=>$3(e,t))):$3(n,t)}}));function $3(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const W3=b2("$ZodPrefault",((e,t)=>{k3.init(e,t),e._zod.optin="optional",P2(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,r)=>("backward"===r.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))})),J3=b2("$ZodNonOptional",((e,t)=>{k3.init(e,t),P2(e._zod,"values",(()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter((e=>void 0!==e))):void 0})),e._zod.parse=(r,n)=>{const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then((t=>Q3(t,e))):Q3(i,e)}}));function Q3(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Z3=b2("$ZodCatch",((e,t)=>{k3.init(e,t),P2(e._zod,"optin",(()=>t.innerType._zod.optin)),P2(e._zod,"optout",(()=>t.innerType._zod.optout)),P2(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then((n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map((e=>G2(e,r,A2())))},input:e.value}),e.issues=[]),e))):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map((e=>G2(e,r,A2())))},input:e.value}),e.issues=[]),e)}})),Y3=b2("$ZodPipe",((e,t)=>{k3.init(e,t),P2(e._zod,"values",(()=>t.in._zod.values)),P2(e._zod,"optin",(()=>t.in._zod.optin)),P2(e._zod,"optout",(()=>t.out._zod.optout)),P2(e._zod,"propValues",(()=>t.in._zod.propValues)),e._zod.parse=(e,r)=>{if("backward"===r.direction){const n=t.out._zod.run(e,r);return n instanceof Promise?n.then((e=>X3(e,t.in,r))):X3(n,t.in,r)}const n=t.in._zod.run(e,r);return n instanceof Promise?n.then((e=>X3(e,t.out,r))):X3(n,t.out,r)}}));function X3(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}const e6=b2("$ZodReadonly",((e,t)=>{k3.init(e,t),P2(e._zod,"propValues",(()=>t.innerType._zod.propValues)),P2(e._zod,"values",(()=>t.innerType._zod.values)),P2(e._zod,"optin",(()=>t.innerType?._zod?.optin)),P2(e._zod,"optout",(()=>t.innerType?._zod?.optout)),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t6):t6(n)}}));function t6(e){return e.value=Object.freeze(e.value),e}const r6=b2("$ZodCustom",((e,t)=>{d3.init(e,t),k3.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then((t=>n6(t,r,n,e)));n6(i,r,n,e)}}));function n6(e,t,r,n){if(!e){const e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(H2(e))}}var i6;class s6{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(i6=globalThis).__zod_globalRegistry??(i6.__zod_globalRegistry=new s6);const o6=globalThis.__zod_globalRegistry;function a6(e,t){return new p3({check:"less_than",...U2(t),value:e,inclusive:!1})}function c6(e,t){return new p3({check:"less_than",...U2(t),value:e,inclusive:!0})}function u6(e,t){return new g3({check:"greater_than",...U2(t),value:e,inclusive:!1})}function l6(e,t){return new g3({check:"greater_than",...U2(t),value:e,inclusive:!0})}function h6(e,t){return new m3({check:"multiple_of",...U2(t),value:e})}function d6(e,t){return new w3({check:"min_length",...U2(t),minimum:e})}function f6(e){const t=function(e,t){const r=new d3({check:"custom",...U2(t)});return r._zod.check=e,r}((r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(H2(e,r.value,t._zod.def));else{const n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(H2(n))}},e(r.value,r))));return t}const p6=b2("ZodError",((e,t)=>{W2.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const r={_errors:[]},n=e=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map((e=>n({issues:e})));else if("invalid_key"===i.code)n({issues:i.issues});else if("invalid_element"===i.code)n({issues:i.issues});else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){const r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(e),r}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const r={},n=[];for(const i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,S2,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,S2,2)}},isEmpty:{get:()=>0===e.issues.length}})}),{Parent:Error}),g6=Q2(p6),m6=Z2(p6),y6=Y2(p6),b6=e3(p6),w6=r3(p6),v6=n3(p6),E6=i3(p6),A6=s3(p6),S6=o3(p6),k6=a3(p6),R6=c3(p6),C6=u3(p6),I6=b2("ZodType",((e,t)=>(k3.init(e,t),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(_2(t,{checks:[...t.checks??[],...r.map((e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e))]})),e.clone=(t,r)=>F2(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>g6(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>y6(e,t,r),e.parseAsync=async(t,r)=>m6(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>b6(e,t,r),e.spa=e.safeParseAsync,e.encode=(t,r)=>w6(e,t,r),e.decode=(t,r)=>v6(e,t,r),e.encodeAsync=async(t,r)=>E6(e,t,r),e.decodeAsync=async(t,r)=>A6(e,t,r),e.safeEncode=(t,r)=>S6(e,t,r),e.safeDecode=(t,r)=>k6(e,t,r),e.safeEncodeAsync=async(t,r)=>R6(e,t,r),e.safeDecodeAsync=async(t,r)=>C6(e,t,r),e.refine=(t,r)=>e.check(function(e,t={}){return function(e,t,r){return new e({type:"custom",check:"custom",fn:t,...U2(r)})}(X6,e,t)}(t,r)),e.superRefine=t=>e.check(f6(t)),e.overwrite=t=>e.check(new E3({check:"overwrite",tx:t})),e.optional=()=>K6(e),e.nullable=()=>V6(e),e.nullish=()=>K6(V6(e)),e.nonoptional=t=>function(e,t){return new W6({type:"nonoptional",innerType:e,...U2(t)})}(e,t),e.array=()=>{return function(e,t,r){return new e({type:"array",element:t,...U2(r)})}(B6,e,t);var t},e.or=t=>{return new F6({type:"union",options:[e,t],...U2(r)});var r},e.and=t=>new U6({type:"intersection",left:e,right:t}),e.transform=t=>Z6(e,new q6({type:"transform",transform:t})),e.default=t=>{return r=t,new H6({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():B2(r)}});var r},e.prefault=t=>{return r=t,new $6({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():B2(r)}});var r},e.catch=t=>{return new J6({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>Z6(e,t),e.readonly=()=>new Y6({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return o6.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>o6.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return o6.get(e);const r=e.clone();return o6.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e))),P6=b2("ZodNumber",((e,t)=>{R3.init(e,t),I6.init(e,t),e.gt=(t,r)=>e.check(u6(t,r)),e.gte=(t,r)=>e.check(l6(t,r)),e.min=(t,r)=>e.check(l6(t,r)),e.lt=(t,r)=>e.check(a6(t,r)),e.lte=(t,r)=>e.check(c6(t,r)),e.max=(t,r)=>e.check(c6(t,r)),e.int=t=>e.check(N6(t)),e.safe=t=>e.check(N6(t)),e.positive=t=>e.check(u6(0,t)),e.nonnegative=t=>e.check(l6(0,t)),e.negative=t=>e.check(a6(0,t)),e.nonpositive=t=>e.check(c6(0,t)),e.multipleOf=(t,r)=>e.check(h6(t,r)),e.step=(t,r)=>e.check(h6(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null}));function T6(e){return function(e,t){return new e({type:"number",checks:[],...U2(t)})}(P6,e)}const _6=b2("ZodNumberFormat",((e,t)=>{C3.init(e,t),P6.init(e,t)}));function N6(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...U2(t)})}(_6,e)}const M6=b2("ZodUnknown",((e,t)=>{I3.init(e,t),I6.init(e,t)}));function x6(){return new M6({type:"unknown"})}const O6=b2("ZodNever",((e,t)=>{P3.init(e,t),I6.init(e,t)}));function D6(e){return function(e,t){return new e({type:"never",...U2(t)})}(O6,e)}const B6=b2("ZodArray",((e,t)=>{_3.init(e,t),I6.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(d6(t,r)),e.nonempty=t=>e.check(d6(1,t)),e.max=(t,r)=>e.check(function(e,t){return new b3({check:"max_length",...U2(t),maximum:e})}(t,r)),e.length=(t,r)=>e.check(function(e,t){return new v3({check:"length_equals",...U2(t),length:e})}(t,r)),e.unwrap=()=>e.element}));const L6=b2("ZodObject",((e,t)=>{D3.init(e,t),I6.init(e,t),P2(e,"shape",(()=>t.shape)),e.keyof=()=>function(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map((e=>[e,e]))):e;return new j6({type:"enum",entries:r,...U2(t)})}(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:x6()}),e.loose=()=>e.clone({...e._zod.def,catchall:x6()}),e.strict=()=>e.clone({...e._zod.def,catchall:D6()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!D2(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const n=_2(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return T2(this,"shape",r),r},checks:[]});return F2(e,n)}(e,t),e.safeExtend=t=>function(e,t){if(!D2(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return T2(this,"shape",r),r},checks:e._zod.def.checks};return F2(e,r)}(e,t),e.merge=t=>function(e,t){const r=_2(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return T2(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return F2(e,r)}(e,t),e.pick=t=>function(e,t){const r=e._zod.def,n=_2(e._zod.def,{get shape(){const e={};for(const n in t){if(!(n in r.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(e[n]=r.shape[n])}return T2(this,"shape",e),e},checks:[]});return F2(e,n)}(e,t),e.omit=t=>function(e,t){const r=e._zod.def,n=_2(e._zod.def,{get shape(){const n={...e._zod.def.shape};for(const e in t){if(!(e in r.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return T2(this,"shape",n),n},checks:[]});return F2(e,n)}(e,t),e.partial=(...t)=>function(e,t,r){const n=_2(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(const t in n)i[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return T2(this,"shape",i),i},checks:[]});return F2(t,n)}(z6,e,t[0]),e.required=(...t)=>function(e,t,r){const n=_2(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(const t in n)i[t]=new e({type:"nonoptional",innerType:n[t]});return T2(this,"shape",i),i},checks:[]});return F2(t,n)}(W6,e,t[0])}));const F6=b2("ZodUnion",((e,t)=>{L3.init(e,t),I6.init(e,t),e.options=t.options}));const U6=b2("ZodIntersection",((e,t)=>{F3.init(e,t),I6.init(e,t)}));const j6=b2("ZodEnum",((e,t)=>{q3.init(e,t),I6.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{const i={};for(const n of e){if(!r.has(n))throw new Error(`Key ${n} not found in enum`);i[n]=t.entries[n]}return new j6({...t,checks:[],...U2(n),entries:i})},e.exclude=(e,n)=>{const i={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new j6({...t,checks:[],...U2(n),entries:i})}}));const q6=b2("ZodTransform",((e,t)=>{z3.init(e,t),I6.init(e,t),e._zod.parse=(r,n)=>{if("backward"===n.direction)throw new v2(e.constructor.name);r.addIssue=n=>{if("string"==typeof n)r.issues.push(H2(n,r.value,t));else{const t=n;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),r.issues.push(H2(t))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then((e=>(r.value=e,r))):(r.value=i,r)}}));const z6=b2("ZodOptional",((e,t)=>{G3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function K6(e){return new z6({type:"optional",innerType:e})}const G6=b2("ZodNullable",((e,t)=>{V3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function V6(e){return new G6({type:"nullable",innerType:e})}const H6=b2("ZodDefault",((e,t)=>{H3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}));const $6=b2("ZodPrefault",((e,t)=>{W3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const W6=b2("ZodNonOptional",((e,t)=>{J3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const J6=b2("ZodCatch",((e,t)=>{Z3.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}));const Q6=b2("ZodPipe",((e,t)=>{Y3.init(e,t),I6.init(e,t),e.in=t.in,e.out=t.out}));function Z6(e,t){return new Q6({type:"pipe",in:e,out:t})}const Y6=b2("ZodReadonly",((e,t)=>{e6.init(e,t),I6.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const X6=b2("ZodCustom",((e,t)=>{r6.init(e,t),I6.init(e,t)}));class e4 extends Error{reasonText;constructor(e){super(`Failed to parse metadata: ${e}`),this.reasonText=e}}const t4=new Bv("Operator");class r4{contractAddress;contract;contractReadonly;contractFactory;rpcProviderSource;theGraphClient;identity;getEthersOverrides;eventEmitter=new sE;constructor(e,t,r,n,i,s,o,a,c){this.contractAddress=e,this.contractFactory=t,this.rpcProviderSource=r,this.contractReadonly=t.createReadContract(nb(e),SA.OperatorABI,r.getProvider(),"operator"),this.theGraphClient=i,this.identity=s,this.getEthersOverrides=c,this.initEventGateways(e,n,a),o.onDestroy.listen((()=>{this.eventEmitter.removeAllListeners()}))}initEventGateways(e,t,r){const n=new uN(SA.OperatorABI),i=([e])=>({sponsorship:nb(e)});wD({sourceDefinition:{contractInterfaceFragment:n.getEvent("Staked"),contractAddress:e},sourceEmitter:t,targetName:"staked",targetEmitter:this.eventEmitter,transformation:i,loggerFactory:r}),wD({sourceDefinition:{contractInterfaceFragment:n.getEvent("Unstaked"),contractAddress:e},sourceEmitter:t,targetName:"unstaked",targetEmitter:this.eventEmitter,transformation:i,loggerFactory:r});wD({sourceDefinition:{contractInterfaceFragment:n.getEvent("ReviewRequest"),contractAddress:e},sourceEmitter:t,targetName:"reviewRequested",targetEmitter:this.eventEmitter,transformation:([e,t,r,n,i])=>{const s=function(e){if(void 0===e)throw new e4("no metadata");let t;try{t=JSON.parse(e)}catch{throw new e4("malformed metadata")}const r=Number(t.partition);if(isNaN(r))throw new e4('invalid or missing "partition" field');try{vE(r)}catch{throw new e4("invalid partition numbering")}return r}(i);return{sponsorship:nb(e),targetOperator:nb(t),partition:s,votingPeriodStartTimestamp:1e3*Number(r),votingPeriodEndTimestamp:1e3*Number(n)}},loggerFactory:r})}async writeHeartbeat(e){const t=JSON.stringify(e);await this.connectToContract(),await(await this.contract.heartbeat(t,await this.getEthersOverrides())).wait()}async getTimestampOfLastHeartbeat(){const e=await this.theGraphClient.queryEntity({query:`{\n operator(id: "${await this.getContractAddress()}") {\n latestHeartbeatTimestamp\n }\n }`});if(null!==e.operator&&null!==e.operator.latestHeartbeatTimestamp){const t=parseInt(e.operator.latestHeartbeatTimestamp);if(isNaN(t))throw new Error("Assertion failed: unexpected non-integer latestHeartbeatTimestamp");return 1e3*t}}async getContractAddress(){return nb(await this.contractReadonly.getAddress())}async getSponsorships(){const e=await this.getContractAddress(),t=this.theGraphClient.queryEntities(((t,r)=>({query:`\n {\n operator(id: "${e}") {\n stakes(where: {id_gt: "${t}"}, first: ${r}) {\n id\n sponsorship {\n id\n operatorCount\n stream {\n id\n }\n }\n }\n }\n }\n `})),(e=>e.operator?.stakes??[])),r=[];for await(const e of t)r.push({sponsorshipAddress:nb(e.sponsorship.id),streamId:bE(e.sponsorship.stream.id),operatorCount:e.sponsorship.operatorCount});return r}async getExpiredFlags(e,t){const r=Math.floor((Date.now()-t)/1e3),n=this.theGraphClient.queryEntities(((t,n)=>({query:`\n {\n flags (where : {\n id_gt: "${t}",\n voteEndTimestamp_lt: ${r},\n result_in: ["waiting", "voting"],\n sponsorship_in: ${JSON.stringify(e)}\n }, first: ${n}) {\n id\n flaggingTimestamp\n target {\n id\n }\n sponsorship {\n id\n }\n }\n }`}))),i=[];for await(const e of n)i.push({id:e.id,flaggingTimestamp:e.flaggingTimestamp,targetOperator:nb(e.target.id),sponsorship:nb(e.sponsorship.id)});return i}async getOperatorsInSponsorship(e){const t=this.theGraphClient.queryEntities(((t,r)=>({query:`\n {\n sponsorship(id: "${e}") {\n stakes(where: {id_gt: "${t}"}, first: ${r}) {\n id\n operator {\n id\n }\n }\n }\n }\n `})),(e=>e.sponsorship?.stakes??[])),r=[];for await(const e of t)r.push(nb(e.operator.id));return r}async flag(e,t,r){const n=JSON.stringify({partition:r});await this.connectToContract(),await(await this.contract.flag(e,t,n,await this.getEthersOverrides())).wait()}async getEarnings(e,t){const{addresses:r,earnings:n,maxAllowedEarnings:i}=await this.contractReadonly.getSponsorshipsAndEarnings(),s=r.map(((e,t)=>({address:e,earnings:n[t]}))).filter((t=>t.earnings>=e)).sort(((e,t)=>((e,t)=>e<t?-1:e>t?1:0)(e.earnings,t.earnings))).slice(0,t);return{sponsorshipAddresses:s.map((e=>nb(e.address))),sum:s.reduce(((e,t)=>e+t.earnings),0n),maxAllowedEarnings:i}}async withdrawEarningsFromSponsorships(e){await this.connectToContract(),await(await this.contract.withdrawEarningsFromSponsorships(e,await this.getEthersOverrides())).wait()}async triggerAnotherOperatorWithdraw(e,t){await this.connectToContract(),await(await this.contract.triggerAnotherOperatorWithdraw(e,t,await this.getEthersOverrides())).wait()}async getStakedOperators(){const e=this.theGraphClient.queryEntities(((e,t)=>({query:`\n {\n operators(where: {totalStakeInSponsorshipsWei_gt: "0", id_gt: "${e}"}, first: ${t}) {\n id\n }\n }\n `}))),t=[];for await(const r of e)t.push(nb(r.id));return t}async*pullStakedStreams(e){const t=await this.getContractAddress();this.theGraphClient.updateRequiredBlockNumber(e);const r=this.theGraphClient.queryEntities(((e,r)=>({query:`\n {\n operator(id: "${t}") {\n stakes(where: {id_gt: "${e}"}, first: ${r}) {\n sponsorship {\n id\n stream {\n id\n }\n }\n }\n }\n _meta {\n block {\n number\n }\n }\n }\n `})),(e=>e.operator?e.operator.stakes:(t4.error("Unable to find operator in The Graph",{operatorContractAddress:t}),[])));for await(const e of r)yield{sponsorship:nb(e.sponsorship.id),streamId:bE(e.sponsorship.stream.id)}}async hasOpenFlag(e){const t=await this.getContractAddress(),r=this.theGraphClient.queryEntities((()=>({query:`\n {\n flags(where: {\n sponsorship: "${e}",\n target: "${t}",\n result_in: ["waiting", "voting"]\n }) {\n id\n }\n }\n `}))),n=await cE(r,1);return n.length>0&&(t4.debug("Found open flag",{flag:n[0]}),!0)}async getStreamId(e){const t=this.contractFactory.createReadContract(nb(e),SA.SponsorshipABI,this.rpcProviderSource.getProvider(),"sponsorship");return bE(await t.streamId())}async voteOnFlag(e,t,r){const n=r?"0x0000000000000000000000000000000000000000000000000000000000000001":"0x0000000000000000000000000000000000000000000000000000000000000000";await this.connectToContract();const i=1300000n,s=await this.contract.voteOnFlag.estimateGas(e,t,n);if(s>i)throw new Error(`Gas estimate (${s}) exceeds limit (1300000)`);await(await this.contract.voteOnFlag(e,t,n,{...await this.getEthersOverrides(),gasLimit:i})).wait()}async closeFlag(e,t){await this.voteOnFlag(e,t,!1)}async fetchRedundancyFactor(){const e=function(e,t){const r={type:"object",shape:e??{},...U2(t)};return new L6(r)}({redundancyFactor:T6().int().gte(1)}),t=await this.contractReadonly.metadata();if(0===t.length)return 1;let r,n;try{r=JSON.parse(t)}catch{return void t4.warn("Encountered malformed metadata",{operatorAddress:await this.getContractAddress(),metadataAsString:t})}try{n=e.parse(r)}catch(e){return void t4.warn("Encountered invalid metadata",{operatorAddress:await this.getContractAddress(),metadataAsString:t,reason:e?.reason})}return n.redundancyFactor}getCurrentBlockNumber(){return this.rpcProviderSource.getProvider().getBlockNumber()}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}async connectToContract(){if(void 0===this.contract){const e=await this.identity.getTransactionSigner(this.rpcProviderSource);this.contract=this.contractFactory.createWriteContract(this.contractAddress,SA.OperatorABI,e,"operator")}}}var n4=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},i4=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s4=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};let o4=class{config;constructor(e,t,r,n){this.config=t,this.initEventListener(r,e,n)}initEventListener(e,t,r){const n=nb(this.config.contracts.sponsorshipFactoryChainAddress),i=new uN(SA.SponsorshipFactoryABI);wD({sourceDefinition:{contractInterfaceFragment:i.getEvent("NewSponsorship"),contractAddress:n},sourceEmitter:t,targetName:"sponsorshipCreated",targetEmitter:e,transformation:([e,t],r)=>({sponsorshipContractAddress:nb(e),streamId:bE(t),blockNumber:r}),loggerFactory:r})}};o4=n4([q(d.ContainerScoped),s4(1,U(cA)),i4("design:paramtypes",[cQ,Object,sD,uD])],o4);var a4,c4=window&&window.__decorate||function(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o},u4=window&&window.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},l4=window&&window.__param||function(e,t){return function(r,n){t(r,n,e)}};!function(e){e[e.NONE=0]="NONE",e[e.NORMAL=1]="NORMAL",e[e.ERC_1271=2]="ERC_1271"}(a4||(a4={}));let h4=class{networkNodeFacade;streamRegistry;signatureValidator;messageSigner;store;identity;logger;erc1271Publishers=new Set;config;constructor(t,r,n,i,s,o,a,c,u){this.networkNodeFacade=t,this.streamRegistry=r,this.signatureValidator=n,this.messageSigner=i,this.store=s,this.identity=o,this.logger=u.createLogger("PublisherKeyExchange"),this.config=a,void 0===a.encryption.keys&&(t.once("start",(async()=>{t.addMessageListener((e=>this.onMessage(e))),this.logger.debug("Started")})),c.on("messagePublished",(t=>{if(t.signatureType===e.SignatureType.ERC_1271){const e=t.getPublisherId();this.erc1271Publishers.has(e)||(this.logger.debug("Add ERC-1271 publisher",{publisherId:e}),this.erc1271Publishers.add(e))}})))}async onMessage(t){if(t.messageType===e.StreamMessageType.GROUP_KEY_REQUEST)try{const{recipientId:e,requestId:r,publicKey:n,groupKeyIds:i,encryptionType:s}=DH.fromBinary(t.content),o=kE(e);if(!function(e,t){const r=R0.has(e),n=t.encryption?.requireQuantumResistantKeyExchange;return r||!n}(s,this.config))throw new uA(`EncryptionType in key request (${s}) is not compliant with encryption settings!`,"ENCRYPTION_POLICY_VIOLATION",t);const a=await this.getResponseType(o);if(a!==a4.NONE){this.logger.debug("Handling group key request",{requestId:r,responseType:a,keyEncryptionType:PH[s]}),await y0(t,this.streamRegistry,this.signatureValidator,this.config);const e=await this.identity.getUserId(),c=ju(await Promise.all(i.map((t=>this.store.get(t,e)))),void 0);if(c.length>0){const e=await this.createResponse(c,a,o,t.getStreamPartID(),n,t.getPublisherId(),r,s);await this.networkNodeFacade.broadcast(e),this.logger.debug("Handled group key request (found keys)",{groupKeyIds:c.map((e=>e.id)).join(),recipient:t.getPublisherId()})}else this.logger.debug("Handled group key request (no keys found)",{requestId:r,recipient:t.getPublisherId()})}}catch(e){this.logger.debug("Failed to handle group key request",e)}}async getResponseType(e){return e===await this.identity.getUserId()?a4.NORMAL:this.erc1271Publishers.has(e)?a4.ERC_1271:a4.NONE}async createResponse(t,r,n,i,s,o,a,c){const u=await Promise.all(t.map((async e=>({id:e.id,data:await YQ.encryptForPublicKey(e.data,s,c)})))),l={recipientId:RE(o),requestId:a,groupKeys:u,encryptionType:c};return this.messageSigner.createSignedMessage({messageId:new CW(AE.getStreamID(i),AE.getStreamPartition(i),Date.now(),0,n,VX()),content:BH.toBinary(l),contentType:e.ContentType.BINARY,messageType:e.StreamMessageType.GROUP_KEY_RESPONSE,encryptionType:e.EncryptionType.NONE},r===a4.NORMAL?this.identity.getSignatureType():e.SignatureType.ERC_1271)}};h4=c4([q(d.ContainerScoped),l4(5,U(kA)),l4(6,U(cA)),u4("design:paramtypes",[GX,EQ,m0,e.MessageSigner,OZ,RA,Object,sD,uD])],h4);class d4{pipeline;onFinally;onBeforeFinally;onError;constructor(e){this.pipeline=e??new uJ,this.onFinally=this.pipeline.onFinally,this.onBeforeFinally=this.pipeline.onBeforeFinally,this.onError=this.pipeline.onError}useLegacyOnMessageHandler(e){return this.pipeline.onMessage.listen((async t=>{const r=Q1(t);await e(r.content,BY(r,"content"))})),this.pipeline.flow(),this}async*[Symbol.asyncIterator](){for await(const e of this.pipeline)yield Q1(e)}async push(e){await this.pipeline.push(e)}pipe(e){return this.pipeline.pipe(e)}async handleError(e){await this.pipeline.handleError(e)}end(e){this.pipeline.end(e)}isDone(){return this.pipeline.isDone()}return(){return this.pipeline.return()}}class f4 extends d4{streamPartId;isRaw;erc1271ContractAddress;deliveryOptions;eventEmitter;logger;constructor(e,t,r,n,i,s){super(),this.streamPartId=e,this.isRaw=t,this.erc1271ContractAddress=r,this.deliveryOptions=n,this.eventEmitter=i,this.logger=s.createLogger("Subscription"),this.onError.listen((e=>{this.eventEmitter.emit("error",e),this.logger.debug("Encountered error",{err:e})}))}async unsubscribe(){this.end(),await this.return(),this.eventEmitter.removeAllListeners()}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.off(e,t)}}const p4=new Bv("waitForStorage");const g4=async(e,t,r,n,i,s,o,a,c)=>{if(r.wait){if(await o.isStoredStream(e,t))return;let u;try{const s=EE(HW(t),0);u=new f4(s,!1,void 0,void 0,new Sl,a),await i.add(u);const l=async function(e,t,r){const n=new Set;for await(const i of e){const e=i.content.streamPart;try{const r=AE.parse(e),[i,s]=AE.getStreamIDAndPartition(r);if(i===t.id&&s<t.partitions&&(n.add(s),n.size===t.partitions))return}catch{r.createLogger("waitForAssignmentsToPropagate").debug("Ignore malformed content")}}}(u,{id:e,partitions:n},a);await o.addStreamToStorageNode(e,t),await Xv(l,r.timeout??c._timeouts.storageNode.timeout,"storage node did not respond")}finally{s.invalidatePermissionCaches(e),await(u?.unsubscribe())}}else await o.addStreamToStorageNode(e,t)},m4=new Bv("StreamrClient");const y4=function(e,t){DA("string"==typeof e,"value must be a string","value",e);let r=18;return r=cS(t,"unit"),HS.fromString(e,{decimals:r,width:512}).value}("1",18);const b4=new Bv("operatorContractUtils");const w4=async(e,t,r,n,i)=>{const s=A4(n),o=await s.connect(e).transferAndCall(t,r,"0x");await o.wait(void 0,i)},v4=e=>new JN(e,SA.OperatorABI),E4=e=>new JN(e,SA.SponsorshipABI),A4=e=>new JN(e,SA.DATAv2ABI),S4={delegate:async(e,t,r,n)=>{b4.debug("Delegate",{amount:r.toString()});const i=await v4(t).connect(e.provider).token();await w4(e,t,r,i,n)},undelegate:async(e,t,r,n)=>{b4.debug("Undelegate",{amount:r.toString()}),await(await v4(t).connect(e).undelegate(r)).wait(void 0,n)},deploySponsorshipContract:async function(e){b4.debug("Deploying SponsorshipContract");const t=[{contractAddress:ZO.config[e.environmentId].contracts.SponsorshipStakeWeightedAllocationPolicy,param:e.earningsPerSecond},{contractAddress:ZO.config[e.environmentId].contracts.SponsorshipDefaultLeavePolicy,param:e.minStakeDuration??0},{contractAddress:ZO.config[e.environmentId].contracts.SponsorshipVoteKickPolicy,param:0}];void 0!==e.maxOperatorCount&&t.push({contractAddress:ZO.config[e.environmentId].contracts.SponsorshipMaxOperatorsJoinPolicy,param:e.maxOperatorCount});const r=rN.defaultAbiCoder().encode(["uint32","string","string","address[]","uint[]"],[(e.minOperatorCount??1).toString(),e.streamId,e.metadata??"{}",t.map((e=>e.contractAddress)),t.map((e=>e.param))]),n=await A4(ZO.config[e.environmentId].contracts.DATA).connect(e.deployer).transferAndCall(ZO.config[e.environmentId].contracts.SponsorshipFactory,e.sponsorAmount??0n,r),i=await n.wait(void 0,e.transactionTimeout),s=new uN(SA.SponsorshipFactoryABI),o=i.logs.map((e=>s.parseLog(e))).find((e=>"NewSponsorship"===e?.name)).args.sponsorshipContract;return b4.debug("Deployed SponsorshipContract",{address:o}),new JN(o,SA.SponsorshipABI,e.deployer)},sponsor:async(e,t,r,n)=>{b4.debug("Sponsor",{amount:r.toString()});const i=await E4(t).connect(e.provider).token();await w4(e,t,r,i,n)},stake:async(e,t,r,n,i={},s=()=>{},o)=>{b4.debug("Stake",{amount:rk(n),sponsorshipContractAddress:r});const a=v4(t).connect(e),c=await a.stake(r,n,i);b4.debug("Stake: transaction submitted",{tx:c.hash,nonce:c.nonce}),s(c),b4.debug("Stake: waiting for transaction to be mined",{tx:c.hash,timeout:o});try{const e=await c.wait(void 0,o);return b4.debug("Stake: confirmation received",{receipt:e?.hash}),e}catch(e){throw b4.error("Stake: error waiting for tx to be mined",{tx:c.hash,error:e}),e}},unstake:async(e,t,r,n,i={},s=()=>{},o)=>{b4.debug("Unstake",{amount:rk(n),sponsorshipContractAddress:r});const a=v4(t).connect(e),c=E4(r).connect(e),u=await c.stakedWei(t)-n,l=await a.reduceStakeTo(r,u,i);b4.debug("Unstake: transaction submitted",{tx:l.hash,nonce:l.nonce}),s(l),b4.debug("Unstake: waiting for transaction to be mined",{tx:l.hash,timeout:o});try{const e=await l.wait(void 0,o);return b4.debug("Unstake: confirmation received",{receipt:e?.hash}),e}catch(e){throw b4.error("Unstake: error waiting for tx to be mined",{tx:l.hash,error:e}),e}},deployOperatorContract:async function(e){b4.debug("Deploying OperatorContract");const t=new JN(ZO.config[e.environmentId].contracts.OperatorFactory,SA.OperatorFactoryABI,e.deployer);if(await t.operators(await e.deployer.getAddress())!==CI)throw new Error("Operator already has a contract");var r,n;const i=(await(await t.deployOperator((r=y4,n=(e.operatorsCutPercentage??0)/100,r*BigInt(IE*n)/BigInt(IE)),e.operatorTokenName??`OperatorToken-${Date.now()}`,e.metadata??"",[ZO.config[e.environmentId].contracts.OperatorDefaultDelegationPolicy,ZO.config[e.environmentId].contracts.OperatorDefaultExchangeRatePolicy,ZO.config[e.environmentId].contracts.OperatorDefaultUndelegationPolicy],[0,0,0])).wait(void 0,e.transactionTimeout)).logs.find((e=>"NewOperator"===e.fragment?.name)).args.operatorContractAddress,s=new JN(i,SA.OperatorABI,e.deployer);return b4.debug("Deployed OperatorContract",{address:i}),s},getOperatorContract:v4};e.ConfigInjectionToken=cA,e.DEFAULT_ENVIRONMENT_ID=aA,e.DEFAULT_KEY_TYPE=h0,e.ECDSAKeyPairIdentity=u0,e.ENVIRONMENT_IDS=["polygon","polygonAmoy","peaq","iotex","dev2"],e.EncryptedGroupKey=LH,e.EncryptionKey=eZ,e.EthereumKeyPairIdentity=i0,e.EthereumProviderIdentity=s0,e.Identity=RA,e.KeyPairIdentity=r0,e.MLDSAKeyPairIdentity=a0,e.MessageID=CW,e.MessageRef=RW,e.Operator=r4,e.STREAMR_STORAGE_NODE_ADDRESS="0x9dc08ff97f5c156181ec6a0b13fc3946454e529a",e.STREAMR_STORAGE_NODE_GERMANY="0x31546eEA76F2B2b3C5cC06B1c93601dc35c9D916",e.Stream=y2,e.StreamMessage=PW,e.StreamrClient=class{id;publisher;subscriber;resends;node;rpcProviderSource;streamRegistry;streamStorageRegistry;storageNodeRegistry;operatorRegistry;contractFactory;localGroupKeyStore;chainEventPoller;theGraphClient;streamIdBuilder;config;identity;eventEmitter;destroySignal;loggerFactory;proxyNodeFinder;constructor(t={},r=F){const n=V1(t),i=function(e){if(void 0!==e.auth?.privateKey){const t=e.auth.keyType??h0,r=l0.find((e=>e.keyType===t));if(r)return r.fromConfig(e);throw new Error(`Unsupported keyType given in config: ${t}`)}return void 0!==e.auth?.identity?e.auth?.identity:void 0!==e.auth?.ethereum?s0.fromConfig(e):i0.generate()}(n);!function(e,t){const r=P0(e),n=t.encryption?.requireQuantumResistantSignatures;if(n&&!r)throw new uA("Quantum resistant signatures are required, but the configured key type doesn't enable quantum resistance!","SIGNATURE_POLICY_VIOLATION")}(i,n),(e=>{void 0!==e.auth?.privateKey&&(e.auth.privateKey="(redacted)")})(n);const s=r.createChildContainer();s.register(kA,{useValue:i}),s.register(cA,{useValue:n});const o=((e,t)=>{const r=new lE({serverUrl:t.contracts.theGraphUrl,fetch:(e,r)=>{const n=t._timeouts.theGraph.fetchTimeout,i=[AbortSignal.timeout(n)];r?.signal instanceof AbortSignal&&i.push(r.signal);const s=rE(...i);try{return fetch(e,aE(r,{signal:s}))}finally{s.destroy()}},indexTimeout:t._timeouts.theGraph.indexTimeout,indexPollInterval:t._timeouts.theGraph.indexPollInterval});return e.on("contractTransactionConfirmed",(e=>{null!=e.receipt&&r.updateRequiredBlockNumber(e.receipt.blockNumber)})),r})(s.resolve(sD),n);s.register(lE,{useValue:o}),this.id=n.id,this.config=n,this.identity=i,this.theGraphClient=o,this.publisher=s.resolve(B1),this.subscriber=s.resolve(T0.Subscriber),this.resends=s.resolve(T0.Resends),this.node=s.resolve(GX),this.rpcProviderSource=s.resolve(e.RpcProviderSource),this.streamRegistry=s.resolve(EQ),this.streamStorageRegistry=s.resolve(OQ),this.storageNodeRegistry=s.resolve(ID),this.operatorRegistry=s.resolve(UY),this.contractFactory=s.resolve(SD),this.localGroupKeyStore=s.resolve(OZ),this.chainEventPoller=s.resolve(cQ),this.streamIdBuilder=s.resolve(RJ),this.eventEmitter=s.resolve(sD),this.destroySignal=s.resolve(dJ),this.loggerFactory=s.resolve(uD),this.proxyNodeFinder=s.resolve(i2),s.resolve(h4),s.resolve(t2),s.resolve(o4)}async publish(e,t,r,n){const i=await this.publisher.publish(e,t,r,n);return this.eventEmitter.emit("messagePublished",i),Q1(i)}async publishRaw(e,t){await this.node.broadcast(e,t),this.eventEmitter.emit("messagePublished",e)}async updateEncryptionKey(e){if(void 0===e.streamId)throw new Error("streamId required");const t=await this.streamIdBuilder.toStreamID(e.streamId),r=await this.publisher.getGroupKeyQueue(t);if("rotate"===e.distributionMethod)await r.rotate(e.key);else{if("rekey"!==e.distributionMethod)throw new Error(`assertion failed: distribution method ${e.distributionMethod}`);await r.rekey(e.key)}}async addEncryptionKey(e,t){await this.localGroupKeyStore.set(e.id,kE(t),e.data)}async subscribe(e,t){if(!0===e.raw&&void 0!==e.resend)throw new Error("Raw subscriptions are not supported for resend");const r=await this.streamIdBuilder.toStreamPartID(e),n=new Sl,i=new f4(r,e.raw??!1,void 0!==e.erc1271Contract?nb(e.erc1271Contract):void 0,e.delivery??{},n,this.loggerFactory);return void 0!==e.resend&&((e,t,r,n,i,s,o)=>{if(e.pipe((async function*(i){try{const i=await r.resend(e.streamPartId,n1(t),n);e.onBeforeFinally.listen((async()=>{i.end(),await i.return()})),yield*i}catch(r){"NO_STORAGE_NODES"===r.code?o.createLogger("resendSubscription").warn("Skip resend (no storage assigned to stream)",{streamPartId:e.streamPartId,resendOptions:t}):await e.handleError(r)}s.emit("resendCompleted"),yield*i})),i.orderMessages){const t=new $0(e.streamPartId,n,(()=>{}),r,i);e.pipe((async function*(e){setImmediate((()=>{t.addMessages(e)})),yield*t})),e.onBeforeFinally.listen((()=>t.destroy()))}})(i,e.resend,this.resends,(e=>this.streamStorageRegistry.getStorageNodes(e)),this.config,n,this.loggerFactory),await this.subscriber.add(i),void 0!==t&&i.useLegacyOnMessageHandler(t),this.eventEmitter.emit("streamPartSubscribed",void 0),i}async unsubscribe(e){if(e instanceof f4){const t=e;return this.subscriber.remove(t)}{const t=await this.getSubscriptions(e);return Promise.allSettled(t.map((e=>this.subscriber.remove(e))))}}async getSubscriptions(e){const t=void 0!==e?await this.streamIdBuilder.getMatcher(e):()=>!0;return this.subscriber.getSubscriptions().filter((e=>t(e.streamPartId)))}async resend(e,t,r){const n=await this.streamIdBuilder.toStreamPartID(e),i=await this.resends.resend(n,n1(t),(e=>this.streamStorageRegistry.getStorageNodes(e))),s=new d4(i);return void 0!==r&&s.useLegacyOnMessageHandler(r),s}waitForStorage(e,t){const r={interval:this.config._timeouts.storageNode.retryInterval,timeout:this.config._timeouts.storageNode.timeout,count:100};return(async(e,t,r,n)=>{if(!e)throw new uA("waitForStorage requires a Message","INVALID_ARGUMENT");const i=t.messageMatchFn??((e,t)=>yw(e.signature,t.signature)),s=Date.now();let o,a=!1;for(;!a;){const c=Date.now()-s;if(c>t.timeout)throw p4.debug("Timed out waiting for storage to contain message",{expected:e.streamMessage.messageId,lastReceived:o?.map((e=>e.messageId))}),new Error(`timed out after ${c}ms waiting for message`);const u=e=>n.getStorageNodes(e),l=await r.resend(EE(e.streamId,e.streamPartition),{last:t.count},u);o=await cE(l);for(const t of o)if(i(e,Q1(t)))return a=!0,void p4.debug("Found matching message");p4.debug("Retry after delay (matching message not found)",{expected:e.streamMessage.messageId,"last-3":o.slice(-3).map((e=>e.messageId)),delayInMs:t.interval}),await Qv(t.interval)}})(e,P1(r,t),this.resends,this.streamStorageRegistry)}async getStream(e){const t=await this.streamIdBuilder.toStreamID(e);return await this.streamRegistry.getStreamMetadata(t),new y2(t,this)}async createStream(e){const t="object"==typeof e?e:{id:e},r=await this.streamIdBuilder.toStreamID(t.id),n=P1({partitions:1},BY(t,"id"));return await this.streamRegistry.createStream(r,n),new y2(r,this)}async getOrCreateStream(e){try{return await this.getStream(e.id)}catch(t){if("STREAM_NOT_FOUND"===t.code)return this.createStream(e);throw t}}async getStreamMetadata(e){const t=await this.streamIdBuilder.toStreamID(e);return this.streamRegistry.getStreamMetadata(t)}async setStreamMetadata(e,t){const r=await this.streamIdBuilder.toStreamID(e);await this.streamRegistry.setStreamMetadata(r,t)}deleteStream(e){return this.streamRegistry.deleteStream(e)}searchStreams(e,t){if(m4.debug("Search for streams",{term:e,permissionFilter:t}),void 0===e&&void 0===t)throw new Error("Requires a search term or a permission filter");const r=this.streamRegistry.searchStreams(e,void 0!==t?(e=>({...e,userId:kE(e.userId)}))(t):void 0);return MW(r,(e=>new y2(e,this)))}getStreamPublishers(e){return this.streamRegistry.getStreamPublishers(e)}getStreamSubscribers(e){return this.streamRegistry.getStreamSubscribers(e)}async hasPermission(e){return this.streamRegistry.hasPermission(await(async(e,t)=>{const r={...e,streamId:await t.toStreamID(e.streamId)};return"userId"in r?{...r,userId:kE(r.userId)}:r})(e,this.streamIdBuilder))}getPermissions(e){return this.streamRegistry.getPermissions(e)}grantPermissions(e,...t){return this.streamRegistry.grantPermissions(e,...t.map(NJ))}revokePermissions(e,...t){return this.streamRegistry.revokePermissions(e,...t.map(NJ))}setPermissions(...e){return this.streamRegistry.setPermissions(...e.map((e=>({...e,assignments:e.assignments.map(NJ)}))))}async isStreamPublisher(e,t){const r=await this.streamIdBuilder.toStreamID(e);return this.streamRegistry.isStreamPublisher(r,kE(t))}async isStreamSubscriber(e,t){const r=await this.streamIdBuilder.toStreamID(e);return this.streamRegistry.isStreamSubscriber(r,kE(t))}async addStreamToStorageNode(e,t,r={wait:!1}){const n=await this.streamIdBuilder.toStreamID(e);await g4(n,nb(t),r,IJ(await this.streamRegistry.getStreamMetadata(n)),this.subscriber,this.streamRegistry,this.streamStorageRegistry,this.loggerFactory,this.config)}async removeStreamFromStorageNode(e,t){return this.streamStorageRegistry.removeStreamFromStorageNode(e,nb(t))}async isStoredStream(e,t){return this.streamStorageRegistry.isStoredStream(e,nb(t))}async getStoredStreams(e){const t=await this.streamStorageRegistry.getStoredStreams(nb(e));for(const e of t.streams)this.streamRegistry.populateMetadataCache(e.id,e.metadata);return{streams:t.streams.map((e=>new y2(e.id,this))),blockNumber:t.blockNumber}}async getStorageNodes(e){return this.streamStorageRegistry.getStorageNodes(e)}setStorageNodeMetadata(e){return this.storageNodeRegistry.setStorageNodeMetadata(e)}async getStorageNodeMetadata(e){return this.storageNodeRegistry.getStorageNodeMetadata(nb(e))}getSigner(){return this.identity.getTransactionSigner(this.rpcProviderSource)}async getUserId(){return await this.identity.getUserId()}getAddress(){return this.getUserId()}getNode(){return this.node}async inspect(e,t){const r=await this.streamIdBuilder.toStreamPartID(t);return this.node.inspect(e,r)}async setProxies(e,t,r,n){const i=await this.streamIdBuilder.toStreamPartID(e);await this.node.setProxies(i,t,r,n)}async setStreamPartitionEntryPoints(e,t){const r=await this.streamIdBuilder.toStreamPartID(e);await this.node.setStreamPartEntryPoints(r,t)}connect(){return this._connect()}_connect=nJ((async()=>{await this.node.startNode()}));destroy(){return this._destroy()}_destroy=nJ((async()=>{this.eventEmitter.removeAllListeners(),this._connect.reset();const e=[this.destroySignal.destroy().then((()=>{})),this.unsubscribe()];await Promise.allSettled(e),await Promise.all(e)}));async getPeerDescriptor(){return JW(await this.node.getPeerDescriptor())}async getNodeId(){return this.node.getNodeId()}async getDiagnosticInfo(){return this.node.getDiagnosticInfo()}getConfig(){return this.config}getTheGraphClient(){return this.theGraphClient}getEthersOverrides(){return nD(this.rpcProviderSource,this.config)}getOperator(e){return new r4(e,this.contractFactory,this.rpcProviderSource,this.chainEventPoller,this.theGraphClient,this.identity,this.destroySignal,this.loggerFactory,(()=>this.getEthersOverrides()))}async findProxyNodes(e,t=1,r=100,n=24){return this.proxyNodeFinder.find(e,t,r,n)}on(e,t){this.eventEmitter.on(e,t)}once(e,t){this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.off(e,t)}},e.Subscription=f4,e._operatorContractUtils=S4,e.convertBytesToStreamMessage=_W,e.convertStreamMessageToBytes=function(e){return xH.toBinary(TW.toProtobuf(e))},e.formStorageNodeAssignmentStreamId=HW,e.getStreamPartitionCount=IJ,e.parseStreamMetadata=CJ,e.peerDescriptorTranslator=WW,window.StreamrClient=window.StreamrClient.StreamrClient}));
65
71
  //# sourceMappingURL=exports-umd.min.js.map