@liascript/editor 1.1.5--0.15.1 → 1.1.5--0.15.2

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.
@@ -1 +0,0 @@
1
- ("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequirea18f.register("5lNoZ",(function(t,e){var n,r;function i(t){if(!Number.isSafeInteger(t)||t<0)throw Error("Wrong positive integer: "+t)}function s(t,...e){if(!((n=t)instanceof Uint8Array||null!=n&&"object"==typeof n&&"Uint8Array"===n.constructor.name))throw Error("Expected Uint8Array");var n;if(e.length>0&&!e.includes(t.length))throw Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function o(t,e=!0){if(t.destroyed)throw Error("Hash instance has been destroyed");if(e&&t.finished)throw Error("Hash#digest() has already been called")}n=t.exports,r=()=>Ee,Object.defineProperty(n,"joinRoom",{get:r,set:undefined,enumerable:!0,configurable:!0});const a="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function c(t){return t instanceof Uint8Array||null!=t&&"object"==typeof t&&"Uint8Array"===t.constructor.name}const h=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),d=(t,e)=>t<<32-e|t>>>e;if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw Error("Non little-endian hardware is not supported");function l(t){if("string"==typeof t&&(t=function(t){if("string"!=typeof t)throw Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))}(t)),!c(t))throw Error("expected Uint8Array, got "+typeof t);return t}class u{clone(){return this._cloneInto()}}function f(t=32){if(a&&"function"==typeof a.getRandomValues)return a.getRandomValues(new Uint8Array(t));throw Error("crypto.getRandomValues must be defined")}class g extends u{constructor(t,e,n,r){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=h(this.buffer)}update(t){o(this);const{view:e,buffer:n,blockLen:r}=this,i=(t=l(t)).length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o!==r)n.set(t.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(e,0),this.pos=0);else{const e=h(t);for(;r<=i-s;s+=r)this.process(e,s)}}return this.length+=t.length,this.roundClean(),this}digestInto(t){o(this),function(t,e){s(t);const n=e.outputLen;if(t.length<n)throw Error("digestInto() expects output buffer of length at least "+n)}(t,this),this.finished=!0;const{buffer:e,view:n,blockLen:r,isLE:i}=this;let{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>r-a&&(this.process(n,0),a=0);for(let t=a;t<r;t++)e[t]=0;!function(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,h=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+h,a,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const c=h(t),d=this.outputLen;if(d%4)throw Error("_sha2: outputLen should be aligned to 32bit");const l=d/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let t=0;t<l;t++)c.setUint32(4*t,u[t],i)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:e,buffer:n,length:r,finished:i,destroyed:s,pos:o}=this;return t.length=r,t.pos=o,t.finished=i,t.destroyed=s,r%e&&t.buffer.set(n),t}}const p=(t,e,n)=>t&e^t&n^e&n,y=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),m=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_=new Uint32Array(64);class b extends g{constructor(){super(64,32,8,!1),this.A=0|m[0],this.B=0|m[1],this.C=0|m[2],this.D=0|m[3],this.E=0|m[4],this.F=0|m[5],this.G=0|m[6],this.H=0|m[7]}get(){const{A:t,B:e,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[t,e,n,r,i,s,o,a]}set(t,e,n,r,i,s,o,a){this.A=0|t,this.B=0|e,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(t,e){for(let n=0;n<16;n++,e+=4)_[n]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=_[t-15],n=_[t-2],r=d(e,7)^d(e,18)^e>>>3,i=d(n,17)^d(n,19)^n>>>10;_[t]=i+_[t-7]+r+_[t-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:c,H:h}=this;for(let t=0;t<64;t++){const e=h+(d(o,6)^d(o,11)^d(o,25))+((l=o)&a^~l&c)+y[t]+_[t]|0,u=(d(n,2)^d(n,13)^d(n,22))+p(n,r,i)|0;h=c,c=a,a=o,o=s+e|0,s=i,i=r,r=n,n=e+u|0}var l;n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(n,r,i,s,o,a,c,h)}roundClean(){_.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const E=function(t){const e=e=>t().update(l(e)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}((()=>new b)),w=BigInt(0),R=BigInt(1),A=BigInt(2);function v(t){return t instanceof Uint8Array||null!=t&&"object"==typeof t&&"Uint8Array"===t.constructor.name}const S=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function T(t){if(!v(t))throw Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=S[t[n]];return e}function C(t){const e=t.toString(16);return 1&e.length?"0"+e:e}function B(t){if("string"!=typeof t)throw Error("hex string expected, got "+typeof t);return BigInt(""===t?"0":"0x"+t)}const I={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function N(t){return t>=I._0&&t<=I._9?t-I._0:t>=I._A&&t<=I._F?t-(I._A-10):t>=I._a&&t<=I._f?t-(I._a-10):void 0}function O(t){if("string"!=typeof t)throw Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw Error("padded hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let e=0,i=0;e<n;e++,i+=2){const n=N(t.charCodeAt(i)),s=N(t.charCodeAt(i+1));if(void 0===n||void 0===s){const e=t[i]+t[i+1];throw Error('hex string expected, got non-hex character "'+e+'" at index '+i)}r[e]=16*n+s}return r}function k(t){return B(T(t))}function x(t){if(!v(t))throw Error("Uint8Array expected");return B(T(Uint8Array.from(t).reverse()))}function D(t,e){return O(t.toString(16).padStart(2*e,"0"))}function L(t,e){return D(t,e).reverse()}function P(t,e,n){let r;if("string"==typeof e)try{r=O(e)}catch(n){throw Error(`${t} must be valid hex string, got "${e}". Cause: ${n}`)}else{if(!v(e))throw Error(t+" must be hex string or Uint8Array");r=Uint8Array.from(e)}const i=r.length;if("number"==typeof n&&i!==n)throw Error(`${t} expected ${n} bytes, got ${i}`);return r}function q(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];if(!v(r))throw Error("Uint8Array expected");e+=r.length}let n=new Uint8Array(e),r=0;for(let e=0;e<t.length;e++){const i=t[e];n.set(i,r),r+=i.length}return n}const U=t=>(A<<BigInt(t-1))-R,H=t=>new Uint8Array(t),$=t=>Uint8Array.from(t);function F(t,e,n){if("number"!=typeof t||t<2)throw Error("hashLen must be a number");if("number"!=typeof e||e<2)throw Error("qByteLen must be a number");if("function"!=typeof n)throw Error("hmacFn must be a function");let r=H(t),i=H(t),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},a=(...t)=>n(i,r,...t),c=(t=H())=>{i=a($([0]),t),r=a(),0!==t.length&&(i=a($([1]),t),r=a())},h=()=>{if(s++>=1e3)throw Error("drbg: tried 1000 values");let t=0;const n=[];for(;t<e;){r=a();const e=r.slice();n.push(e),t+=r.length}return q(...n)};return(t,e)=>{let n;for(o(),c(t);!(n=e(h()));)c();return o(),n}}const M={bigint:t=>"bigint"==typeof t,function:t=>"function"==typeof t,boolean:t=>"boolean"==typeof t,string:t=>"string"==typeof t,stringOrUint8Array:t=>"string"==typeof t||v(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>"function"==typeof t&&Number.isSafeInteger(t.outputLen)};function j(t,e,n={}){const r=(e,n,r)=>{const i=M[n];if("function"!=typeof i)throw Error(`Invalid validator "${n}", expected function`);const s=t[e];if(!(r&&void 0===s||i(s,t)))throw Error(`Invalid param ${e+""}=${s} (${typeof s}), expected ${n}`)};for(const[t,n]of Object.entries(e))r(t,n,!1);for(const[t,e]of Object.entries(n))r(t,e,!0);return t}var z=Object.freeze({__proto__:null,bitGet:(t,e)=>t>>BigInt(e)&R,bitLen(t){let e;for(e=0;t>w;t>>=R,e+=1);return e},bitMask:U,bitSet:(t,e,n)=>t|(n?R:w)<<BigInt(e),bytesToHex:T,bytesToNumberBE:k,bytesToNumberLE:x,concatBytes:q,createHmacDrbg:F,ensureBytes:P,equalBytes(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n},hexToBytes:O,hexToNumber:B,isBytes:v,numberToBytesBE:D,numberToBytesLE:L,numberToHexUnpadded:C,numberToVarBytesBE:t=>O(C(t)),utf8ToBytes(t){if("string"!=typeof t)throw Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))},validateObject:j});const V=BigInt(0),K=BigInt(1),Z=BigInt(2),Y=BigInt(3),W=BigInt(4),G=BigInt(5),J=BigInt(8);function Q(t,e){const n=t%e;return n>=V?n:e+n}function X(t,e,n){if(n<=V||e<V)throw Error("Expected power/modulo > 0");if(n===K)return V;let r=K;for(;e>V;)e&K&&(r=r*t%n),t=t*t%n,e>>=K;return r}function tt(t,e,n){let r=t;for(;e-- >V;)r*=r,r%=n;return r}function et(t,e){if(t===V||e<=V)throw Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=Q(t,e),r=e,i=V,s=K;for(;n!==V;){const t=r%n,e=i-s*(r/n);r=n,n=t,i=s,s=e}if(r!==K)throw Error("invert: does not exist");return Q(i,e)}BigInt(9),BigInt(16);const nt=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rt(t,e){const n=void 0!==e?e:t.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function it(t){if("bigint"!=typeof t)throw Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function st(t){const e=it(t);return e+Math.ceil(e/2)}const ot=BigInt(0),at=BigInt(1);function ct(t){return j(t.Fp,nt.reduce(((t,e)=>(t[e]="function",t)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),j(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...rt(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const{bytesToNumberBE:ht,hexToBytes:dt}=z,lt={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){const{Err:e}=lt;if(t.length<2||2!==t[0])throw new e("Invalid signature integer tag");const n=t[1],r=t.subarray(2,n+2);if(!n||r.length!==n)throw new e("Invalid signature integer: wrong length");if(128&r[0])throw new e("Invalid signature integer: negative");if(0===r[0]&&!(128&r[1]))throw new e("Invalid signature integer: unnecessary leading zero");return{d:ht(r),l:t.subarray(n+2)}},toSig(t){const{Err:e}=lt,n="string"==typeof t?dt(t):t;if(!v(n))throw Error("ui8a expected");let r=n.length;if(r<2||48!=n[0])throw new e("Invalid signature tag");if(n[1]!==r-2)throw new e("Invalid signature: incorrect length");const{d:i,l:s}=lt._parseInt(n.subarray(2)),{d:o,l:a}=lt._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(t){const e=t=>8&Number.parseInt(t[0],16)?"00"+t:t,n=t=>{const e=t.toString(16);return 1&e.length?"0"+e:e},r=e(n(t.s)),i=e(n(t.r)),s=r.length/2,o=i.length/2,a=n(s),c=n(o);return`30${n(o+s+4)}02${c}${i}02${a}${r}`}},ut=BigInt(0),ft=BigInt(1);BigInt(2);const gt=BigInt(3);BigInt(4);class pt extends u{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,function(t){if("function"!=typeof t||"function"!=typeof t.create)throw Error("Hash should be wrapped by utils.wrapConstructor");i(t.outputLen),i(t.blockLen)}(t);const n=l(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(n.length>r?t.create().update(n).digest():n);for(let t=0;t<s.length;t++)s[t]^=54;this.iHash.update(s),this.oHash=t.create();for(let t=0;t<s.length;t++)s[t]^=106;this.oHash.update(s),s.fill(0)}update(t){return o(this),this.iHash.update(t),this}digestInto(t){o(this),s(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:e,iHash:n,finished:r,destroyed:i,blockLen:s,outputLen:o}=this;return t.finished=r,t.destroyed=i,t.blockLen=s,t.outputLen=o,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const yt=(t,e,n)=>new pt(t,e).update(n).digest();function mt(t){return{hash:t,hmac:(e,...n)=>yt(t,e,function(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];if(!c(r))throw Error("Uint8Array expected");e+=r.length}const n=new Uint8Array(e);for(let e=0,r=0;e<t.length;e++){const i=t[e];n.set(i,r),r+=i.length}return n}(...n)),randomBytes:f}}yt.create=(t,e)=>new pt(t,e);const _t=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),bt=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Et=BigInt(1),wt=BigInt(2),Rt=(t,e)=>(t+e/wt)/e;function At(t){const e=_t,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),h=t*t*t%e,d=h*h*t%e,l=tt(d,n,e)*d%e,u=tt(l,n,e)*d%e,f=tt(u,wt,e)*h%e,g=tt(f,i,e)*f%e,p=tt(g,s,e)*g%e,y=tt(p,a,e)*p%e,m=tt(y,c,e)*y%e,_=tt(m,a,e)*p%e,b=tt(_,n,e)*d%e,E=tt(b,o,e)*g%e,w=tt(E,r,e)*h%e,R=tt(w,wt,e);if(!vt.eql(vt.sqr(R),t))throw Error("Cannot find square root");return R}const vt=function(t,e,n=!1,r={}){if(t<=V)throw Error("Expected Field ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=rt(t,e);if(s>2048)throw Error("Field lengths over 2048 bytes are not supported");const o=function(t){if(t%W===Y){const e=(t+K)/W;return function(t,n){const r=t.pow(n,e);if(!t.eql(t.sqr(r),n))throw Error("Cannot find square root");return r}}if(t%J===G){const e=(t-G)/J;return function(t,n){const r=t.mul(n,Z),i=t.pow(r,e),s=t.mul(n,i),o=t.mul(t.mul(s,Z),i),a=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),n))throw Error("Cannot find square root");return a}}return function(t){const e=(t-K)/Z;let n,r,i;for(n=t-K,r=0;n%Z===V;n/=Z,r++);for(i=Z;i<t&&X(i,e,t)!==t-K;i++);if(1===r){const e=(t+K)/W;return(t,n)=>{const r=t.pow(n,e);if(!t.eql(t.sqr(r),n))throw Error("Cannot find square root");return r}}const s=(n+K)/Z;return(t,o)=>{if(t.pow(o,e)===t.neg(t.ONE))throw Error("Cannot find square root");let a=r,c=t.pow(t.mul(t.ONE,i),n),h=t.pow(o,s),d=t.pow(o,n);for(;!t.eql(d,t.ONE);){if(t.eql(d,t.ZERO))return t.ZERO;let e=1;for(let n=t.sqr(d);e<a&&!t.eql(n,t.ONE);e++)n=t.sqr(n);const n=t.pow(c,K<<BigInt(a-e-1));c=t.sqr(n),h=t.mul(h,n),d=t.mul(d,c),a=e}return h}}(t)}(t),a=Object.freeze({ORDER:t,BITS:i,BYTES:s,MASK:U(i),ZERO:V,ONE:K,create:e=>Q(e,t),isValid(e){if("bigint"!=typeof e)throw Error("Invalid field element: expected bigint, got "+typeof e);return V<=e&&e<t},is0:t=>t===V,isOdd:t=>(t&K)===K,neg:e=>Q(-e,t),eql:(t,e)=>t===e,sqr:e=>Q(e*e,t),add:(e,n)=>Q(e+n,t),sub:(e,n)=>Q(e-n,t),mul:(e,n)=>Q(e*n,t),pow:(t,e)=>function(t,e,n){if(n<V)throw Error("Expected power > 0");if(n===V)return t.ONE;if(n===K)return e;let r=t.ONE,i=e;for(;n>V;)n&K&&(r=t.mul(r,i)),i=t.sqr(i),n>>=K;return r}(a,t,e),div:(e,n)=>Q(e*et(n,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>et(e,t),sqrt:r.sqrt||(t=>o(a,t)),invertBatch:t=>function(t,e){const n=Array(e.length),r=e.reduce(((e,r,i)=>t.is0(r)?e:(n[i]=e,t.mul(e,r))),t.ONE),i=t.inv(r);return e.reduceRight(((e,r,i)=>t.is0(r)?e:(n[i]=t.mul(e,n[i]),t.mul(e,r))),i),n}(a,t),cmov:(t,e,n)=>n?e:t,toBytes:t=>n?L(t,s):D(t,s),fromBytes(t){if(t.length!==s)throw Error(`Fp.fromBytes: expected ${s}, got ${t.length}`);return n?x(t):k(t)}});return Object.freeze(a)}(_t,void 0,void 0,{sqrt:At}),St=function(t,e){const n=e=>function(t){const e=function(t){const e=ct(t);return j(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}(t),{Fp:n,n:r}=e,i=n.BYTES+1,s=2*n.BYTES+1;function o(t){return Q(t,r)}function a(t){return et(t,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:d,isWithinCurveOrder:l}=function(t){const e=function(t){const e=ct(t);j(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:i}=e;if(n){if(!r.eql(i,r.ZERO))throw Error("Endomorphism can only be defined for Koblitz curves that have a=0");if("object"!=typeof n||"bigint"!=typeof n.beta||"function"!=typeof n.splitScalar)throw Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}(t),{Fp:n}=e,r=e.toBytes||((t,e)=>{const r=e.toAffine();return q(Uint8Array.from([4]),n.toBytes(r.x),n.toBytes(r.y))}),i=e.fromBytes||(t=>{const e=t.subarray(1);return{x:n.fromBytes(e.subarray(0,n.BYTES)),y:n.fromBytes(e.subarray(n.BYTES,2*n.BYTES))}});function s(t){const{a:r,b:i}=e,s=n.sqr(t),o=n.mul(s,t);return n.add(n.add(o,n.mul(t,r)),i)}if(!n.eql(n.sqr(e.Gy),s(e.Gx)))throw Error("bad generator point: equation left != right");function o(t){return"bigint"==typeof t&&ut<t&&t<e.n}function a(t){if(!o(t))throw Error("Expected valid bigint: 0 < bigint < curve.n")}function c(t){const{allowedPrivateKeyLengths:n,nByteLength:r,wrapPrivateKey:i,n:s}=e;if(n&&"bigint"!=typeof t){if(v(t)&&(t=T(t)),"string"!=typeof t||!n.includes(t.length))throw Error("Invalid key");t=t.padStart(2*r,"0")}let o;try{o="bigint"==typeof t?t:k(P("private key",t,r))}catch(e){throw Error(`private key must be ${r} bytes, hex or bigint, not ${typeof t}`)}return i&&(o=Q(o,s)),a(o),o}const h=new Map;function d(t){if(!(t instanceof l))throw Error("ProjectivePoint expected")}class l{constructor(t,e,r){if(this.px=t,this.py=e,this.pz=r,null==t||!n.isValid(t))throw Error("x required");if(null==e||!n.isValid(e))throw Error("y required");if(null==r||!n.isValid(r))throw Error("z required")}static fromAffine(t){const{x:e,y:r}=t||{};if(!t||!n.isValid(e)||!n.isValid(r))throw Error("invalid affine point");if(t instanceof l)throw Error("projective point not allowed");const i=t=>n.eql(t,n.ZERO);return i(e)&&i(r)?l.ZERO:new l(e,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(t){const e=n.invertBatch(t.map((t=>t.pz)));return t.map(((t,n)=>t.toAffine(e[n]))).map(l.fromAffine)}static fromHex(t){const e=l.fromAffine(i(P("pointHex",t)));return e.assertValidity(),e}static fromPrivateKey(t){return l.BASE.multiply(c(t))}_setWindowSize(t){this._WINDOW_SIZE=t,h.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!n.is0(this.py))return;throw Error("bad point: ZERO")}const{x:t,y:r}=this.toAffine();if(!n.isValid(t)||!n.isValid(r))throw Error("bad point: x or y not FE");const i=n.sqr(r),o=s(t);if(!n.eql(i,o))throw Error("bad point: equation left != right");if(!this.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:t}=this.toAffine();if(n.isOdd)return!n.isOdd(t);throw Error("Field doesn't support isOdd")}equals(t){d(t);const{px:e,py:r,pz:i}=this,{px:s,py:o,pz:a}=t,c=n.eql(n.mul(e,a),n.mul(s,i)),h=n.eql(n.mul(r,a),n.mul(o,i));return c&&h}negate(){return new l(this.px,n.neg(this.py),this.pz)}double(){const{a:t,b:r}=e,i=n.mul(r,gt),{px:s,py:o,pz:a}=this;let c=n.ZERO,h=n.ZERO,d=n.ZERO,u=n.mul(s,s),f=n.mul(o,o),g=n.mul(a,a),p=n.mul(s,o);return p=n.add(p,p),d=n.mul(s,a),d=n.add(d,d),c=n.mul(t,d),h=n.mul(i,g),h=n.add(c,h),c=n.sub(f,h),h=n.add(f,h),h=n.mul(c,h),c=n.mul(p,c),d=n.mul(i,d),g=n.mul(t,g),p=n.sub(u,g),p=n.mul(t,p),p=n.add(p,d),d=n.add(u,u),u=n.add(d,u),u=n.add(u,g),u=n.mul(u,p),h=n.add(h,u),g=n.mul(o,a),g=n.add(g,g),u=n.mul(g,p),c=n.sub(c,u),d=n.mul(g,f),d=n.add(d,d),d=n.add(d,d),new l(c,h,d)}add(t){d(t);const{px:r,py:i,pz:s}=this,{px:o,py:a,pz:c}=t;let h=n.ZERO,u=n.ZERO,f=n.ZERO;const g=e.a,p=n.mul(e.b,gt);let y=n.mul(r,o),m=n.mul(i,a),_=n.mul(s,c),b=n.add(r,i),E=n.add(o,a);b=n.mul(b,E),E=n.add(y,m),b=n.sub(b,E),E=n.add(r,s);let w=n.add(o,c);return E=n.mul(E,w),w=n.add(y,_),E=n.sub(E,w),w=n.add(i,s),h=n.add(a,c),w=n.mul(w,h),h=n.add(m,_),w=n.sub(w,h),f=n.mul(g,E),h=n.mul(p,_),f=n.add(h,f),h=n.sub(m,f),f=n.add(m,f),u=n.mul(h,f),m=n.add(y,y),m=n.add(m,y),_=n.mul(g,_),E=n.mul(p,E),m=n.add(m,_),_=n.sub(y,_),_=n.mul(g,_),E=n.add(E,_),y=n.mul(m,E),u=n.add(u,y),y=n.mul(w,E),h=n.mul(b,h),h=n.sub(h,y),y=n.mul(b,m),f=n.mul(w,f),f=n.add(f,y),new l(h,u,f)}subtract(t){return this.add(t.negate())}is0(){return this.equals(l.ZERO)}wNAF(t){return f.wNAFCached(this,h,t,(t=>{const e=n.invertBatch(t.map((t=>t.pz)));return t.map(((t,n)=>t.toAffine(e[n]))).map(l.fromAffine)}))}multiplyUnsafe(t){const r=l.ZERO;if(t===ut)return r;if(a(t),t===ft)return this;const{endo:i}=e;if(!i)return f.unsafeLadder(this,t);let{k1neg:s,k1:o,k2neg:c,k2:h}=i.splitScalar(t),d=r,u=r,g=this;for(;o>ut||h>ut;)o&ft&&(d=d.add(g)),h&ft&&(u=u.add(g)),g=g.double(),o>>=ft,h>>=ft;return s&&(d=d.negate()),c&&(u=u.negate()),u=new l(n.mul(u.px,i.beta),u.py,u.pz),d.add(u)}multiply(t){a(t);let r,i,s=t;const{endo:o}=e;if(o){const{k1neg:t,k1:e,k2neg:a,k2:c}=o.splitScalar(s);let{p:h,f:d}=this.wNAF(e),{p:u,f:g}=this.wNAF(c);h=f.constTimeNegate(t,h),u=f.constTimeNegate(a,u),u=new l(n.mul(u.px,o.beta),u.py,u.pz),r=h.add(u),i=d.add(g)}else{const{p:t,f:e}=this.wNAF(s);r=t,i=e}return l.normalizeZ([r,i])[0]}multiplyAndAddUnsafe(t,e,n){const r=l.BASE,i=(t,e)=>e!==ut&&e!==ft&&t.equals(r)?t.multiply(e):t.multiplyUnsafe(e),s=i(this,e).add(i(t,n));return s.is0()?void 0:s}toAffine(t){const{px:e,py:r,pz:i}=this,s=this.is0();null==t&&(t=s?n.ONE:n.inv(i));const o=n.mul(e,t),a=n.mul(r,t),c=n.mul(i,t);if(s)return{x:n.ZERO,y:n.ZERO};if(!n.eql(c,n.ONE))throw Error("invZ was invalid");return{x:o,y:a}}isTorsionFree(){const{h:t,isTorsionFree:n}=e;if(t===ft)return!0;if(n)return n(l,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:t,clearCofactor:n}=e;return t===ft?this:n?n(l,this):this.multiplyUnsafe(e.h)}toRawBytes(t=!0){return this.assertValidity(),r(l,this,t)}toHex(t=!0){return T(this.toRawBytes(t))}}l.BASE=new l(e.Gx,e.Gy,n.ONE),l.ZERO=new l(n.ZERO,n.ONE,n.ZERO);const u=e.nBitLength,f=function(t,e){const n=(t,e)=>{const n=e.negate();return t?n:e},r=t=>({windows:Math.ceil(e/t)+1,windowSize:2**(t-1)});return{constTimeNegate:n,unsafeLadder(e,n){let r=t.ZERO,i=e;for(;n>ot;)n&at&&(r=r.add(i)),i=i.double(),n>>=at;return r},precomputeWindow(t,e){const{windows:n,windowSize:i}=r(e),s=[];let o=t,a=o;for(let t=0;t<n;t++){a=o,s.push(a);for(let t=1;t<i;t++)a=a.add(o),s.push(a);o=a.double()}return s},wNAF(e,i,s){const{windows:o,windowSize:a}=r(e);let c=t.ZERO,h=t.BASE;const d=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let t=0;t<o;t++){const e=t*a;let r=Number(s&d);s>>=u,r>a&&(r-=l,s+=at);const o=e,f=e+Math.abs(r)-1,g=t%2!=0,p=r<0;0===r?h=h.add(n(g,i[o])):c=c.add(n(p,i[f]))}return{p:c,f:h}},wNAFCached(t,e,n,r){const i=t._WINDOW_SIZE||1;let s=e.get(t);return s||(s=this.precomputeWindow(t,i),1!==i&&e.set(t,r(s))),this.wNAF(i,s,n)}}}(l,e.endo?Math.ceil(u/2):u);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:o}}({...e,toBytes(t,e,r){const i=e.toAffine(),s=n.toBytes(i.x),o=q;return r?o(Uint8Array.from([e.hasEvenY()?2:3]),s):o(Uint8Array.from([4]),s,n.toBytes(i.y))},fromBytes(t){const e=t.length,r=t[0],o=t.subarray(1);if(e!==i||2!==r&&3!==r){if(e===s&&4===r)return{x:n.fromBytes(o.subarray(0,n.BYTES)),y:n.fromBytes(o.subarray(n.BYTES,2*n.BYTES))};throw Error(`Point of length ${e} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}{const t=k(o);if(!(ut<(a=t)&&a<n.ORDER))throw Error("Point is not on curve");const e=d(t);let i=n.sqrt(e);return!(1&~r)!=((i&ft)===ft)&&(i=n.neg(i)),{x:t,y:i}}var a}}),u=t=>T(D(t,e.nByteLength));function f(t){return t>r>>ft}const g=(t,e,n)=>k(t.slice(e,n));class p{constructor(t,e,n){this.r=t,this.s=e,this.recovery=n,this.assertValidity()}static fromCompact(t){const n=e.nByteLength;return t=P("compactSignature",t,2*n),new p(g(t,0,n),g(t,n,2*n))}static fromDER(t){const{r:e,s:n}=lt.toSig(P("DER",t));return new p(e,n)}assertValidity(){if(!l(this.r))throw Error("r must be 0 < r < CURVE.n");if(!l(this.s))throw Error("s must be 0 < s < CURVE.n")}addRecoveryBit(t){return new p(this.r,this.s,t)}recoverPublicKey(t){const{r:r,s:i,recovery:s}=this,h=b(P("msgHash",t));if(null==s||![0,1,2,3].includes(s))throw Error("recovery id invalid");const d=2===s||3===s?r+e.n:r;if(d>=n.ORDER)throw Error("recovery id 2 or 3 invalid");const l=1&s?"03":"02",f=c.fromHex(l+u(d)),g=a(d),p=o(-h*g),y=o(i*g),m=c.BASE.multiplyAndAddUnsafe(f,p,y);if(!m)throw Error("point at infinify");return m.assertValidity(),m}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return O(this.toDERHex())}toDERHex(){return lt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return O(this.toCompactHex())}toCompactHex(){return u(this.r)+u(this.s)}}const y={isValidPrivateKey(t){try{return h(t),!0}catch(t){return!1}},normPrivateKeyToScalar:h,randomPrivateKey(){const t=st(e.n);return function(t,e,n=!1){const r=t.length,i=it(e),s=st(e);if(r<16||r<s||r>1024)throw Error(`expected ${s}-1024 bytes of input, got ${r}`);const o=Q(n?k(t):x(t),e-K)+K;return n?L(o,i):D(o,i)}(e.randomBytes(t),e.n)},precompute:(t=8,e=c.BASE)=>(e._setWindowSize(t),e.multiply(BigInt(3)),e)};function m(t){const e=v(t),n="string"==typeof t,r=(e||n)&&t.length;return e?r===i||r===s:n?r===2*i||r===2*s:t instanceof c}const _=e.bits2int||(t=>{const n=k(t),r=8*t.length-e.nBitLength;return r>0?n>>BigInt(r):n}),b=e.bits2int_modN||(t=>o(_(t))),E=U(e.nBitLength);function w(t){if("bigint"!=typeof t)throw Error("bigint expected");if(!(ut<=t&&t<E))throw Error("bigint expected < 2^"+e.nBitLength);return D(t,e.nByteLength)}function R(t,r,i=A){if(["recovered","canonical"].some((t=>t in i)))throw Error("sign() legacy options not supported");const{hash:s,randomBytes:d}=e;let{lowS:u,prehash:g,extraEntropy:y}=i;null==u&&(u=!0),t=P("msgHash",t),g&&(t=P("prehashed msgHash",s(t)));const m=b(t),E=h(r),R=[w(E),w(m)];if(null!=y){const t=!0===y?d(n.BYTES):y;R.push(P("extraEntropy",t))}const v=q(...R),S=m;return{seed:v,k2sig(t){const e=_(t);if(!l(e))return;const n=a(e),r=c.BASE.multiply(e).toAffine(),i=o(r.x);if(i===ut)return;const s=o(n*o(S+i*E));if(s===ut)return;let h=(r.x===i?0:2)|Number(r.y&ft),d=s;return u&&f(s)&&(d=function(t){return f(t)?o(-t):t}(s),h^=1),new p(i,d,h)}}}const A={lowS:e.lowS,prehash:!1},S={lowS:e.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:e,getPublicKey:(t,e=!0)=>c.fromPrivateKey(t).toRawBytes(e),getSharedSecret(t,e,n=!0){if(m(t))throw Error("first arg must be private key");if(!m(e))throw Error("second arg must be public key");return c.fromHex(e).multiply(h(t)).toRawBytes(n)},sign(t,n,r=A){const{seed:i,k2sig:s}=R(t,n,r),o=e;return F(o.hash.outputLen,o.nByteLength,o.hmac)(i,s)},verify(t,n,r,i=S){const s=t;if(n=P("msgHash",n),r=P("publicKey",r),"strict"in i)throw Error("options.strict was renamed to lowS");const{lowS:h,prehash:d}=i;let l,u;try{if("string"==typeof s||v(s))try{l=p.fromDER(s)}catch(t){if(!(t instanceof lt.Err))throw t;l=p.fromCompact(s)}else{if("object"!=typeof s||"bigint"!=typeof s.r||"bigint"!=typeof s.s)throw Error("PARSE");{const{r:t,s:e}=s;l=new p(t,e)}}u=c.fromHex(r)}catch(t){if("PARSE"===t.message)throw Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(h&&l.hasHighS())return!1;d&&(n=e.hash(n));const{r:f,s:g}=l,y=b(n),m=a(g),_=o(y*m),E=o(f*m),w=c.BASE.multiplyAndAddUnsafe(u,_,E)?.toAffine();return!!w&&o(w.x)===f},ProjectivePoint:c,Signature:p,utils:y}}({...t,...mt(e)});return Object.freeze({...n(e),create:n})}({a:BigInt(0),b:BigInt(7),Fp:vt,n:bt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(t){const e=bt,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Et*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=Rt(s*t,e),c=Rt(-r*t,e);let h=Q(t-a*n-c*i,e),d=Q(-a*r-c*s,e);const l=h>o,u=d>o;if(l&&(h=e-h),u&&(d=e-d),h>o||d>o)throw Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:l,k1:h,k2neg:u,k2:d}}}},E),Tt=BigInt(0),Ct=t=>"bigint"==typeof t&&Tt<t&&t<_t,Bt=t=>"bigint"==typeof t&&Tt<t&&t<bt,It={};function Nt(t,...e){let n=It[t];if(void 0===n){const e=E(Uint8Array.from(t,(t=>t.charCodeAt(0))));n=q(e,e),It[t]=n}return E(q(n,...e))}const Ot=t=>t.toRawBytes(!0).slice(1),kt=t=>D(t,32),xt=t=>Q(t,_t),Dt=t=>Q(t,bt),Lt=St.ProjectivePoint,Pt=(t,e,n)=>Lt.BASE.multiplyAndAddUnsafe(t,e,n);function qt(t){let e=St.utils.normPrivateKeyToScalar(t),n=Lt.fromPrivateKey(e);return{scalar:n.hasEvenY()?e:Dt(-e),bytes:Ot(n)}}function Ut(t){if(!Ct(t))throw Error("bad x: need 0 < x < p");const e=xt(t*t);let n=At(xt(e*t+BigInt(7)));n%wt!==Tt&&(n=xt(-n));const r=new Lt(t,n,Et);return r.assertValidity(),r}function Ht(...t){return Dt(k(Nt("BIP0340/challenge",...t)))}function $t(t,e,n){const r=P("signature",t,64),i=P("message",e),s=P("publicKey",n,32);try{const t=Ut(k(s)),e=k(r.subarray(0,32));if(!Ct(e))return!1;const n=k(r.subarray(32,64));if(!Bt(n))return!1;const o=Ht(kt(e),Ot(t),i),a=Pt(t,n,Dt(-o));return!(!a||!a.hasEvenY()||a.toAffine().x!==e)}catch(t){return!1}}const Ft={getPublicKey:function(t){return qt(t).bytes},sign:function(t,e,n=f(32)){const r=P("message",t),{bytes:i,scalar:s}=qt(e),o=P("auxRand",n,32),a=kt(s^k(Nt("BIP0340/aux",o))),c=Nt("BIP0340/nonce",a,i,r),h=Dt(k(c));if(h===Tt)throw Error("sign failed: k is zero");const{bytes:d,scalar:l}=qt(h),u=Ht(d,i,r),g=new Uint8Array(64);if(g.set(d,0),g.set(kt(Dt(l+u*s)),32),!$t(g,r,i))throw Error("sign: Invalid signature produced");return g},verify:$t,utils:{randomPrivateKey:St.utils.randomPrivateKey,lift_x:Ut,pointToBytes:Ot,numberToBytesBE:D,bytesToNumberBE:k,taggedHash:Nt,mod:Q}};function Mt(t){const e=new Uint8Array(t);for(let n=0;n<t;n++)e[n]=256*Math.random()|0;return e}function jt(){if("undefined"==typeof globalThis)return null;const t={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return t.RTCPeerConnection?t:null}function zt(t,e){return Object.defineProperty(t,"code",{value:e,enumerable:!0,configurable:!0}),t}function Vt(t){return t.replace(/a=ice-options:trickle\s\n/g,"")}class Kt{constructor(t={}){if(this._map=new Map,this._id=Mt(4).toString("hex").slice(0,7),this._doDebug=t.debug,this._debug("new peer %o",t),this.channelName=t.initiator?t.channelName||Mt(20).toString("hex"):null,this.initiator=t.initiator||!1,this.channelConfig=t.channelConfig||Kt.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Kt.config,t.config),this.offerOptions=t.offerOptions||{},this.answerOptions=t.answerOptions||{},this.sdpTransform=t.sdpTransform||(t=>t),this.streams=t.streams||(t.stream?[t.stream]:[]),this.trickle=void 0===t.trickle||t.trickle,this.allowHalfTrickle=void 0!==t.allowHalfTrickle&&t.allowHalfTrickle,this.iceCompleteTimeout=t.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=t.wrtc&&"object"==typeof t.wrtc?t.wrtc:jt(),!this._wrtc)throw"undefined"==typeof window?zt(Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):zt(Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(t){return void this.destroy(zt(t,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=t=>{this._onIceCandidate(t)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch((t=>{this.destroy(zt(t,"ERR_PC_PEER_IDENTITY"))})),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=t=>{this._setupData(t)},this.streams&&this.streams.forEach((t=>{this.addStream(t)})),this._pc.ontrack=t=>{this._onTrack(t)},this._debug("initial negotiation"),this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(t){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof t)try{t=JSON.parse(t)}catch(e){t={}}this._debug("signal()"),t.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),t.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(t.transceiverRequest.kind,t.transceiverRequest.init)),t.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(t.candidate):this._pendingCandidates.push(t.candidate)),t.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(t)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((t=>{this._addIceCandidate(t)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((t=>{this.destroy(zt(t,"ERR_SET_REMOTE_DESCRIPTION"))})),t.sdp||t.candidate||t.renegotiate||t.transceiverRequest||this.destroy(zt(Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(t){const e=new this._wrtc.RTCIceCandidate(t);this._pc.addIceCandidate(e).catch((t=>{!e.address||e.address.endsWith(".local")?console.warn("Ignoring unsupported ICE candidate."):this.destroy(zt(t,"ERR_ADD_ICE_CANDIDATE"))}))}send(t){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(t)}}addTransceiver(t,e){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(t,e),this._needsNegotiation()}catch(t){this.destroy(zt(t,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:t,init:e}})}}addStream(t){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),t.getTracks().forEach((e=>{this.addTrack(e,t)}))}}addTrack(t,e){if(this.destroying)return;if(this.destroyed)throw zt(Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(t)||new Map;let r=n.get(e);if(r)throw r.removed?zt(Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):zt(Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");r=this._pc.addTrack(t,e),n.set(e,r),this._senderMap.set(t,n),this._needsNegotiation()}replaceTrack(t,e,n){if(this.destroying)return;if(this.destroyed)throw zt(Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const r=this._senderMap.get(t),i=r?r.get(n):null;if(!i)throw zt(Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");e&&this._senderMap.set(e,r),null!=i.replaceTrack?i.replaceTrack(e):this.destroy(zt(Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(t,e){if(this.destroying)return;if(this.destroyed)throw zt(Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const n=this._senderMap.get(t),r=n?n.get(e):null;if(!r)throw zt(Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{r.removed=!0,this._pc.removeTrack(r)}catch(t){"NS_ERROR_UNEXPECTED"===t.name?this._sendersAwaitingStable.push(r):this.destroy(zt(t,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(t){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),t.getTracks().forEach((e=>{this.removeTrack(e,t)}))}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask((()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1})))}negotiate(){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout((()=>{this._createOffer()}),0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(t){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",t&&(t.message||t)),queueMicrotask((()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",t&&(t.message||t)),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(t){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(t){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,t&&this.emit("error",t),this.emit("close")})))}_setupData(t){if(!t.channel)return this.destroy(zt(Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=t.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=65536),this.channelName=this._channel.label,this._channel.onmessage=t=>{this._onChannelMessage(t)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=t=>{this.destroy(zt(t,"ERR_DATA_CHANNEL"))};let e=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(e&&this._onChannelClose(),e=!0):e=!1}),5e3)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((t=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(t.sdp=Vt(t.sdp)),t.sdp=this.sdpTransform(t.sdp);const e=()=>{if(this.destroyed)return;const e=this._pc.localDescription||t;this._debug("signal"),this.emit("signal",{type:e.type,sdp:e.sdp})};this._pc.setLocalDescription(t).then((()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?e():this.once("_iceComplete",e))})).catch((t=>{this.destroy(zt(t,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((t=>{this.destroy(zt(t,"ERR_CREATE_OFFER"))}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((t=>{t.mid||!t.sender.track||t.requested||(t.requested=!0,this.addTransceiver(t.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((t=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(t.sdp=Vt(t.sdp)),t.sdp=this.sdpTransform(t.sdp);const e=()=>{if(this.destroyed)return;const e=this._pc.localDescription||t;this._debug("signal"),this.emit("signal",{type:e.type,sdp:e.sdp}),this.initiator||this._requestMissingTransceivers()};this._pc.setLocalDescription(t).then((()=>{this.destroyed||(this.trickle||this._iceComplete?e():this.once("_iceComplete",e))})).catch((t=>{this.destroy(zt(t,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((t=>{this.destroy(zt(t,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(zt(Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const t=this._pc.iceConnectionState,e=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",t,e),this.emit("iceStateChange",t,e),"connected"!==t&&"completed"!==t||(this._pcReady=!0,this._maybeReady()),"failed"===t&&this.destroy(zt(Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===t&&this.destroy(zt(Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(t){const e=t=>("[object Array]"==={}.toString.call(t.values)&&t.values.forEach((e=>{Object.assign(t,e)})),t);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((n=>{const r=[];n.forEach((t=>{r.push(e(t))})),t(null,r)}),(e=>t(e))):this._pc.getStats.length>0?this._pc.getStats((n=>{if(this.destroyed)return;const r=[];n.result().forEach((t=>{const n={};t.names().forEach((e=>{n[e]=t.stat(e)})),n.id=t.id,n.type=t.type,n.timestamp=t.timestamp,r.push(e(n))})),t(null,r)}),(e=>t(e))):t(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const t=()=>{this.destroyed||this.getStats(((e,n)=>{if(this.destroyed)return;e&&(n=[]);const r={},i={},s={};let o=!1;n.forEach((t=>{"remotecandidate"!==t.type&&"remote-candidate"!==t.type||(r[t.id]=t),"localcandidate"!==t.type&&"local-candidate"!==t.type||(i[t.id]=t),"candidatepair"!==t.type&&"candidate-pair"!==t.type||(s[t.id]=t)}));const a=t=>{o=!0;let e=i[t.localCandidateId];e&&(e.ip||e.address)?(this.localAddress=e.ip||e.address,this.localPort=Number(e.port)):e&&e.ipAddress?(this.localAddress=e.ipAddress,this.localPort=Number(e.portNumber)):"string"==typeof t.googLocalAddress&&(e=t.googLocalAddress.split(":"),this.localAddress=e[0],this.localPort=Number(e[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=r[t.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=Number(n.port)):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=Number(n.portNumber)):"string"==typeof t.googRemoteAddress&&(n=t.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=Number(n[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach((t=>{"transport"===t.type&&t.selectedCandidatePairId&&a(s[t.selectedCandidatePairId]),("googCandidatePair"===t.type&&"true"===t.googActiveConnection||("candidatepair"===t.type||"candidate-pair"===t.type)&&t.selected)&&a(t)})),o||Object.keys(s).length&&!Object.keys(i).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(zt(e,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const t=this._cb;this._cb=null,t(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(t,100)}))};t()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>65536||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach((t=>{this._pc.removeTrack(t),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(t){this.destroyed||(t.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:t.candidate.candidate,sdpMLineIndex:t.candidate.sdpMLineIndex,sdpMid:t.candidate.sdpMid}}):t.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),t.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(t){if(this.destroyed)return;let e=t.data;e instanceof ArrayBuffer&&(e=new Uint8Array(e)),this.emit("data",e)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const t=this._cb;this._cb=null,t(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(t){this.destroyed||t.streams.forEach((e=>{this._debug("on track"),this.emit("track",t.track,e),this._remoteTracks.push({track:t.track,stream:e}),this._remoteStreams.some((t=>t.id===e.id))||(this._remoteStreams.push(e),queueMicrotask((()=>{this._debug("on stream"),this.emit("stream",e)})))}))}_debug(...t){this._doDebug&&(t[0]="["+this._id+"] "+t[0])}on(t,e){const n=this._map;n.has(t)||n.set(t,new Set),n.get(t).add(e)}off(t,e){const n=this._map,r=n.get(t);r&&(r.delete(e),0===r.size&&n.delete(t))}once(t,e){const n=(...r)=>{this.off(t,n),e(...r)};this.on(t,n)}emit(t,...e){const n=this._map;if(n.has(t))for(const r of n.get(t))try{r(...e)}catch(t){console.error(t)}}}Kt.WEBRTC_SUPPORT=!!jt(),Kt.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Kt.channelConfig={};const Zt=(t,e,n)=>{const r=new Kt({initiator:t,trickle:e,config:n}),i=t=>r.__earlyDataBuffer.push(t);return r.on(oe.data,i),r.__earlyDataBuffer=[],r.__drainEarlyData=t=>{r.off(oe.data,i),r.__earlyDataBuffer.forEach(t),delete r.__earlyDataBuffer,delete r.__drainEarlyData},r},Yt=t=>Array(t).fill().map((()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[Math.floor(62*Math.random())])).join(""),Wt="Trystero",Gt=Yt(20),{keys:Jt,values:Qt,entries:Xt,fromEntries:te}=Object,ee=()=>{},ne=t=>Error(`${Wt}: ${t}`),re=t=>(new TextEncoder).encode(t),ie=t=>(new TextDecoder).decode(t),se=t=>t.reduce(((t,e)=>t+e.toString(16).padStart(2,"0")),""),oe=te(["close","connect","data","error","signal","stream","track"].map((t=>[t,t]))),ae=Object.getPrototypeOf(Uint8Array),ce=16369,he=255,de="bufferedamountlow",le="AES-CBC",ue=async(t,e)=>{const n=crypto.getRandomValues(new Uint8Array(16));var r;return JSON.stringify({c:(r=await crypto.subtle.encrypt({name:le,iv:n},await t,re(e)),btoa(String.fromCharCode.apply(null,new Uint8Array(r)))),iv:[...n]})},fe=async(t,e)=>{const{c:n,iv:r}=JSON.parse(e);return ie(await crypto.subtle.decrypt({name:le,iv:new Uint8Array(r)},await t,(t=>{const e=atob(t);return new Uint8Array(e.length).map(((t,n)=>e.charCodeAt(n))).buffer})(n)))},ge={},pe=se(crypto.getRandomValues(new Uint8Array(32))),ye=se(Ft.getPublicKey(pe)),me={},_e=()=>Math.floor(Date.now()/1e3),be=["wss://relay.nostr.net","wss://relay.blackbyte.nl","wss://relay.piazza.today","wss://relay.exit.pub","wss://relay.nostr.band","wss://relay.damus.io","wss://nostr.mom","wss://relay.snort.social","wss://nostr.lu.ke","wss://relay.plebstr.com","wss://nostr.sathoarder.com","wss://nsrelay.assilvestrar.club","wss://nostrasia.casa","wss://relay.nostr.bg","wss://relay.nostrr.de","wss://relay.nostrss.re"],Ee=(we=ge,(t,e)=>{if(we[e])return we[e];if(!t)throw ne("requires a config map as the first argument");if(!t.appId&&!t.firebaseApp)throw ne("config map is missing appId field");if(!e)throw ne("namespace argument required");return we[e]=((t,e)=>{const n=t.password&&(async(t,e)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},re(`${t}:${e}`)),{name:le},!1,["encrypt","decrypt"]))(t.password,e),r=`trystero/${t.appId}/${e}`,i=`${r}/${Gt}`,s=Yt(64),o=Yt(64),a={},c={},h={},d=((t,e,n)=>(t.relayUrls||e).slice(0,t.relayUrls?t.relayUrls.length:t.relayRedundancy||4))(t,be),l=(t,e)=>{y(t,e),h[e]=t},u=t=>{delete a[t],delete c[t],delete h[t]},f=(t,e)=>JSON.stringify(["REQ",t,{kinds:[29333],since:_e(),"#x":[e]}]),g=t=>JSON.stringify(["CLOSE",t]),p=async(t,e)=>{const n={kind:29333,content:JSON.stringify(e),pubkey:ye,created_at:_e(),tags:[["x",t]]},r=se(new Uint8Array(await crypto.subtle.digest("SHA-256",re(JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content])))));return JSON.stringify(["EVENT",{...n,id:r,sig:se(await Ft.sign(r,pe))}])};let y=ee;return d.forEach((e=>{const d=new WebSocket(e);me[e]=d,d.addEventListener("open",(async()=>{d.send(f(s,r)),d.send(f(o,i)),d.send(await p(r,Gt))})),d.addEventListener("message",(async e=>{const[i,f,g,y]=JSON.parse(e.data);if("EVENT"!==i)return void("OK"!==i||g||console.warn(`${Wt}: relay failure from ${d.url} - ${y}`));const m=JSON.parse(g.content);if(f===s){const e=m;if(e!==Gt&&!h[e]&&!c[e]){c[e]=!0;const i=a[e]=Zt(!0,!1,t.rtcConfig);i.once(oe.signal,(async t=>{d.send(await p(`${r}/${e}`,{peerId:Gt,offer:n?{...t,sdp:await ue(n,t.sdp)}:t}))})),i.once(oe.connect,(()=>l(i,e))),i.once(oe.close,(()=>u(e)))}}else if(f===o){const{peerId:e,offer:i,answer:s}=m;if(a[e]&&s)return void a[e].signal(n?{...s,sdp:await fe(n,s.sdp)}:s);if(!i)return;const o=Zt(!1,!1,t.rtcConfig);o.once(oe.signal,(async t=>d.send(await p(`${r}/${e}`,{peerId:Gt,answer:n?{...t,sdp:await ue(n,t.sdp)}:t})))),o.once(oe.connect,(()=>l(o,e))),o.once(oe.close,(()=>u(e))),o.signal(i)}}))})),((t,e)=>{const n={},r={},i={},s={},o={},a={},c=(t,e)=>(t?Array.isArray(t)?t:[t]:Jt(n)).flatMap((t=>{const r=n[t];return r?e(t,r):(console.warn(`${Wt}: no peer with id ${t} found`),[])})),h=t=>{if(r[t])return[r[t].send,r[t].setOnComplete,r[t].setOnProgress];if(!t)throw ne("action type argument is required");const e=re(t);if(e.byteLength>12)throw ne(`action type string "${t}" (${e.byteLength}b) exceeds byte limit (12). Hint: choose a shorter name.`);const i=new Uint8Array(12);i.set(e);let s=0;return r[t]={onComplete:ee,onProgress:ee,setOnComplete:e=>r[t]={...r[t],onComplete:e},setOnProgress:e=>r[t]={...r[t],onProgress:e},async send(t,e,r,o){if(r&&"object"!=typeof r)throw ne("action meta argument must be an object");if(void 0===t)throw ne("action data cannot be undefined");const a="string"!=typeof t,h=t instanceof Blob,d=h||t instanceof ArrayBuffer||t instanceof ae;if(r&&!d)throw ne("action meta argument can only be used with binary data");const l=d?new Uint8Array(h?await t.arrayBuffer():t):re(a?JSON.stringify(t):t),u=r?re(JSON.stringify(r)):null,f=Math.ceil(l.byteLength/ce)+(r?1:0)||1,g=Array(f).fill().map(((t,e)=>{const n=e===f-1,o=r&&0===e,c=new Uint8Array(15+(o?u.byteLength:n?l.byteLength-ce*(f-(r?2:1)):ce));return c.set(i),c.set([s],12),c.set([n|o<<1|d<<2|a<<3],13),c.set([Math.round((e+1)/f*he)],14),c.set(r?o?u:l.subarray((e-1)*ce,e*ce):l.subarray(e*ce,(e+1)*ce),15),c}));return s=s+1&he,Promise.all(c(e,(async(t,e)=>{const i=e._channel;let s=0;for(;s<f;){const a=g[s];if(i.bufferedAmount>i.bufferedAmountLowThreshold&&await new Promise((t=>{const e=()=>{i.removeEventListener(de,e),t()};i.addEventListener(de,e)})),!n[t])break;e.send(a),s++,o&&o(a[14]/he,t,r)}})))}},[r[t].send,r[t].setOnComplete,r[t].setOnProgress]},d=(t,e)=>{const n=new Uint8Array(e),s=ie(n.subarray(0,12)).replaceAll("\0",""),[o]=n.subarray(12,13),[a]=n.subarray(13,14),[c]=n.subarray(14,15),h=n.subarray(15),d=!!(1&a),l=!!(2&a),u=!!(4&a),f=!!(8&a);if(!r[s])throw ne(`received message with unregistered type (${s})`);i[t]||(i[t]={}),i[t][s]||(i[t][s]={});let g=i[t][s][o];if(g||(g=i[t][s][o]={chunks:[]}),l?g.meta=JSON.parse(ie(h)):g.chunks.push(h),r[s].onProgress(c/he,t,g.meta),!d)return;const p=new Uint8Array(g.chunks.reduce(((t,e)=>t+e.byteLength),0));if(g.chunks.reduce(((t,e)=>(p.set(e,t),t+e.byteLength)),0),u)r[s].onComplete(p,t,g.meta);else{const e=ie(p);r[s].onComplete(f?JSON.parse(e):e,t)}delete i[t][s][o]},[l,u]=h("__91n6__"),[f,g]=h("__90n6__"),[p,y]=h("__516n4L__"),[m,_]=h("__57r34m__"),[b,E]=h("__7r4ck__");let w=ee,R=ee,A=ee,v=ee;return t(((t,e)=>{if(n[e])return;const r=d.bind(null,e);n[e]=t,t.on(oe.signal,(t=>p(t,e))),t.on(oe.close,(()=>(t=>{n[t]&&(delete n[t],delete i[t],delete s[t],R(t))})(e))),t.on(oe.data,r),t.on(oe.stream,(t=>{A(t,e,o[e]),delete o[e]})),t.on(oe.track,((t,n)=>{v(t,n,e,a[e]),delete a[e]})),t.on(oe.error,(t=>{"ERR_DATA_CHANNEL"!==t.code&&console.error(t)})),w(e),t.__drainEarlyData(r)})),u(((t,e)=>f("",e))),g(((t,e)=>{s[e]&&(s[e](),delete s[e])})),y(((t,e)=>{n[e]&&n[e].signal(t)})),_(((t,e)=>o[e]=t)),E(((t,e)=>a[e]=t)),{makeAction:h,async ping(t){if(!t)throw ne("ping() must be called with target peer ID");const e=Date.now();return l("",t),await new Promise((e=>s[t]=e)),Date.now()-e},leave(){Xt(n).forEach((([t,e])=>{e.destroy(),delete n[t]})),e()},getPeers:()=>te(Xt(n).map((([t,e])=>[t,e._pc]))),addStream:(t,e,n)=>c(e,(async(e,r)=>{n&&await m(n,e),r.addStream(t)})),removeStream:(t,e)=>c(e,((e,n)=>n.removeStream(t))),addTrack:(t,e,n,r)=>c(n,(async(n,i)=>{r&&await b(r,n),i.addTrack(t,e)})),removeTrack:(t,e,n)=>c(n,((n,r)=>r.removeTrack(t,e))),replaceTrack:(t,e,n,r,i)=>c(r,(async(r,s)=>{i&&await b(i,r),s.replaceTrack(t,e,n)})),onPeerJoin:t=>w=t,onPeerLeave:t=>R=t,onPeerStream:t=>A=t,onPeerTrack:t=>v=t}})((t=>y=t),(()=>{delete ge[e],Qt(me).forEach((t=>{t.send(g(s)),t.send(g(o))}))}))})(t,e)});var we}));
@@ -1 +0,0 @@
1
- ("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequirea18f.register("9ZhAU",(function(t,e){var n,r;function i(t){if(!Number.isSafeInteger(t)||t<0)throw Error("Wrong positive integer: "+t)}function s(t,...e){if(!((n=t)instanceof Uint8Array||null!=n&&"object"==typeof n&&"Uint8Array"===n.constructor.name))throw Error("Expected Uint8Array");var n;if(e.length>0&&!e.includes(t.length))throw Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function o(t,e=!0){if(t.destroyed)throw Error("Hash instance has been destroyed");if(e&&t.finished)throw Error("Hash#digest() has already been called")}n=t.exports,r=function(){return Ee},Object.defineProperty(n,"joinRoom",{get:r,set:undefined,enumerable:!0,configurable:!0});const a="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function c(t){return t instanceof Uint8Array||null!=t&&"object"==typeof t&&"Uint8Array"===t.constructor.name}const h=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),d=(t,e)=>t<<32-e|t>>>e;if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw Error("Non little-endian hardware is not supported");function l(t){if("string"==typeof t&&(t=function(t){if("string"!=typeof t)throw Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))}(t)),!c(t))throw Error("expected Uint8Array, got "+typeof t);return t}class u{clone(){return this._cloneInto()}}function f(t=32){if(a&&"function"==typeof a.getRandomValues)return a.getRandomValues(new Uint8Array(t));throw Error("crypto.getRandomValues must be defined")}class g extends u{constructor(t,e,n,r){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=h(this.buffer)}update(t){o(this);const{view:e,buffer:n,blockLen:r}=this,i=(t=l(t)).length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o!==r)n.set(t.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(e,0),this.pos=0);else{const e=h(t);for(;r<=i-s;s+=r)this.process(e,s)}}return this.length+=t.length,this.roundClean(),this}digestInto(t){o(this),function(t,e){s(t);const n=e.outputLen;if(t.length<n)throw Error("digestInto() expects output buffer of length at least "+n)}(t,this),this.finished=!0;const{buffer:e,view:n,blockLen:r,isLE:i}=this;let{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>r-a&&(this.process(n,0),a=0);for(let t=a;t<r;t++)e[t]=0;!function(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,h=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+h,a,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const c=h(t),d=this.outputLen;if(d%4)throw Error("_sha2: outputLen should be aligned to 32bit");const l=d/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let t=0;t<l;t++)c.setUint32(4*t,u[t],i)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:e,buffer:n,length:r,finished:i,destroyed:s,pos:o}=this;return t.length=r,t.pos=o,t.finished=i,t.destroyed=s,r%e&&t.buffer.set(n),t}}const p=(t,e,n)=>t&e^t&n^e&n,y=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),m=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_=new Uint32Array(64);class b extends g{constructor(){super(64,32,8,!1),this.A=0|m[0],this.B=0|m[1],this.C=0|m[2],this.D=0|m[3],this.E=0|m[4],this.F=0|m[5],this.G=0|m[6],this.H=0|m[7]}get(){const{A:t,B:e,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[t,e,n,r,i,s,o,a]}set(t,e,n,r,i,s,o,a){this.A=0|t,this.B=0|e,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(t,e){for(let n=0;n<16;n++,e+=4)_[n]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=_[t-15],n=_[t-2],r=d(e,7)^d(e,18)^e>>>3,i=d(n,17)^d(n,19)^n>>>10;_[t]=i+_[t-7]+r+_[t-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:c,H:h}=this;for(let t=0;t<64;t++){const e=h+(d(o,6)^d(o,11)^d(o,25))+((l=o)&a^~l&c)+y[t]+_[t]|0,u=(d(n,2)^d(n,13)^d(n,22))+p(n,r,i)|0;h=c,c=a,a=o,o=s+e|0,s=i,i=r,r=n,n=e+u|0}var l;n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(n,r,i,s,o,a,c,h)}roundClean(){_.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const E=function(t){const e=e=>t().update(l(e)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}((()=>new b)),w=BigInt(0),R=BigInt(1),A=BigInt(2);function v(t){return t instanceof Uint8Array||null!=t&&"object"==typeof t&&"Uint8Array"===t.constructor.name}const S=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function T(t){if(!v(t))throw Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=S[t[n]];return e}function C(t){const e=t.toString(16);return 1&e.length?"0"+e:e}function B(t){if("string"!=typeof t)throw Error("hex string expected, got "+typeof t);return BigInt(""===t?"0":"0x"+t)}const I={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function N(t){return t>=I._0&&t<=I._9?t-I._0:t>=I._A&&t<=I._F?t-(I._A-10):t>=I._a&&t<=I._f?t-(I._a-10):void 0}function O(t){if("string"!=typeof t)throw Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw Error("padded hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let e=0,i=0;e<n;e++,i+=2){const n=N(t.charCodeAt(i)),s=N(t.charCodeAt(i+1));if(void 0===n||void 0===s){const e=t[i]+t[i+1];throw Error('hex string expected, got non-hex character "'+e+'" at index '+i)}r[e]=16*n+s}return r}function k(t){return B(T(t))}function x(t){if(!v(t))throw Error("Uint8Array expected");return B(T(Uint8Array.from(t).reverse()))}function D(t,e){return O(t.toString(16).padStart(2*e,"0"))}function L(t,e){return D(t,e).reverse()}function P(t,e,n){let r;if("string"==typeof e)try{r=O(e)}catch(n){throw Error(`${t} must be valid hex string, got "${e}". Cause: ${n}`)}else{if(!v(e))throw Error(t+" must be hex string or Uint8Array");r=Uint8Array.from(e)}const i=r.length;if("number"==typeof n&&i!==n)throw Error(`${t} expected ${n} bytes, got ${i}`);return r}function q(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];if(!v(r))throw Error("Uint8Array expected");e+=r.length}let n=new Uint8Array(e),r=0;for(let e=0;e<t.length;e++){const i=t[e];n.set(i,r),r+=i.length}return n}const U=t=>(A<<BigInt(t-1))-R,H=t=>new Uint8Array(t),$=t=>Uint8Array.from(t);function F(t,e,n){if("number"!=typeof t||t<2)throw Error("hashLen must be a number");if("number"!=typeof e||e<2)throw Error("qByteLen must be a number");if("function"!=typeof n)throw Error("hmacFn must be a function");let r=H(t),i=H(t),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},a=(...t)=>n(i,r,...t),c=(t=H())=>{i=a($([0]),t),r=a(),0!==t.length&&(i=a($([1]),t),r=a())},h=()=>{if(s++>=1e3)throw Error("drbg: tried 1000 values");let t=0;const n=[];for(;t<e;){r=a();const e=r.slice();n.push(e),t+=r.length}return q(...n)};return(t,e)=>{let n;for(o(),c(t);!(n=e(h()));)c();return o(),n}}const M={bigint:t=>"bigint"==typeof t,function:t=>"function"==typeof t,boolean:t=>"boolean"==typeof t,string:t=>"string"==typeof t,stringOrUint8Array:t=>"string"==typeof t||v(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>"function"==typeof t&&Number.isSafeInteger(t.outputLen)};function j(t,e,n={}){const r=(e,n,r)=>{const i=M[n];if("function"!=typeof i)throw Error(`Invalid validator "${n}", expected function`);const s=t[e];if(!(r&&void 0===s||i(s,t)))throw Error(`Invalid param ${e+""}=${s} (${typeof s}), expected ${n}`)};for(const[t,n]of Object.entries(e))r(t,n,!1);for(const[t,e]of Object.entries(n))r(t,e,!0);return t}var z=Object.freeze({__proto__:null,bitGet:(t,e)=>t>>BigInt(e)&R,bitLen(t){let e;for(e=0;t>w;t>>=R,e+=1);return e},bitMask:U,bitSet:(t,e,n)=>t|(n?R:w)<<BigInt(e),bytesToHex:T,bytesToNumberBE:k,bytesToNumberLE:x,concatBytes:q,createHmacDrbg:F,ensureBytes:P,equalBytes(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n},hexToBytes:O,hexToNumber:B,isBytes:v,numberToBytesBE:D,numberToBytesLE:L,numberToHexUnpadded:C,numberToVarBytesBE:t=>O(C(t)),utf8ToBytes(t){if("string"!=typeof t)throw Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))},validateObject:j});const V=BigInt(0),K=BigInt(1),Z=BigInt(2),Y=BigInt(3),W=BigInt(4),G=BigInt(5),J=BigInt(8);function Q(t,e){const n=t%e;return n>=V?n:e+n}function X(t,e,n){if(n<=V||e<V)throw Error("Expected power/modulo > 0");if(n===K)return V;let r=K;for(;e>V;)e&K&&(r=r*t%n),t=t*t%n,e>>=K;return r}function tt(t,e,n){let r=t;for(;e-- >V;)r*=r,r%=n;return r}function et(t,e){if(t===V||e<=V)throw Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=Q(t,e),r=e,i=V,s=K;for(;n!==V;){const t=r%n,e=i-s*(r/n);r=n,n=t,i=s,s=e}if(r!==K)throw Error("invert: does not exist");return Q(i,e)}BigInt(9),BigInt(16);const nt=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rt(t,e){const n=void 0!==e?e:t.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function it(t){if("bigint"!=typeof t)throw Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function st(t){const e=it(t);return e+Math.ceil(e/2)}const ot=BigInt(0),at=BigInt(1);function ct(t){return j(t.Fp,nt.reduce(((t,e)=>(t[e]="function",t)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),j(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...rt(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const{bytesToNumberBE:ht,hexToBytes:dt}=z,lt={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){const{Err:e}=lt;if(t.length<2||2!==t[0])throw new e("Invalid signature integer tag");const n=t[1],r=t.subarray(2,n+2);if(!n||r.length!==n)throw new e("Invalid signature integer: wrong length");if(128&r[0])throw new e("Invalid signature integer: negative");if(0===r[0]&&!(128&r[1]))throw new e("Invalid signature integer: unnecessary leading zero");return{d:ht(r),l:t.subarray(n+2)}},toSig(t){const{Err:e}=lt,n="string"==typeof t?dt(t):t;if(!v(n))throw Error("ui8a expected");let r=n.length;if(r<2||48!=n[0])throw new e("Invalid signature tag");if(n[1]!==r-2)throw new e("Invalid signature: incorrect length");const{d:i,l:s}=lt._parseInt(n.subarray(2)),{d:o,l:a}=lt._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(t){const e=t=>8&Number.parseInt(t[0],16)?"00"+t:t,n=t=>{const e=t.toString(16);return 1&e.length?"0"+e:e},r=e(n(t.s)),i=e(n(t.r)),s=r.length/2,o=i.length/2,a=n(s),c=n(o);return`30${n(o+s+4)}02${c}${i}02${a}${r}`}},ut=BigInt(0),ft=BigInt(1);BigInt(2);const gt=BigInt(3);BigInt(4);class pt extends u{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,function(t){if("function"!=typeof t||"function"!=typeof t.create)throw Error("Hash should be wrapped by utils.wrapConstructor");i(t.outputLen),i(t.blockLen)}(t);const n=l(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,s=new Uint8Array(r);s.set(n.length>r?t.create().update(n).digest():n);for(let t=0;t<s.length;t++)s[t]^=54;this.iHash.update(s),this.oHash=t.create();for(let t=0;t<s.length;t++)s[t]^=106;this.oHash.update(s),s.fill(0)}update(t){return o(this),this.iHash.update(t),this}digestInto(t){o(this),s(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:e,iHash:n,finished:r,destroyed:i,blockLen:s,outputLen:o}=this;return t.finished=r,t.destroyed=i,t.blockLen=s,t.outputLen=o,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const yt=(t,e,n)=>new pt(t,e).update(n).digest();function mt(t){return{hash:t,hmac:(e,...n)=>yt(t,e,function(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];if(!c(r))throw Error("Uint8Array expected");e+=r.length}const n=new Uint8Array(e);for(let e=0,r=0;e<t.length;e++){const i=t[e];n.set(i,r),r+=i.length}return n}(...n)),randomBytes:f}}yt.create=(t,e)=>new pt(t,e);const _t=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),bt=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Et=BigInt(1),wt=BigInt(2),Rt=(t,e)=>(t+e/wt)/e;function At(t){const e=_t,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),h=t*t*t%e,d=h*h*t%e,l=tt(d,n,e)*d%e,u=tt(l,n,e)*d%e,f=tt(u,wt,e)*h%e,g=tt(f,i,e)*f%e,p=tt(g,s,e)*g%e,y=tt(p,a,e)*p%e,m=tt(y,c,e)*y%e,_=tt(m,a,e)*p%e,b=tt(_,n,e)*d%e,E=tt(b,o,e)*g%e,w=tt(E,r,e)*h%e,R=tt(w,wt,e);if(!vt.eql(vt.sqr(R),t))throw Error("Cannot find square root");return R}const vt=function(t,e,n=!1,r={}){if(t<=V)throw Error("Expected Field ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=rt(t,e);if(s>2048)throw Error("Field lengths over 2048 bytes are not supported");const o=function(t){if(t%W===Y){const e=(t+K)/W;return function(t,n){const r=t.pow(n,e);if(!t.eql(t.sqr(r),n))throw Error("Cannot find square root");return r}}if(t%J===G){const e=(t-G)/J;return function(t,n){const r=t.mul(n,Z),i=t.pow(r,e),s=t.mul(n,i),o=t.mul(t.mul(s,Z),i),a=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),n))throw Error("Cannot find square root");return a}}return function(t){const e=(t-K)/Z;let n,r,i;for(n=t-K,r=0;n%Z===V;n/=Z,r++);for(i=Z;i<t&&X(i,e,t)!==t-K;i++);if(1===r){const e=(t+K)/W;return(t,n)=>{const r=t.pow(n,e);if(!t.eql(t.sqr(r),n))throw Error("Cannot find square root");return r}}const s=(n+K)/Z;return(t,o)=>{if(t.pow(o,e)===t.neg(t.ONE))throw Error("Cannot find square root");let a=r,c=t.pow(t.mul(t.ONE,i),n),h=t.pow(o,s),d=t.pow(o,n);for(;!t.eql(d,t.ONE);){if(t.eql(d,t.ZERO))return t.ZERO;let e=1;for(let n=t.sqr(d);e<a&&!t.eql(n,t.ONE);e++)n=t.sqr(n);const n=t.pow(c,K<<BigInt(a-e-1));c=t.sqr(n),h=t.mul(h,n),d=t.mul(d,c),a=e}return h}}(t)}(t),a=Object.freeze({ORDER:t,BITS:i,BYTES:s,MASK:U(i),ZERO:V,ONE:K,create:e=>Q(e,t),isValid(e){if("bigint"!=typeof e)throw Error("Invalid field element: expected bigint, got "+typeof e);return V<=e&&e<t},is0:t=>t===V,isOdd:t=>(t&K)===K,neg:e=>Q(-e,t),eql:(t,e)=>t===e,sqr:e=>Q(e*e,t),add:(e,n)=>Q(e+n,t),sub:(e,n)=>Q(e-n,t),mul:(e,n)=>Q(e*n,t),pow:(t,e)=>function(t,e,n){if(n<V)throw Error("Expected power > 0");if(n===V)return t.ONE;if(n===K)return e;let r=t.ONE,i=e;for(;n>V;)n&K&&(r=t.mul(r,i)),i=t.sqr(i),n>>=K;return r}(a,t,e),div:(e,n)=>Q(e*et(n,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>et(e,t),sqrt:r.sqrt||(t=>o(a,t)),invertBatch:t=>function(t,e){const n=Array(e.length),r=e.reduce(((e,r,i)=>t.is0(r)?e:(n[i]=e,t.mul(e,r))),t.ONE),i=t.inv(r);return e.reduceRight(((e,r,i)=>t.is0(r)?e:(n[i]=t.mul(e,n[i]),t.mul(e,r))),i),n}(a,t),cmov:(t,e,n)=>n?e:t,toBytes:t=>n?L(t,s):D(t,s),fromBytes(t){if(t.length!==s)throw Error(`Fp.fromBytes: expected ${s}, got ${t.length}`);return n?x(t):k(t)}});return Object.freeze(a)}(_t,void 0,void 0,{sqrt:At}),St=function(t,e){const n=e=>function(t){const e=function(t){const e=ct(t);return j(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}(t),{Fp:n,n:r}=e,i=n.BYTES+1,s=2*n.BYTES+1;function o(t){return Q(t,r)}function a(t){return et(t,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:d,isWithinCurveOrder:l}=function(t){const e=function(t){const e=ct(t);j(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:i}=e;if(n){if(!r.eql(i,r.ZERO))throw Error("Endomorphism can only be defined for Koblitz curves that have a=0");if("object"!=typeof n||"bigint"!=typeof n.beta||"function"!=typeof n.splitScalar)throw Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}(t),{Fp:n}=e,r=e.toBytes||((t,e)=>{const r=e.toAffine();return q(Uint8Array.from([4]),n.toBytes(r.x),n.toBytes(r.y))}),i=e.fromBytes||(t=>{const e=t.subarray(1);return{x:n.fromBytes(e.subarray(0,n.BYTES)),y:n.fromBytes(e.subarray(n.BYTES,2*n.BYTES))}});function s(t){const{a:r,b:i}=e,s=n.sqr(t),o=n.mul(s,t);return n.add(n.add(o,n.mul(t,r)),i)}if(!n.eql(n.sqr(e.Gy),s(e.Gx)))throw Error("bad generator point: equation left != right");function o(t){return"bigint"==typeof t&&ut<t&&t<e.n}function a(t){if(!o(t))throw Error("Expected valid bigint: 0 < bigint < curve.n")}function c(t){const{allowedPrivateKeyLengths:n,nByteLength:r,wrapPrivateKey:i,n:s}=e;if(n&&"bigint"!=typeof t){if(v(t)&&(t=T(t)),"string"!=typeof t||!n.includes(t.length))throw Error("Invalid key");t=t.padStart(2*r,"0")}let o;try{o="bigint"==typeof t?t:k(P("private key",t,r))}catch(e){throw Error(`private key must be ${r} bytes, hex or bigint, not ${typeof t}`)}return i&&(o=Q(o,s)),a(o),o}const h=new Map;function d(t){if(!(t instanceof l))throw Error("ProjectivePoint expected")}class l{constructor(t,e,r){if(this.px=t,this.py=e,this.pz=r,null==t||!n.isValid(t))throw Error("x required");if(null==e||!n.isValid(e))throw Error("y required");if(null==r||!n.isValid(r))throw Error("z required")}static fromAffine(t){const{x:e,y:r}=t||{};if(!t||!n.isValid(e)||!n.isValid(r))throw Error("invalid affine point");if(t instanceof l)throw Error("projective point not allowed");const i=t=>n.eql(t,n.ZERO);return i(e)&&i(r)?l.ZERO:new l(e,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(t){const e=n.invertBatch(t.map((t=>t.pz)));return t.map(((t,n)=>t.toAffine(e[n]))).map(l.fromAffine)}static fromHex(t){const e=l.fromAffine(i(P("pointHex",t)));return e.assertValidity(),e}static fromPrivateKey(t){return l.BASE.multiply(c(t))}_setWindowSize(t){this._WINDOW_SIZE=t,h.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!n.is0(this.py))return;throw Error("bad point: ZERO")}const{x:t,y:r}=this.toAffine();if(!n.isValid(t)||!n.isValid(r))throw Error("bad point: x or y not FE");const i=n.sqr(r),o=s(t);if(!n.eql(i,o))throw Error("bad point: equation left != right");if(!this.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:t}=this.toAffine();if(n.isOdd)return!n.isOdd(t);throw Error("Field doesn't support isOdd")}equals(t){d(t);const{px:e,py:r,pz:i}=this,{px:s,py:o,pz:a}=t,c=n.eql(n.mul(e,a),n.mul(s,i)),h=n.eql(n.mul(r,a),n.mul(o,i));return c&&h}negate(){return new l(this.px,n.neg(this.py),this.pz)}double(){const{a:t,b:r}=e,i=n.mul(r,gt),{px:s,py:o,pz:a}=this;let c=n.ZERO,h=n.ZERO,d=n.ZERO,u=n.mul(s,s),f=n.mul(o,o),g=n.mul(a,a),p=n.mul(s,o);return p=n.add(p,p),d=n.mul(s,a),d=n.add(d,d),c=n.mul(t,d),h=n.mul(i,g),h=n.add(c,h),c=n.sub(f,h),h=n.add(f,h),h=n.mul(c,h),c=n.mul(p,c),d=n.mul(i,d),g=n.mul(t,g),p=n.sub(u,g),p=n.mul(t,p),p=n.add(p,d),d=n.add(u,u),u=n.add(d,u),u=n.add(u,g),u=n.mul(u,p),h=n.add(h,u),g=n.mul(o,a),g=n.add(g,g),u=n.mul(g,p),c=n.sub(c,u),d=n.mul(g,f),d=n.add(d,d),d=n.add(d,d),new l(c,h,d)}add(t){d(t);const{px:r,py:i,pz:s}=this,{px:o,py:a,pz:c}=t;let h=n.ZERO,u=n.ZERO,f=n.ZERO;const g=e.a,p=n.mul(e.b,gt);let y=n.mul(r,o),m=n.mul(i,a),_=n.mul(s,c),b=n.add(r,i),E=n.add(o,a);b=n.mul(b,E),E=n.add(y,m),b=n.sub(b,E),E=n.add(r,s);let w=n.add(o,c);return E=n.mul(E,w),w=n.add(y,_),E=n.sub(E,w),w=n.add(i,s),h=n.add(a,c),w=n.mul(w,h),h=n.add(m,_),w=n.sub(w,h),f=n.mul(g,E),h=n.mul(p,_),f=n.add(h,f),h=n.sub(m,f),f=n.add(m,f),u=n.mul(h,f),m=n.add(y,y),m=n.add(m,y),_=n.mul(g,_),E=n.mul(p,E),m=n.add(m,_),_=n.sub(y,_),_=n.mul(g,_),E=n.add(E,_),y=n.mul(m,E),u=n.add(u,y),y=n.mul(w,E),h=n.mul(b,h),h=n.sub(h,y),y=n.mul(b,m),f=n.mul(w,f),f=n.add(f,y),new l(h,u,f)}subtract(t){return this.add(t.negate())}is0(){return this.equals(l.ZERO)}wNAF(t){return f.wNAFCached(this,h,t,(t=>{const e=n.invertBatch(t.map((t=>t.pz)));return t.map(((t,n)=>t.toAffine(e[n]))).map(l.fromAffine)}))}multiplyUnsafe(t){const r=l.ZERO;if(t===ut)return r;if(a(t),t===ft)return this;const{endo:i}=e;if(!i)return f.unsafeLadder(this,t);let{k1neg:s,k1:o,k2neg:c,k2:h}=i.splitScalar(t),d=r,u=r,g=this;for(;o>ut||h>ut;)o&ft&&(d=d.add(g)),h&ft&&(u=u.add(g)),g=g.double(),o>>=ft,h>>=ft;return s&&(d=d.negate()),c&&(u=u.negate()),u=new l(n.mul(u.px,i.beta),u.py,u.pz),d.add(u)}multiply(t){a(t);let r,i,s=t;const{endo:o}=e;if(o){const{k1neg:t,k1:e,k2neg:a,k2:c}=o.splitScalar(s);let{p:h,f:d}=this.wNAF(e),{p:u,f:g}=this.wNAF(c);h=f.constTimeNegate(t,h),u=f.constTimeNegate(a,u),u=new l(n.mul(u.px,o.beta),u.py,u.pz),r=h.add(u),i=d.add(g)}else{const{p:t,f:e}=this.wNAF(s);r=t,i=e}return l.normalizeZ([r,i])[0]}multiplyAndAddUnsafe(t,e,n){const r=l.BASE,i=(t,e)=>e!==ut&&e!==ft&&t.equals(r)?t.multiply(e):t.multiplyUnsafe(e),s=i(this,e).add(i(t,n));return s.is0()?void 0:s}toAffine(t){const{px:e,py:r,pz:i}=this,s=this.is0();null==t&&(t=s?n.ONE:n.inv(i));const o=n.mul(e,t),a=n.mul(r,t),c=n.mul(i,t);if(s)return{x:n.ZERO,y:n.ZERO};if(!n.eql(c,n.ONE))throw Error("invZ was invalid");return{x:o,y:a}}isTorsionFree(){const{h:t,isTorsionFree:n}=e;if(t===ft)return!0;if(n)return n(l,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:t,clearCofactor:n}=e;return t===ft?this:n?n(l,this):this.multiplyUnsafe(e.h)}toRawBytes(t=!0){return this.assertValidity(),r(l,this,t)}toHex(t=!0){return T(this.toRawBytes(t))}}l.BASE=new l(e.Gx,e.Gy,n.ONE),l.ZERO=new l(n.ZERO,n.ONE,n.ZERO);const u=e.nBitLength,f=function(t,e){const n=(t,e)=>{const n=e.negate();return t?n:e},r=t=>({windows:Math.ceil(e/t)+1,windowSize:2**(t-1)});return{constTimeNegate:n,unsafeLadder(e,n){let r=t.ZERO,i=e;for(;n>ot;)n&at&&(r=r.add(i)),i=i.double(),n>>=at;return r},precomputeWindow(t,e){const{windows:n,windowSize:i}=r(e),s=[];let o=t,a=o;for(let t=0;t<n;t++){a=o,s.push(a);for(let t=1;t<i;t++)a=a.add(o),s.push(a);o=a.double()}return s},wNAF(e,i,s){const{windows:o,windowSize:a}=r(e);let c=t.ZERO,h=t.BASE;const d=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let t=0;t<o;t++){const e=t*a;let r=Number(s&d);s>>=u,r>a&&(r-=l,s+=at);const o=e,f=e+Math.abs(r)-1,g=t%2!=0,p=r<0;0===r?h=h.add(n(g,i[o])):c=c.add(n(p,i[f]))}return{p:c,f:h}},wNAFCached(t,e,n,r){const i=t._WINDOW_SIZE||1;let s=e.get(t);return s||(s=this.precomputeWindow(t,i),1!==i&&e.set(t,r(s))),this.wNAF(i,s,n)}}}(l,e.endo?Math.ceil(u/2):u);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:o}}({...e,toBytes(t,e,r){const i=e.toAffine(),s=n.toBytes(i.x),o=q;return r?o(Uint8Array.from([e.hasEvenY()?2:3]),s):o(Uint8Array.from([4]),s,n.toBytes(i.y))},fromBytes(t){const e=t.length,r=t[0],o=t.subarray(1);if(e!==i||2!==r&&3!==r){if(e===s&&4===r)return{x:n.fromBytes(o.subarray(0,n.BYTES)),y:n.fromBytes(o.subarray(n.BYTES,2*n.BYTES))};throw Error(`Point of length ${e} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}{const t=k(o);if(!(ut<(a=t)&&a<n.ORDER))throw Error("Point is not on curve");const e=d(t);let i=n.sqrt(e);return!(1&~r)!=((i&ft)===ft)&&(i=n.neg(i)),{x:t,y:i}}var a}}),u=t=>T(D(t,e.nByteLength));function f(t){return t>r>>ft}const g=(t,e,n)=>k(t.slice(e,n));class p{constructor(t,e,n){this.r=t,this.s=e,this.recovery=n,this.assertValidity()}static fromCompact(t){const n=e.nByteLength;return t=P("compactSignature",t,2*n),new p(g(t,0,n),g(t,n,2*n))}static fromDER(t){const{r:e,s:n}=lt.toSig(P("DER",t));return new p(e,n)}assertValidity(){if(!l(this.r))throw Error("r must be 0 < r < CURVE.n");if(!l(this.s))throw Error("s must be 0 < s < CURVE.n")}addRecoveryBit(t){return new p(this.r,this.s,t)}recoverPublicKey(t){const{r:r,s:i,recovery:s}=this,h=b(P("msgHash",t));if(null==s||![0,1,2,3].includes(s))throw Error("recovery id invalid");const d=2===s||3===s?r+e.n:r;if(d>=n.ORDER)throw Error("recovery id 2 or 3 invalid");const l=1&s?"03":"02",f=c.fromHex(l+u(d)),g=a(d),p=o(-h*g),y=o(i*g),m=c.BASE.multiplyAndAddUnsafe(f,p,y);if(!m)throw Error("point at infinify");return m.assertValidity(),m}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return O(this.toDERHex())}toDERHex(){return lt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return O(this.toCompactHex())}toCompactHex(){return u(this.r)+u(this.s)}}const y={isValidPrivateKey(t){try{return h(t),!0}catch(t){return!1}},normPrivateKeyToScalar:h,randomPrivateKey(){const t=st(e.n);return function(t,e,n=!1){const r=t.length,i=it(e),s=st(e);if(r<16||r<s||r>1024)throw Error(`expected ${s}-1024 bytes of input, got ${r}`);const o=Q(n?k(t):x(t),e-K)+K;return n?L(o,i):D(o,i)}(e.randomBytes(t),e.n)},precompute:(t=8,e=c.BASE)=>(e._setWindowSize(t),e.multiply(BigInt(3)),e)};function m(t){const e=v(t),n="string"==typeof t,r=(e||n)&&t.length;return e?r===i||r===s:n?r===2*i||r===2*s:t instanceof c}const _=e.bits2int||(t=>{const n=k(t),r=8*t.length-e.nBitLength;return r>0?n>>BigInt(r):n}),b=e.bits2int_modN||(t=>o(_(t))),E=U(e.nBitLength);function w(t){if("bigint"!=typeof t)throw Error("bigint expected");if(!(ut<=t&&t<E))throw Error("bigint expected < 2^"+e.nBitLength);return D(t,e.nByteLength)}function R(t,r,i=A){if(["recovered","canonical"].some((t=>t in i)))throw Error("sign() legacy options not supported");const{hash:s,randomBytes:d}=e;let{lowS:u,prehash:g,extraEntropy:y}=i;null==u&&(u=!0),t=P("msgHash",t),g&&(t=P("prehashed msgHash",s(t)));const m=b(t),E=h(r),R=[w(E),w(m)];if(null!=y){const t=!0===y?d(n.BYTES):y;R.push(P("extraEntropy",t))}const v=q(...R),S=m;return{seed:v,k2sig(t){const e=_(t);if(!l(e))return;const n=a(e),r=c.BASE.multiply(e).toAffine(),i=o(r.x);if(i===ut)return;const s=o(n*o(S+i*E));if(s===ut)return;let h=(r.x===i?0:2)|Number(r.y&ft),d=s;return u&&f(s)&&(d=function(t){return f(t)?o(-t):t}(s),h^=1),new p(i,d,h)}}}const A={lowS:e.lowS,prehash:!1},S={lowS:e.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:e,getPublicKey:(t,e=!0)=>c.fromPrivateKey(t).toRawBytes(e),getSharedSecret(t,e,n=!0){if(m(t))throw Error("first arg must be private key");if(!m(e))throw Error("second arg must be public key");return c.fromHex(e).multiply(h(t)).toRawBytes(n)},sign(t,n,r=A){const{seed:i,k2sig:s}=R(t,n,r),o=e;return F(o.hash.outputLen,o.nByteLength,o.hmac)(i,s)},verify(t,n,r,i=S){const s=t;if(n=P("msgHash",n),r=P("publicKey",r),"strict"in i)throw Error("options.strict was renamed to lowS");const{lowS:h,prehash:d}=i;let l,u;try{if("string"==typeof s||v(s))try{l=p.fromDER(s)}catch(t){if(!(t instanceof lt.Err))throw t;l=p.fromCompact(s)}else{if("object"!=typeof s||"bigint"!=typeof s.r||"bigint"!=typeof s.s)throw Error("PARSE");{const{r:t,s:e}=s;l=new p(t,e)}}u=c.fromHex(r)}catch(t){if("PARSE"===t.message)throw Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(h&&l.hasHighS())return!1;d&&(n=e.hash(n));const{r:f,s:g}=l,y=b(n),m=a(g),_=o(y*m),E=o(f*m),w=c.BASE.multiplyAndAddUnsafe(u,_,E)?.toAffine();return!!w&&o(w.x)===f},ProjectivePoint:c,Signature:p,utils:y}}({...t,...mt(e)});return Object.freeze({...n(e),create:n})}({a:BigInt(0),b:BigInt(7),Fp:vt,n:bt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(t){const e=bt,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Et*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=Rt(s*t,e),c=Rt(-r*t,e);let h=Q(t-a*n-c*i,e),d=Q(-a*r-c*s,e);const l=h>o,u=d>o;if(l&&(h=e-h),u&&(d=e-d),h>o||d>o)throw Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:l,k1:h,k2neg:u,k2:d}}}},E),Tt=BigInt(0),Ct=t=>"bigint"==typeof t&&Tt<t&&t<_t,Bt=t=>"bigint"==typeof t&&Tt<t&&t<bt,It={};function Nt(t,...e){let n=It[t];if(void 0===n){const e=E(Uint8Array.from(t,(t=>t.charCodeAt(0))));n=q(e,e),It[t]=n}return E(q(n,...e))}const Ot=t=>t.toRawBytes(!0).slice(1),kt=t=>D(t,32),xt=t=>Q(t,_t),Dt=t=>Q(t,bt),Lt=St.ProjectivePoint,Pt=(t,e,n)=>Lt.BASE.multiplyAndAddUnsafe(t,e,n);function qt(t){let e=St.utils.normPrivateKeyToScalar(t),n=Lt.fromPrivateKey(e);return{scalar:n.hasEvenY()?e:Dt(-e),bytes:Ot(n)}}function Ut(t){if(!Ct(t))throw Error("bad x: need 0 < x < p");const e=xt(t*t);let n=At(xt(e*t+BigInt(7)));n%wt!==Tt&&(n=xt(-n));const r=new Lt(t,n,Et);return r.assertValidity(),r}function Ht(...t){return Dt(k(Nt("BIP0340/challenge",...t)))}function $t(t,e,n){const r=P("signature",t,64),i=P("message",e),s=P("publicKey",n,32);try{const t=Ut(k(s)),e=k(r.subarray(0,32));if(!Ct(e))return!1;const n=k(r.subarray(32,64));if(!Bt(n))return!1;const o=Ht(kt(e),Ot(t),i),a=Pt(t,n,Dt(-o));return!(!a||!a.hasEvenY()||a.toAffine().x!==e)}catch(t){return!1}}const Ft={getPublicKey:function(t){return qt(t).bytes},sign:function(t,e,n=f(32)){const r=P("message",t),{bytes:i,scalar:s}=qt(e),o=P("auxRand",n,32),a=kt(s^k(Nt("BIP0340/aux",o))),c=Nt("BIP0340/nonce",a,i,r),h=Dt(k(c));if(h===Tt)throw Error("sign failed: k is zero");const{bytes:d,scalar:l}=qt(h),u=Ht(d,i,r),g=new Uint8Array(64);if(g.set(d,0),g.set(kt(Dt(l+u*s)),32),!$t(g,r,i))throw Error("sign: Invalid signature produced");return g},verify:$t,utils:{randomPrivateKey:St.utils.randomPrivateKey,lift_x:Ut,pointToBytes:Ot,numberToBytesBE:D,bytesToNumberBE:k,taggedHash:Nt,mod:Q}};function Mt(t){const e=new Uint8Array(t);for(let n=0;n<t;n++)e[n]=256*Math.random()|0;return e}function jt(){if("undefined"==typeof globalThis)return null;const t={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return t.RTCPeerConnection?t:null}function zt(t,e){return Object.defineProperty(t,"code",{value:e,enumerable:!0,configurable:!0}),t}function Vt(t){return t.replace(/a=ice-options:trickle\s\n/g,"")}class Kt{constructor(t={}){if(this._map=new Map,this._id=Mt(4).toString("hex").slice(0,7),this._doDebug=t.debug,this._debug("new peer %o",t),this.channelName=t.initiator?t.channelName||Mt(20).toString("hex"):null,this.initiator=t.initiator||!1,this.channelConfig=t.channelConfig||Kt.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Kt.config,t.config),this.offerOptions=t.offerOptions||{},this.answerOptions=t.answerOptions||{},this.sdpTransform=t.sdpTransform||(t=>t),this.streams=t.streams||(t.stream?[t.stream]:[]),this.trickle=void 0===t.trickle||t.trickle,this.allowHalfTrickle=void 0!==t.allowHalfTrickle&&t.allowHalfTrickle,this.iceCompleteTimeout=t.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=t.wrtc&&"object"==typeof t.wrtc?t.wrtc:jt(),!this._wrtc)throw"undefined"==typeof window?zt(Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):zt(Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(t){return void this.destroy(zt(t,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=t=>{this._onIceCandidate(t)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch((t=>{this.destroy(zt(t,"ERR_PC_PEER_IDENTITY"))})),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=t=>{this._setupData(t)},this.streams&&this.streams.forEach((t=>{this.addStream(t)})),this._pc.ontrack=t=>{this._onTrack(t)},this._debug("initial negotiation"),this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(t){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof t)try{t=JSON.parse(t)}catch(e){t={}}this._debug("signal()"),t.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),t.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(t.transceiverRequest.kind,t.transceiverRequest.init)),t.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(t.candidate):this._pendingCandidates.push(t.candidate)),t.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(t)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((t=>{this._addIceCandidate(t)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((t=>{this.destroy(zt(t,"ERR_SET_REMOTE_DESCRIPTION"))})),t.sdp||t.candidate||t.renegotiate||t.transceiverRequest||this.destroy(zt(Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(t){const e=new this._wrtc.RTCIceCandidate(t);this._pc.addIceCandidate(e).catch((t=>{!e.address||e.address.endsWith(".local")?console.warn("Ignoring unsupported ICE candidate."):this.destroy(zt(t,"ERR_ADD_ICE_CANDIDATE"))}))}send(t){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(t)}}addTransceiver(t,e){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(t,e),this._needsNegotiation()}catch(t){this.destroy(zt(t,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:t,init:e}})}}addStream(t){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),t.getTracks().forEach((e=>{this.addTrack(e,t)}))}}addTrack(t,e){if(this.destroying)return;if(this.destroyed)throw zt(Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(t)||new Map;let r=n.get(e);if(r)throw r.removed?zt(Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):zt(Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");r=this._pc.addTrack(t,e),n.set(e,r),this._senderMap.set(t,n),this._needsNegotiation()}replaceTrack(t,e,n){if(this.destroying)return;if(this.destroyed)throw zt(Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const r=this._senderMap.get(t),i=r?r.get(n):null;if(!i)throw zt(Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");e&&this._senderMap.set(e,r),null!=i.replaceTrack?i.replaceTrack(e):this.destroy(zt(Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(t,e){if(this.destroying)return;if(this.destroyed)throw zt(Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const n=this._senderMap.get(t),r=n?n.get(e):null;if(!r)throw zt(Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{r.removed=!0,this._pc.removeTrack(r)}catch(t){"NS_ERROR_UNEXPECTED"===t.name?this._sendersAwaitingStable.push(r):this.destroy(zt(t,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(t){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),t.getTracks().forEach((e=>{this.removeTrack(e,t)}))}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask((()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1})))}negotiate(){if(!this.destroying){if(this.destroyed)throw zt(Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout((()=>{this._createOffer()}),0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(t){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",t&&(t.message||t)),queueMicrotask((()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",t&&(t.message||t)),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(t){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(t){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,t&&this.emit("error",t),this.emit("close")})))}_setupData(t){if(!t.channel)return this.destroy(zt(Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=t.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=65536),this.channelName=this._channel.label,this._channel.onmessage=t=>{this._onChannelMessage(t)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=t=>{this.destroy(zt(t,"ERR_DATA_CHANNEL"))};let e=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(e&&this._onChannelClose(),e=!0):e=!1}),5e3)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((t=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(t.sdp=Vt(t.sdp)),t.sdp=this.sdpTransform(t.sdp);const e=()=>{if(this.destroyed)return;const e=this._pc.localDescription||t;this._debug("signal"),this.emit("signal",{type:e.type,sdp:e.sdp})};this._pc.setLocalDescription(t).then((()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?e():this.once("_iceComplete",e))})).catch((t=>{this.destroy(zt(t,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((t=>{this.destroy(zt(t,"ERR_CREATE_OFFER"))}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((t=>{t.mid||!t.sender.track||t.requested||(t.requested=!0,this.addTransceiver(t.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((t=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(t.sdp=Vt(t.sdp)),t.sdp=this.sdpTransform(t.sdp);const e=()=>{if(this.destroyed)return;const e=this._pc.localDescription||t;this._debug("signal"),this.emit("signal",{type:e.type,sdp:e.sdp}),this.initiator||this._requestMissingTransceivers()};this._pc.setLocalDescription(t).then((()=>{this.destroyed||(this.trickle||this._iceComplete?e():this.once("_iceComplete",e))})).catch((t=>{this.destroy(zt(t,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((t=>{this.destroy(zt(t,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(zt(Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const t=this._pc.iceConnectionState,e=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",t,e),this.emit("iceStateChange",t,e),"connected"!==t&&"completed"!==t||(this._pcReady=!0,this._maybeReady()),"failed"===t&&this.destroy(zt(Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===t&&this.destroy(zt(Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(t){const e=t=>("[object Array]"==={}.toString.call(t.values)&&t.values.forEach((e=>{Object.assign(t,e)})),t);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((n=>{const r=[];n.forEach((t=>{r.push(e(t))})),t(null,r)}),(e=>t(e))):this._pc.getStats.length>0?this._pc.getStats((n=>{if(this.destroyed)return;const r=[];n.result().forEach((t=>{const n={};t.names().forEach((e=>{n[e]=t.stat(e)})),n.id=t.id,n.type=t.type,n.timestamp=t.timestamp,r.push(e(n))})),t(null,r)}),(e=>t(e))):t(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const t=()=>{this.destroyed||this.getStats(((e,n)=>{if(this.destroyed)return;e&&(n=[]);const r={},i={},s={};let o=!1;n.forEach((t=>{"remotecandidate"!==t.type&&"remote-candidate"!==t.type||(r[t.id]=t),"localcandidate"!==t.type&&"local-candidate"!==t.type||(i[t.id]=t),"candidatepair"!==t.type&&"candidate-pair"!==t.type||(s[t.id]=t)}));const a=t=>{o=!0;let e=i[t.localCandidateId];e&&(e.ip||e.address)?(this.localAddress=e.ip||e.address,this.localPort=Number(e.port)):e&&e.ipAddress?(this.localAddress=e.ipAddress,this.localPort=Number(e.portNumber)):"string"==typeof t.googLocalAddress&&(e=t.googLocalAddress.split(":"),this.localAddress=e[0],this.localPort=Number(e[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=r[t.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=Number(n.port)):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=Number(n.portNumber)):"string"==typeof t.googRemoteAddress&&(n=t.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=Number(n[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach((t=>{"transport"===t.type&&t.selectedCandidatePairId&&a(s[t.selectedCandidatePairId]),("googCandidatePair"===t.type&&"true"===t.googActiveConnection||("candidatepair"===t.type||"candidate-pair"===t.type)&&t.selected)&&a(t)})),o||Object.keys(s).length&&!Object.keys(i).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(zt(e,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const t=this._cb;this._cb=null,t(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(t,100)}))};t()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>65536||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach((t=>{this._pc.removeTrack(t),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(t){this.destroyed||(t.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:t.candidate.candidate,sdpMLineIndex:t.candidate.sdpMLineIndex,sdpMid:t.candidate.sdpMid}}):t.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),t.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(t){if(this.destroyed)return;let e=t.data;e instanceof ArrayBuffer&&(e=new Uint8Array(e)),this.emit("data",e)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const t=this._cb;this._cb=null,t(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(t){this.destroyed||t.streams.forEach((e=>{this._debug("on track"),this.emit("track",t.track,e),this._remoteTracks.push({track:t.track,stream:e}),this._remoteStreams.some((t=>t.id===e.id))||(this._remoteStreams.push(e),queueMicrotask((()=>{this._debug("on stream"),this.emit("stream",e)})))}))}_debug(...t){this._doDebug&&(t[0]="["+this._id+"] "+t[0])}on(t,e){const n=this._map;n.has(t)||n.set(t,new Set),n.get(t).add(e)}off(t,e){const n=this._map,r=n.get(t);r&&(r.delete(e),0===r.size&&n.delete(t))}once(t,e){const n=(...r)=>{this.off(t,n),e(...r)};this.on(t,n)}emit(t,...e){const n=this._map;if(n.has(t))for(const r of n.get(t))try{r(...e)}catch(t){console.error(t)}}}Kt.WEBRTC_SUPPORT=!!jt(),Kt.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Kt.channelConfig={};const Zt=(t,e,n)=>{const r=new Kt({initiator:t,trickle:e,config:n}),i=t=>r.__earlyDataBuffer.push(t);return r.on(oe.data,i),r.__earlyDataBuffer=[],r.__drainEarlyData=t=>{r.off(oe.data,i),r.__earlyDataBuffer.forEach(t),delete r.__earlyDataBuffer,delete r.__drainEarlyData},r},Yt=t=>Array(t).fill().map((()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[Math.floor(62*Math.random())])).join(""),Wt="Trystero",Gt=Yt(20),{keys:Jt,values:Qt,entries:Xt,fromEntries:te}=Object,ee=()=>{},ne=t=>Error(`${Wt}: ${t}`),re=t=>(new TextEncoder).encode(t),ie=t=>(new TextDecoder).decode(t),se=t=>t.reduce(((t,e)=>t+e.toString(16).padStart(2,"0")),""),oe=te(["close","connect","data","error","signal","stream","track"].map((t=>[t,t]))),ae=Object.getPrototypeOf(Uint8Array),ce=16369,he=255,de="bufferedamountlow",le="AES-CBC",ue=async(t,e)=>{const n=crypto.getRandomValues(new Uint8Array(16));var r;return JSON.stringify({c:(r=await crypto.subtle.encrypt({name:le,iv:n},await t,re(e)),btoa(String.fromCharCode.apply(null,new Uint8Array(r)))),iv:[...n]})},fe=async(t,e)=>{const{c:n,iv:r}=JSON.parse(e);return ie(await crypto.subtle.decrypt({name:le,iv:new Uint8Array(r)},await t,(t=>{const e=atob(t);return new Uint8Array(e.length).map(((t,n)=>e.charCodeAt(n))).buffer})(n)))},ge={},pe=se(crypto.getRandomValues(new Uint8Array(32))),ye=se(Ft.getPublicKey(pe)),me={},_e=()=>Math.floor(Date.now()/1e3),be=["wss://relay.nostr.net","wss://relay.blackbyte.nl","wss://relay.piazza.today","wss://relay.exit.pub","wss://relay.nostr.band","wss://relay.damus.io","wss://nostr.mom","wss://relay.snort.social","wss://nostr.lu.ke","wss://relay.plebstr.com","wss://nostr.sathoarder.com","wss://nsrelay.assilvestrar.club","wss://nostrasia.casa","wss://relay.nostr.bg","wss://relay.nostrr.de","wss://relay.nostrss.re"],Ee=(we=ge,(t,e)=>{if(we[e])return we[e];if(!t)throw ne("requires a config map as the first argument");if(!t.appId&&!t.firebaseApp)throw ne("config map is missing appId field");if(!e)throw ne("namespace argument required");return we[e]=((t,e)=>{const n=t.password&&(async(t,e)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},re(`${t}:${e}`)),{name:le},!1,["encrypt","decrypt"]))(t.password,e),r=`trystero/${t.appId}/${e}`,i=`${r}/${Gt}`,s=Yt(64),o=Yt(64),a={},c={},h={},d=((t,e,n)=>(t.relayUrls||e).slice(0,t.relayUrls?t.relayUrls.length:t.relayRedundancy||4))(t,be),l=(t,e)=>{y(t,e),h[e]=t},u=t=>{delete a[t],delete c[t],delete h[t]},f=(t,e)=>JSON.stringify(["REQ",t,{kinds:[29333],since:_e(),"#x":[e]}]),g=t=>JSON.stringify(["CLOSE",t]),p=async(t,e)=>{const n={kind:29333,content:JSON.stringify(e),pubkey:ye,created_at:_e(),tags:[["x",t]]},r=se(new Uint8Array(await crypto.subtle.digest("SHA-256",re(JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content])))));return JSON.stringify(["EVENT",{...n,id:r,sig:se(await Ft.sign(r,pe))}])};let y=ee;return d.forEach((e=>{const d=new WebSocket(e);me[e]=d,d.addEventListener("open",(async()=>{d.send(f(s,r)),d.send(f(o,i)),d.send(await p(r,Gt))})),d.addEventListener("message",(async e=>{const[i,f,g,y]=JSON.parse(e.data);if("EVENT"!==i)return void("OK"!==i||g||console.warn(`${Wt}: relay failure from ${d.url} - ${y}`));const m=JSON.parse(g.content);if(f===s){const e=m;if(e!==Gt&&!h[e]&&!c[e]){c[e]=!0;const i=a[e]=Zt(!0,!1,t.rtcConfig);i.once(oe.signal,(async t=>{d.send(await p(`${r}/${e}`,{peerId:Gt,offer:n?{...t,sdp:await ue(n,t.sdp)}:t}))})),i.once(oe.connect,(()=>l(i,e))),i.once(oe.close,(()=>u(e)))}}else if(f===o){const{peerId:e,offer:i,answer:s}=m;if(a[e]&&s)return void a[e].signal(n?{...s,sdp:await fe(n,s.sdp)}:s);if(!i)return;const o=Zt(!1,!1,t.rtcConfig);o.once(oe.signal,(async t=>d.send(await p(`${r}/${e}`,{peerId:Gt,answer:n?{...t,sdp:await ue(n,t.sdp)}:t})))),o.once(oe.connect,(()=>l(o,e))),o.once(oe.close,(()=>u(e))),o.signal(i)}}))})),((t,e)=>{const n={},r={},i={},s={},o={},a={},c=(t,e)=>(t?Array.isArray(t)?t:[t]:Jt(n)).flatMap((t=>{const r=n[t];return r?e(t,r):(console.warn(`${Wt}: no peer with id ${t} found`),[])})),h=t=>{if(r[t])return[r[t].send,r[t].setOnComplete,r[t].setOnProgress];if(!t)throw ne("action type argument is required");const e=re(t);if(e.byteLength>12)throw ne(`action type string "${t}" (${e.byteLength}b) exceeds byte limit (12). Hint: choose a shorter name.`);const i=new Uint8Array(12);i.set(e);let s=0;return r[t]={onComplete:ee,onProgress:ee,setOnComplete:e=>r[t]={...r[t],onComplete:e},setOnProgress:e=>r[t]={...r[t],onProgress:e},async send(t,e,r,o){if(r&&"object"!=typeof r)throw ne("action meta argument must be an object");if(void 0===t)throw ne("action data cannot be undefined");const a="string"!=typeof t,h=t instanceof Blob,d=h||t instanceof ArrayBuffer||t instanceof ae;if(r&&!d)throw ne("action meta argument can only be used with binary data");const l=d?new Uint8Array(h?await t.arrayBuffer():t):re(a?JSON.stringify(t):t),u=r?re(JSON.stringify(r)):null,f=Math.ceil(l.byteLength/ce)+(r?1:0)||1,g=Array(f).fill().map(((t,e)=>{const n=e===f-1,o=r&&0===e,c=new Uint8Array(15+(o?u.byteLength:n?l.byteLength-ce*(f-(r?2:1)):ce));return c.set(i),c.set([s],12),c.set([n|o<<1|d<<2|a<<3],13),c.set([Math.round((e+1)/f*he)],14),c.set(r?o?u:l.subarray((e-1)*ce,e*ce):l.subarray(e*ce,(e+1)*ce),15),c}));return s=s+1&he,Promise.all(c(e,(async(t,e)=>{const i=e._channel;let s=0;for(;s<f;){const a=g[s];if(i.bufferedAmount>i.bufferedAmountLowThreshold&&await new Promise((t=>{const e=()=>{i.removeEventListener(de,e),t()};i.addEventListener(de,e)})),!n[t])break;e.send(a),s++,o&&o(a[14]/he,t,r)}})))}},[r[t].send,r[t].setOnComplete,r[t].setOnProgress]},d=(t,e)=>{const n=new Uint8Array(e),s=ie(n.subarray(0,12)).replaceAll("\0",""),[o]=n.subarray(12,13),[a]=n.subarray(13,14),[c]=n.subarray(14,15),h=n.subarray(15),d=!!(1&a),l=!!(2&a),u=!!(4&a),f=!!(8&a);if(!r[s])throw ne(`received message with unregistered type (${s})`);i[t]||(i[t]={}),i[t][s]||(i[t][s]={});let g=i[t][s][o];if(g||(g=i[t][s][o]={chunks:[]}),l?g.meta=JSON.parse(ie(h)):g.chunks.push(h),r[s].onProgress(c/he,t,g.meta),!d)return;const p=new Uint8Array(g.chunks.reduce(((t,e)=>t+e.byteLength),0));if(g.chunks.reduce(((t,e)=>(p.set(e,t),t+e.byteLength)),0),u)r[s].onComplete(p,t,g.meta);else{const e=ie(p);r[s].onComplete(f?JSON.parse(e):e,t)}delete i[t][s][o]},[l,u]=h("__91n6__"),[f,g]=h("__90n6__"),[p,y]=h("__516n4L__"),[m,_]=h("__57r34m__"),[b,E]=h("__7r4ck__");let w=ee,R=ee,A=ee,v=ee;return t(((t,e)=>{if(n[e])return;const r=d.bind(null,e);n[e]=t,t.on(oe.signal,(t=>p(t,e))),t.on(oe.close,(()=>(t=>{n[t]&&(delete n[t],delete i[t],delete s[t],R(t))})(e))),t.on(oe.data,r),t.on(oe.stream,(t=>{A(t,e,o[e]),delete o[e]})),t.on(oe.track,((t,n)=>{v(t,n,e,a[e]),delete a[e]})),t.on(oe.error,(t=>{"ERR_DATA_CHANNEL"!==t.code&&console.error(t)})),w(e),t.__drainEarlyData(r)})),u(((t,e)=>f("",e))),g(((t,e)=>{s[e]&&(s[e](),delete s[e])})),y(((t,e)=>{n[e]&&n[e].signal(t)})),_(((t,e)=>o[e]=t)),E(((t,e)=>a[e]=t)),{makeAction:h,async ping(t){if(!t)throw ne("ping() must be called with target peer ID");const e=Date.now();return l("",t),await new Promise((e=>s[t]=e)),Date.now()-e},leave(){Xt(n).forEach((([t,e])=>{e.destroy(),delete n[t]})),e()},getPeers:()=>te(Xt(n).map((([t,e])=>[t,e._pc]))),addStream:(t,e,n)=>c(e,(async(e,r)=>{n&&await m(n,e),r.addStream(t)})),removeStream:(t,e)=>c(e,((e,n)=>n.removeStream(t))),addTrack:(t,e,n,r)=>c(n,(async(n,i)=>{r&&await b(r,n),i.addTrack(t,e)})),removeTrack:(t,e,n)=>c(n,((n,r)=>r.removeTrack(t,e))),replaceTrack:(t,e,n,r,i)=>c(r,(async(r,s)=>{i&&await b(i,r),s.replaceTrack(t,e,n)})),onPeerJoin:t=>w=t,onPeerLeave:t=>R=t,onPeerStream:t=>A=t,onPeerTrack:t=>v=t}})((t=>y=t),(()=>{delete ge[e],Qt(me).forEach((t=>{t.send(g(s)),t.send(g(o))}))}))})(t,e)});var we}));
@@ -1 +0,0 @@
1
- ("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequirea18f.register("b1IkL",(function(e,t){var i,s;function n(e){const t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=256*Math.random()|0;return t}function r(){if("undefined"==typeof globalThis)return null;const e={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}function a(e,t){return Object.defineProperty(e,"code",{value:t,enumerable:!0,configurable:!0}),e}function o(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}i=e.exports,s=()=>M,Object.defineProperty(i,"joinRoom",{get:s,set:undefined,enumerable:!0,configurable:!0});class c{constructor(e={}){if(this._map=new Map,this._id=n(4).toString("hex").slice(0,7),this._doDebug=e.debug,this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||n(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||c.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},c.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:r(),!this._wrtc)throw"undefined"==typeof window?a(Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):a(Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void this.destroy(a(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch((e=>{this.destroy(a(e,"ERR_PC_PEER_IDENTITY"))})),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach((e=>{this.addStream(e)})),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this.destroying){if(this.destroyed)throw a(Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(a(e,"ERR_SET_REMOTE_DESCRIPTION"))})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(a(Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{!t.address||t.address.endsWith(".local")?console.warn("Ignoring unsupported ICE candidate."):this.destroy(a(e,"ERR_ADD_ICE_CANDIDATE"))}))}send(e){if(!this.destroying){if(this.destroyed)throw a(Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}addTransceiver(e,t){if(!this.destroying){if(this.destroyed)throw a(Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(a(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this.destroying){if(this.destroyed)throw a(Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),e.getTracks().forEach((t=>{this.addTrack(t,e)}))}}addTrack(e,t){if(this.destroying)return;if(this.destroyed)throw a(Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const i=this._senderMap.get(e)||new Map;let s=i.get(t);if(s)throw s.removed?a(Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):a(Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");s=this._pc.addTrack(e,t),i.set(t,s),this._senderMap.set(e,i),this._needsNegotiation()}replaceTrack(e,t,i){if(this.destroying)return;if(this.destroyed)throw a(Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const s=this._senderMap.get(e),n=s?s.get(i):null;if(!n)throw a(Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,s),null!=n.replaceTrack?n.replaceTrack(t):this.destroy(a(Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(e,t){if(this.destroying)return;if(this.destroyed)throw a(Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const i=this._senderMap.get(e),s=i?i.get(t):null;if(!s)throw a(Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{s.removed=!0,this._pc.removeTrack(s)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(s):this.destroy(a(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){if(!this.destroying){if(this.destroyed)throw a(Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),e.getTracks().forEach((t=>{this.removeTrack(t,e)}))}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask((()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1})))}negotiate(){if(!this.destroying){if(this.destroyed)throw a(Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout((()=>{this._createOffer()}),0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(e){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",e&&(e.message||e)),queueMicrotask((()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",e&&(e.message||e)),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(a(Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=65536),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{this.destroy(a(e,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=o(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(a(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.destroy(a(e,"ERR_CREATE_OFFER"))}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=o(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(a(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.destroy(a(e,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(a(Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(a(Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(a(Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"==={}.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((i=>{const s=[];i.forEach((e=>{s.push(t(e))})),e(null,s)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((i=>{if(this.destroyed)return;const s=[];i.result().forEach((e=>{const i={};e.names().forEach((t=>{i[t]=e.stat(t)})),i.id=e.id,i.type=e.type,i.timestamp=e.timestamp,s.push(t(i))})),e(null,s)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,i)=>{if(this.destroyed)return;t&&(i=[]);const s={},n={},r={};let o=!1;i.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(s[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(n[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(r[e.id]=e)}));const c=e=>{o=!0;let t=n[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let i=s[e.remoteCandidateId];i&&(i.ip||i.address)?(this.remoteAddress=i.ip||i.address,this.remotePort=Number(i.port)):i&&i.ipAddress?(this.remoteAddress=i.ipAddress,this.remotePort=Number(i.portNumber)):"string"==typeof e.googRemoteAddress&&(i=e.googRemoteAddress.split(":"),this.remoteAddress=i[0],this.remotePort=Number(i[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(i.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&c(r[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&c(e)})),o||Object.keys(r).length&&!Object.keys(n).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(a(t,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>65536||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=new Uint8Array(t)),this.emit("data",t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach((t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some((e=>e.id===t.id))||(this._remoteStreams.push(t),queueMicrotask((()=>{this._debug("on stream"),this.emit("stream",t)})))}))}_debug(...e){this._doDebug&&(e[0]="["+this._id+"] "+e[0])}on(e,t){const i=this._map;i.has(e)||i.set(e,new Set),i.get(e).add(t)}off(e,t){const i=this._map,s=i.get(e);s&&(s.delete(t),0===s.size&&i.delete(e))}once(e,t){const i=(...s)=>{this.off(e,i),t(...s)};this.on(e,i)}emit(e,...t){const i=this._map;if(i.has(e))for(const s of i.get(e))try{s(...t)}catch(e){console.error(e)}}}c.WEBRTC_SUPPORT=!!r(),c.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},c.channelConfig={};const d=(e,t,i)=>{const s=new c({initiator:e,trickle:t,config:i}),n=e=>s.__earlyDataBuffer.push(e);return s.on(R.data,n),s.__earlyDataBuffer=[],s.__drainEarlyData=e=>{s.off(R.data,n),s.__earlyDataBuffer.forEach(e),delete s.__earlyDataBuffer,delete s.__drainEarlyData},s},h=e=>Array(e).fill().map((()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[Math.floor(62*Math.random())])).join(""),l="Trystero",_=h(20),{keys:p,values:u,entries:g,fromEntries:f}=Object,y=()=>{},m=e=>Error(`${l}: ${e}`),b=e=>(new TextEncoder).encode(e),E=e=>(new TextDecoder).decode(e),R=f(["close","connect","data","error","signal","stream","track"].map((e=>[e,e]))),C=Object.getPrototypeOf(Uint8Array),w=16369,T=255,S="bufferedamountlow",A="AES-CBC",v=async(e,t)=>{const i=crypto.getRandomValues(new Uint8Array(16));var s;return JSON.stringify({c:(s=await crypto.subtle.encrypt({name:A,iv:i},await e,b(t)),btoa(String.fromCharCode.apply(null,new Uint8Array(s)))),iv:[...i]})},k=async(e,t)=>{const{c:i,iv:s}=JSON.parse(t);return E(await crypto.subtle.decrypt({name:A,iv:new Uint8Array(s)},await e,(e=>{const t=atob(e);return new Uint8Array(t.length).map(((e,i)=>t.charCodeAt(i))).buffer})(i)))},N={},D={},O={},I={},P={},L="announce",q=["wss://tracker.webtorrent.dev","wss://tracker.openwebtorrent.com","wss://tracker.files.fm:7073/announce","wss://tracker.btorrent.xyz"],M=((e,t)=>(t,i)=>{if(e[i])return e[i];if(!t)throw m("requires a config map as the first argument");if(!t.appId&&!t.firebaseApp)throw m("config map is missing appId field");if(!i)throw m("namespace argument required");return e[i]=((e,t)=>{if(e.trackerUrls||e.trackerRedundancy)throw m("trackerUrls/trackerRedundancy have been replaced by relayUrls/relayRedundancy");const i={},s=e.password&&(async(e,t)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},b(`${e}:${t}`)),{name:A},!1,["encrypt","decrypt"]))(e.password,t),n=((e,t,i)=>(e.relayUrls||t).slice(0,e.relayUrls?e.relayUrls.length:e.relayRedundancy||3))(e,q),r=crypto.subtle.digest("SHA-1",b(`${l}:${e.appId}:${t}`)).then((e=>Array.from(new Uint8Array(e)).map((e=>e.toString(36))).join("").slice(0,20))),a=t=>f(Array(t).fill().map((()=>{const t=d(!0,!1,e.rtcConfig);return[h(20),{peer:t,offerP:new Promise((e=>t.once(R.signal,e)))}]}))),o=async(t,n)=>{const a=await r;let o;try{o=JSON.parse(n.data)}catch(n){return void console.error(l+": received malformed SDP JSON")}if(o.info_hash!==a||o.peer_id&&o.peer_id===_)return;const c=o["failure reason"];if(c)console.warn(`${l}: torrent tracker failure from ${t.url} - ${c}`);else{if(o.interval&&o.interval>J&&o.interval<=120&&(clearInterval(W),J=o.interval,W=setInterval(U,1e3*J)),o.offer&&o.offer_id){if(i[o.peer_id]||x[o.offer_id])return;x[o.offer_id]=!0;const n=d(!1,!1,e.rtcConfig);return n.once(R.signal,(async e=>t.send(JSON.stringify({answer:s?{...e,sdp:await v(s,e.sdp)}:e,action:L,info_hash:a,peer_id:_,to_peer_id:o.peer_id,offer_id:o.offer_id})))),n.on(R.connect,(()=>B(n,o.peer_id))),n.on(R.close,(()=>$(n,o.peer_id,o.offer_id))),void n.signal(s?{...o.offer,sdp:await k(s,o.offer.sdp)}:o.offer)}if(o.answer){if(i[o.peer_id]||x[o.offer_id])return;const e=H[o.offer_id];if(e){const{peer:t}=e;if(t.destroyed)return;x[o.offer_id]=!0,t.on(R.connect,(()=>B(t,o.peer_id,o.offer_id))),t.on(R.close,(()=>$(t,o.peer_id,o.offer_id))),t.signal(s?{...o.answer,sdp:await k(s,o.answer.sdp)}:o.answer)}}}},c=async(e,t)=>e.send(JSON.stringify({action:L,info_hash:t,numwant:10,peer_id:_,offers:await Promise.all(g(H).map((async([e,{offerP:t}])=>{const i=await t;return{offer_id:e,offer:s?{...i,sdp:await v(s,i.sdp)}:i}})))})),M=(e,t,i)=>(i||!D[e]?(P[e]={...P[e],[t]:o},D[e]=new Promise((i=>{const s=new WebSocket(e);O[e]=s,s.addEventListener("open",(()=>{I[e]=4e3,i(s)})),s.addEventListener("message",(t=>u(P[e]).forEach((e=>e(s,t))))),s.addEventListener("close",(async()=>{var i;I[e]=I[e]??4e3,await(i=I[e],new Promise((e=>setTimeout(e,i)))),I[e]*=2,M(e,t,!0)}))}))):P[e][t]=o,D[e]),U=async()=>{const e=await r;H&&j(),H=a(10),n.forEach((async t=>{const i=await M(t,e);i.readyState===WebSocket.OPEN?c(i,e):i.readyState!==WebSocket.CONNECTING&&c(await M(t,e,!0),e)}))},j=()=>{g(H).forEach((([e,{peer:t}])=>{x[e]||i[e]||t.destroy()})),x={}},B=(e,t,s)=>{Y(e,t),i[t]=!0,s&&(i[s]=!0)},$=(e,t,s)=>{delete i[t],e.destroy(),s in H&&(delete H[s],H={...H,...a(1)})};let H,J=33,W=setInterval(U,1e3*J),Y=y,x={};return U(),((e,t)=>{const i={},s={},n={},r={},a={},o={},c=(e,t)=>(e?Array.isArray(e)?e:[e]:p(i)).flatMap((e=>{const s=i[e];return s?t(e,s):(console.warn(`${l}: no peer with id ${e} found`),[])})),d=e=>{if(s[e])return[s[e].send,s[e].setOnComplete,s[e].setOnProgress];if(!e)throw m("action type argument is required");const t=b(e);if(t.byteLength>12)throw m(`action type string "${e}" (${t.byteLength}b) exceeds byte limit (12). Hint: choose a shorter name.`);const n=new Uint8Array(12);n.set(t);let r=0;return s[e]={onComplete:y,onProgress:y,setOnComplete:t=>s[e]={...s[e],onComplete:t},setOnProgress:t=>s[e]={...s[e],onProgress:t},async send(e,t,s,a){if(s&&"object"!=typeof s)throw m("action meta argument must be an object");if(void 0===e)throw m("action data cannot be undefined");const o="string"!=typeof e,d=e instanceof Blob,h=d||e instanceof ArrayBuffer||e instanceof C;if(s&&!h)throw m("action meta argument can only be used with binary data");const l=h?new Uint8Array(d?await e.arrayBuffer():e):b(o?JSON.stringify(e):e),_=s?b(JSON.stringify(s)):null,p=Math.ceil(l.byteLength/w)+(s?1:0)||1,u=Array(p).fill().map(((e,t)=>{const i=t===p-1,a=s&&0===t,c=new Uint8Array(15+(a?_.byteLength:i?l.byteLength-w*(p-(s?2:1)):w));return c.set(n),c.set([r],12),c.set([i|a<<1|h<<2|o<<3],13),c.set([Math.round((t+1)/p*T)],14),c.set(s?a?_:l.subarray((t-1)*w,t*w):l.subarray(t*w,(t+1)*w),15),c}));return r=r+1&T,Promise.all(c(t,(async(e,t)=>{const n=t._channel;let r=0;for(;r<p;){const o=u[r];if(n.bufferedAmount>n.bufferedAmountLowThreshold&&await new Promise((e=>{const t=()=>{n.removeEventListener(S,t),e()};n.addEventListener(S,t)})),!i[e])break;t.send(o),r++,a&&a(o[14]/T,e,s)}})))}},[s[e].send,s[e].setOnComplete,s[e].setOnProgress]},h=(e,t)=>{const i=new Uint8Array(t),r=E(i.subarray(0,12)).replaceAll("\0",""),[a]=i.subarray(12,13),[o]=i.subarray(13,14),[c]=i.subarray(14,15),d=i.subarray(15),h=!!(1&o),l=!!(2&o),_=!!(4&o),p=!!(8&o);if(!s[r])throw m(`received message with unregistered type (${r})`);n[e]||(n[e]={}),n[e][r]||(n[e][r]={});let u=n[e][r][a];if(u||(u=n[e][r][a]={chunks:[]}),l?u.meta=JSON.parse(E(d)):u.chunks.push(d),s[r].onProgress(c/T,e,u.meta),!h)return;const g=new Uint8Array(u.chunks.reduce(((e,t)=>e+t.byteLength),0));if(u.chunks.reduce(((e,t)=>(g.set(t,e),e+t.byteLength)),0),_)s[r].onComplete(g,e,u.meta);else{const t=E(g);s[r].onComplete(p?JSON.parse(t):t,e)}delete n[e][r][a]},[_,u]=d("__91n6__"),[A,v]=d("__90n6__"),[k,N]=d("__516n4L__"),[D,O]=d("__57r34m__"),[I,P]=d("__7r4ck__");let L=y,q=y,M=y,U=y;return(e=>{Y=e})(((e,t)=>{if(i[t])return;const s=h.bind(null,t);i[t]=e,e.on(R.signal,(e=>k(e,t))),e.on(R.close,(()=>(e=>{i[e]&&(delete i[e],delete n[e],delete r[e],q(e))})(t))),e.on(R.data,s),e.on(R.stream,(e=>{M(e,t,a[t]),delete a[t]})),e.on(R.track,((e,i)=>{U(e,i,t,o[t]),delete o[t]})),e.on(R.error,(e=>{"ERR_DATA_CHANNEL"!==e.code&&console.error(e)})),L(t),e.__drainEarlyData(s)})),u(((e,t)=>A("",t))),v(((e,t)=>{r[t]&&(r[t](),delete r[t])})),N(((e,t)=>{i[t]&&i[t].signal(e)})),O(((e,t)=>a[t]=e)),P(((e,t)=>o[t]=e)),{makeAction:d,async ping(e){if(!e)throw m("ping() must be called with target peer ID");const t=Date.now();return _("",e),await new Promise((t=>r[e]=t)),Date.now()-t},leave(){g(i).forEach((([e,t])=>{t.destroy(),delete i[e]})),t()},getPeers:()=>f(g(i).map((([e,t])=>[e,t._pc]))),addStream:(e,t,i)=>c(t,(async(t,s)=>{i&&await D(i,t),s.addStream(e)})),removeStream:(e,t)=>c(t,((t,i)=>i.removeStream(e))),addTrack:(e,t,i,s)=>c(i,(async(i,n)=>{s&&await I(s,i),n.addTrack(e,t)})),removeTrack:(e,t,i)=>c(i,((i,s)=>s.removeTrack(e,t))),replaceTrack:(e,t,i,s,n)=>c(s,(async(s,r)=>{n&&await I(n,s),r.replaceTrack(e,t,i)})),onPeerJoin:e=>L=e,onPeerLeave:e=>q=e,onPeerStream:e=>M=e,onPeerTrack:e=>U=e}})(0,(async()=>{const e=await r;n.forEach((t=>delete P[t][e])),delete N[t],clearInterval(W),j()}))})(t,i)})(N)}));
@@ -1 +0,0 @@
1
- ("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequirea18f.register("k0jqy",(function(e,t){var i,s,n,r;function a(e){const t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=256*Math.random()|0;return t}function o(){if("undefined"==typeof globalThis)return null;const e={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}function c(e,t){return Object.defineProperty(e,"code",{value:t,enumerable:!0,configurable:!0}),e}function d(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}i=e.exports,s="joinRoom",n=function(){return j},Object.defineProperty(i,s,{get:n,set:r,enumerable:!0,configurable:!0});class h{constructor(e={}){if(this._map=new Map,this._id=a(4).toString("hex").slice(0,7),this._doDebug=e.debug,this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||a(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||h.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},h.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:o(),!this._wrtc)throw"undefined"==typeof window?c(Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void this.destroy(c(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch((e=>{this.destroy(c(e,"ERR_PC_PEER_IDENTITY"))})),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach((e=>{this.addStream(e)})),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this.destroying){if(this.destroyed)throw c(Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(c(e,"ERR_SET_REMOTE_DESCRIPTION"))})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(c(Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{!t.address||t.address.endsWith(".local")?console.warn("Ignoring unsupported ICE candidate."):this.destroy(c(e,"ERR_ADD_ICE_CANDIDATE"))}))}send(e){if(!this.destroying){if(this.destroyed)throw c(Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}addTransceiver(e,t){if(!this.destroying){if(this.destroyed)throw c(Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(c(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this.destroying){if(this.destroyed)throw c(Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),e.getTracks().forEach((t=>{this.addTrack(t,e)}))}}addTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const i=this._senderMap.get(e)||new Map;let s=i.get(t);if(s)throw s.removed?c(Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");s=this._pc.addTrack(e,t),i.set(t,s),this._senderMap.set(e,i),this._needsNegotiation()}replaceTrack(e,t,i){if(this.destroying)return;if(this.destroyed)throw c(Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const s=this._senderMap.get(e),n=s?s.get(i):null;if(!n)throw c(Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,s),null!=n.replaceTrack?n.replaceTrack(t):this.destroy(c(Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const i=this._senderMap.get(e),s=i?i.get(t):null;if(!s)throw c(Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{s.removed=!0,this._pc.removeTrack(s)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(s):this.destroy(c(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){if(!this.destroying){if(this.destroyed)throw c(Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),e.getTracks().forEach((t=>{this.removeTrack(t,e)}))}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask((()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1})))}negotiate(){if(!this.destroying){if(this.destroyed)throw c(Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout((()=>{this._createOffer()}),0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(e){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",e&&(e.message||e)),queueMicrotask((()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",e&&(e.message||e)),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(c(Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=65536),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{this.destroy(c(e,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=d(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.destroy(c(e,"ERR_CREATE_OFFER"))}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=d(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.destroy(c(e,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(c(Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(c(Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(c(Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"==={}.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((i=>{const s=[];i.forEach((e=>{s.push(t(e))})),e(null,s)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((i=>{if(this.destroyed)return;const s=[];i.result().forEach((e=>{const i={};e.names().forEach((t=>{i[t]=e.stat(t)})),i.id=e.id,i.type=e.type,i.timestamp=e.timestamp,s.push(t(i))})),e(null,s)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,i)=>{if(this.destroyed)return;t&&(i=[]);const s={},n={},r={};let a=!1;i.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(s[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(n[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(r[e.id]=e)}));const o=e=>{a=!0;let t=n[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let i=s[e.remoteCandidateId];i&&(i.ip||i.address)?(this.remoteAddress=i.ip||i.address,this.remotePort=Number(i.port)):i&&i.ipAddress?(this.remoteAddress=i.ipAddress,this.remotePort=Number(i.portNumber)):"string"==typeof e.googRemoteAddress&&(i=e.googRemoteAddress.split(":"),this.remoteAddress=i[0],this.remotePort=Number(i[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(i.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(r[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(r).length&&!Object.keys(n).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(c(t,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>65536||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=new Uint8Array(t)),this.emit("data",t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach((t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some((e=>e.id===t.id))||(this._remoteStreams.push(t),queueMicrotask((()=>{this._debug("on stream"),this.emit("stream",t)})))}))}_debug(...e){this._doDebug&&(e[0]="["+this._id+"] "+e[0])}on(e,t){const i=this._map;i.has(e)||i.set(e,new Set),i.get(e).add(t)}off(e,t){const i=this._map,s=i.get(e);s&&(s.delete(t),0===s.size&&i.delete(e))}once(e,t){const i=(...s)=>{this.off(e,i),t(...s)};this.on(e,i)}emit(e,...t){const i=this._map;if(i.has(e))for(const s of i.get(e))try{s(...t)}catch(e){console.error(e)}}}h.WEBRTC_SUPPORT=!!o(),h.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},h.channelConfig={};const l=(e,t,i)=>{const s=new h({initiator:e,trickle:t,config:i}),n=e=>s.__earlyDataBuffer.push(e);return s.on(w.data,n),s.__earlyDataBuffer=[],s.__drainEarlyData=e=>{s.off(w.data,n),s.__earlyDataBuffer.forEach(e),delete s.__earlyDataBuffer,delete s.__drainEarlyData},s},_=e=>Array(e).fill().map((()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[Math.floor(62*Math.random())])).join(""),u="Trystero",p=_(20),{keys:g,values:f,entries:y,fromEntries:m}=Object,b=()=>{},E=e=>Error(`${u}: ${e}`),R=e=>(new TextEncoder).encode(e),C=e=>(new TextDecoder).decode(e),w=m(["close","connect","data","error","signal","stream","track"].map((e=>[e,e]))),T=Object.getPrototypeOf(Uint8Array),S=16369,A=255,v="bufferedamountlow",k="AES-CBC",N=async(e,t)=>{const i=crypto.getRandomValues(new Uint8Array(16));var s;return JSON.stringify({c:(s=await crypto.subtle.encrypt({name:k,iv:i},await e,R(t)),btoa(String.fromCharCode.apply(null,new Uint8Array(s)))),iv:[...i]})},D=async(e,t)=>{const{c:i,iv:s}=JSON.parse(t);return C(await crypto.subtle.decrypt({name:k,iv:new Uint8Array(s)},await e,(e=>{const t=atob(e);return new Uint8Array(t.length).map(((e,i)=>t.charCodeAt(i))).buffer})(i)))},O={},I={},P={},L={},q={},M="announce",U=["wss://tracker.webtorrent.dev","wss://tracker.openwebtorrent.com","wss://tracker.files.fm:7073/announce","wss://tracker.btorrent.xyz"],j=((e,t)=>(t,i)=>{if(e[i])return e[i];if(!t)throw E("requires a config map as the first argument");if(!t.appId&&!t.firebaseApp)throw E("config map is missing appId field");if(!i)throw E("namespace argument required");return e[i]=((e,t)=>{if(e.trackerUrls||e.trackerRedundancy)throw E("trackerUrls/trackerRedundancy have been replaced by relayUrls/relayRedundancy");const i={},s=e.password&&(async(e,t)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},R(`${e}:${t}`)),{name:k},!1,["encrypt","decrypt"]))(e.password,t),n=((e,t,i)=>(e.relayUrls||t).slice(0,e.relayUrls?e.relayUrls.length:e.relayRedundancy||i))(e,U,3),r=crypto.subtle.digest("SHA-1",R(`${u}:${e.appId}:${t}`)).then((e=>Array.from(new Uint8Array(e)).map((e=>e.toString(36))).join("").slice(0,20))),a=t=>m(Array(t).fill().map((()=>{const t=l(!0,!1,e.rtcConfig);return[_(20),{peer:t,offerP:new Promise((e=>t.once(w.signal,e)))}]}))),o=async(t,n)=>{const a=await r;let o;try{o=JSON.parse(n.data)}catch(n){return void console.error(u+": received malformed SDP JSON")}if(o.info_hash!==a||o.peer_id&&o.peer_id===p)return;const c=o["failure reason"];if(c)console.warn(`${u}: torrent tracker failure from ${t.url} - ${c}`);else{if(o.interval&&o.interval>J&&o.interval<=120&&(clearInterval(W),J=o.interval,W=setInterval(h,1e3*J)),o.offer&&o.offer_id){if(i[o.peer_id]||x[o.offer_id])return;x[o.offer_id]=!0;const n=l(!1,!1,e.rtcConfig);return n.once(w.signal,(async e=>t.send(JSON.stringify({answer:s?{...e,sdp:await N(s,e.sdp)}:e,action:M,info_hash:a,peer_id:p,to_peer_id:o.peer_id,offer_id:o.offer_id})))),n.on(w.connect,(()=>B(n,o.peer_id))),n.on(w.close,(()=>$(n,o.peer_id,o.offer_id))),void n.signal(s?{...o.offer,sdp:await D(s,o.offer.sdp)}:o.offer)}if(o.answer){if(i[o.peer_id]||x[o.offer_id])return;const e=H[o.offer_id];if(e){const{peer:t}=e;if(t.destroyed)return;x[o.offer_id]=!0,t.on(w.connect,(()=>B(t,o.peer_id,o.offer_id))),t.on(w.close,(()=>$(t,o.peer_id,o.offer_id))),t.signal(s?{...o.answer,sdp:await D(s,o.answer.sdp)}:o.answer)}}}},c=async(e,t)=>e.send(JSON.stringify({action:M,info_hash:t,numwant:10,peer_id:p,offers:await Promise.all(y(H).map((async([e,{offerP:t}])=>{const i=await t;return{offer_id:e,offer:s?{...i,sdp:await N(s,i.sdp)}:i}})))})),d=(e,t,i)=>(i||!I[e]?(q[e]={...q[e],[t]:o},I[e]=new Promise((i=>{const s=new WebSocket(e);P[e]=s,s.addEventListener("open",(()=>{L[e]=4e3,i(s)})),s.addEventListener("message",(t=>f(q[e]).forEach((e=>e(s,t))))),s.addEventListener("close",(async()=>{var i;L[e]=L[e]??4e3,await(i=L[e],new Promise((e=>setTimeout(e,i)))),L[e]*=2,d(e,t,!0)}))}))):q[e][t]=o,I[e]),h=async()=>{const e=await r;H&&j(),H=a(10),n.forEach((async t=>{const i=await d(t,e);i.readyState===WebSocket.OPEN?c(i,e):i.readyState!==WebSocket.CONNECTING&&c(await d(t,e,!0),e)}))},j=()=>{y(H).forEach((([e,{peer:t}])=>{x[e]||i[e]||t.destroy()})),x={}},B=(e,t,s)=>{Y(e,t),i[t]=!0,s&&(i[s]=!0)},$=(e,t,s)=>{delete i[t],e.destroy(),s in H&&(delete H[s],H={...H,...a(1)})};let H,J=33,W=setInterval(h,1e3*J),Y=b,x={};return h(),((e,t)=>{const i={},s={},n={},r={},a={},o={},c=(e,t)=>(e?Array.isArray(e)?e:[e]:g(i)).flatMap((e=>{const s=i[e];return s?t(e,s):(console.warn(`${u}: no peer with id ${e} found`),[])})),d=e=>{if(s[e])return[s[e].send,s[e].setOnComplete,s[e].setOnProgress];if(!e)throw E("action type argument is required");const t=R(e);if(t.byteLength>12)throw E(`action type string "${e}" (${t.byteLength}b) exceeds byte limit (12). Hint: choose a shorter name.`);const n=new Uint8Array(12);n.set(t);let r=0;return s[e]={onComplete:b,onProgress:b,setOnComplete:t=>s[e]={...s[e],onComplete:t},setOnProgress:t=>s[e]={...s[e],onProgress:t},async send(e,t,s,a){if(s&&"object"!=typeof s)throw E("action meta argument must be an object");if(void 0===e)throw E("action data cannot be undefined");const o="string"!=typeof e,d=e instanceof Blob,h=d||e instanceof ArrayBuffer||e instanceof T;if(s&&!h)throw E("action meta argument can only be used with binary data");const l=h?new Uint8Array(d?await e.arrayBuffer():e):R(o?JSON.stringify(e):e),_=s?R(JSON.stringify(s)):null,u=Math.ceil(l.byteLength/S)+(s?1:0)||1,p=Array(u).fill().map(((e,t)=>{const i=t===u-1,a=s&&0===t,c=new Uint8Array(15+(a?_.byteLength:i?l.byteLength-S*(u-(s?2:1)):S));return c.set(n),c.set([r],12),c.set([i|a<<1|h<<2|o<<3],13),c.set([Math.round((t+1)/u*A)],14),c.set(s?a?_:l.subarray((t-1)*S,t*S):l.subarray(t*S,(t+1)*S),15),c}));return r=r+1&A,Promise.all(c(t,(async(e,t)=>{const n=t._channel;let r=0;for(;r<u;){const o=p[r];if(n.bufferedAmount>n.bufferedAmountLowThreshold&&await new Promise((e=>{const t=()=>{n.removeEventListener(v,t),e()};n.addEventListener(v,t)})),!i[e])break;t.send(o),r++,a&&a(o[14]/A,e,s)}})))}},[s[e].send,s[e].setOnComplete,s[e].setOnProgress]},h=(e,t)=>{const i=new Uint8Array(t),r=C(i.subarray(0,12)).replaceAll("\0",""),[a]=i.subarray(12,13),[o]=i.subarray(13,14),[c]=i.subarray(14,15),d=i.subarray(15),h=!!(1&o),l=!!(2&o),_=!!(4&o),u=!!(8&o);if(!s[r])throw E(`received message with unregistered type (${r})`);n[e]||(n[e]={}),n[e][r]||(n[e][r]={});let p=n[e][r][a];if(p||(p=n[e][r][a]={chunks:[]}),l?p.meta=JSON.parse(C(d)):p.chunks.push(d),s[r].onProgress(c/A,e,p.meta),!h)return;const g=new Uint8Array(p.chunks.reduce(((e,t)=>e+t.byteLength),0));if(p.chunks.reduce(((e,t)=>(g.set(t,e),e+t.byteLength)),0),_)s[r].onComplete(g,e,p.meta);else{const t=C(g);s[r].onComplete(u?JSON.parse(t):t,e)}delete n[e][r][a]},[l,_]=d("__91n6__"),[p,f]=d("__90n6__"),[k,N]=d("__516n4L__"),[D,O]=d("__57r34m__"),[I,P]=d("__7r4ck__");let L=b,q=b,M=b,U=b;return e(((e,t)=>{if(i[t])return;const s=h.bind(null,t);i[t]=e,e.on(w.signal,(e=>k(e,t))),e.on(w.close,(()=>(e=>{i[e]&&(delete i[e],delete n[e],delete r[e],q(e))})(t))),e.on(w.data,s),e.on(w.stream,(e=>{M(e,t,a[t]),delete a[t]})),e.on(w.track,((e,i)=>{U(e,i,t,o[t]),delete o[t]})),e.on(w.error,(e=>{"ERR_DATA_CHANNEL"!==e.code&&console.error(e)})),L(t),e.__drainEarlyData(s)})),_(((e,t)=>p("",t))),f(((e,t)=>{r[t]&&(r[t](),delete r[t])})),N(((e,t)=>{i[t]&&i[t].signal(e)})),O(((e,t)=>a[t]=e)),P(((e,t)=>o[t]=e)),{makeAction:d,async ping(e){if(!e)throw E("ping() must be called with target peer ID");const t=Date.now();return l("",e),await new Promise((t=>r[e]=t)),Date.now()-t},leave(){y(i).forEach((([e,t])=>{t.destroy(),delete i[e]})),t()},getPeers:()=>m(y(i).map((([e,t])=>[e,t._pc]))),addStream:(e,t,i)=>c(t,(async(t,s)=>{i&&await D(i,t),s.addStream(e)})),removeStream:(e,t)=>c(t,((t,i)=>i.removeStream(e))),addTrack:(e,t,i,s)=>c(i,(async(i,n)=>{s&&await I(s,i),n.addTrack(e,t)})),removeTrack:(e,t,i)=>c(i,((i,s)=>s.removeTrack(e,t))),replaceTrack:(e,t,i,s,n)=>c(s,(async(s,r)=>{n&&await I(n,s),r.replaceTrack(e,t,i)})),onPeerJoin:e=>L=e,onPeerLeave:e=>q=e,onPeerStream:e=>M=e,onPeerTrack:e=>U=e}})((e=>Y=e),(async()=>{const e=await r;n.forEach((t=>delete q[t][e])),delete O[t],clearInterval(W),j()}))})(t,i)})(O)}));