PageSourceSearch

https://www.virtualuser.com/_next/static/chunks/144d3bae-e0340dd2e…?dpl=dpl_3RAp55Bwp5ysgLwiDWsr1C6REuKo

js virtualuser.com collected 2026-10-07 14:36:31 UTC 424,869 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[67501],{3481:(e,t,i)=>{let n,a,r,s,o;i.d(t,{CC:()=>rW,KN:()=>e_,Wv:()=>oz,rV:()=>oH,u9:()=>eo});var c,l,d,u,h,p,m,g,f,v,k,b,y,T,C,S,E,w,P,R,I,_,O,D,M,x,A,N,L,U,j,F,B,q,V,H,W,G,K,J,z,Q,Y,X,Z,$,ee,et,ei,en,ea,er,es,eo,ec,el,ed,eu,eh,ep,em,eg,ef,ev,ek,eb,ey,eT,eC,eS,eE,ew,eP,eR,eI,e_,eO,eD,eM,ex,eA,eN,eL=i(41463),eU=Object.defineProperty,ej=(e,t,i)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?eU(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i};class eF{constructor(){ej(this,"_locking"),ej(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;let t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function eB(e,t){if(!e)throw Error(t)}function eq(e){if("number"!=typeof e)throw Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>0x7fffffff||e<-0x80000000)throw Error("invalid int 32: "+e)}function eV(e){if("number"!=typeof e)throw Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>0xffffffff||e<0)throw Error("invalid uint 32: "+e)}function eH(e){if("number"!=typeof e)throw Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw Error("invalid float 32: "+e)}let eW=Symbol("@bufbuild/protobuf/enum-type");function eG(e,t,i,n){e[eW]=eK(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function eK(e,t,i){let n=Object.create(null),a=Object.create(null),r=[];for(let e of t){let t=eJ(e);r.push(t),n[e.name]=t,a[e.no]=t}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>a[e]}}function eJ(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class ez{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){let i=this.getType(),n=i.runtime.json,a=n.makeReadOptions(t);return n.readMessage(i,e,a,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){let t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){let t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;return JSON.stringify(this.toJson(e),null,null!=(t=null==e?void 0:e.prettySpaces)?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function eQ(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,(128&i)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}throw Error("invalid varint")}function eY(e,t,i){for(let n=0;n<28;n+=7){let a=e>>>n,r=a>>>7!=0||0!=t,s=(r?128|a:a)&255;if(i.push(s),!r)return}let n=e>>>28&15|(7&t)<<4,a=t>>3!=0;if(i.push((a?128|n:n)&255),a){for(let e=3;e<31;e+=7){let n=t>>>e,a=n>>>7!=0,r=(a?128|n:n)&255;if(i.push(r),!a)return}i.push(t>>>31&1)}}function eX(e){let t="-"===e[0];t&&(e=e.slice(1));let i=0,n=0;function a(t,a){let r=Number(e.slice(t,a));n*=1e6,(i=1e6*i+r)>=0x100000000&&(n+=i/0x100000000|0,i%=0x100000000)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?e0(i,n):e$(i,n)}function eZ(e,t){if({lo:e,hi:t}={lo:e>>>0,hi:t>>>0},t<=2097151)return String(0x100000000*t+e);let i=0xffffff&e,n=(e>>>24|t<<8)&0xffffff,a=t>>16&65535,r=i+6777216*n+6710656*a,s=n+8147497*a,o=2*a;return r>=1e7&&(s+=Math.floor(r/1e7),r%=1e7),s>=1e7&&(o+=Math.floor(s/1e7),s%=1e7),o.toString()+e1(s)+e1(r)}function e$(e,t){return{lo:0|e,hi:0|t}}function e0(e,t){return t=~t,e?e=~e+1:t+=1,e$(e,t)}let e1=e=>{let t=String(e);return"0000000".slice(t.length)+t};function e2(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function e3(){let e=this.buf[this.pos++],t=127&e;if((128&e)==0||(t|=(127&(e=this.buf[this.pos++]))<<7,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<14,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<21,(128&e)==0))return this.assertBounds(),t;
1t|=(15&(e=this.buf[this.pos++]))<<28;for(let t=5;(128&e)!=0&&t<10;t++)e=this.buf[this.pos++];if((128&e)!=0)throw Error("invalid varint");return this.assertBounds(),t>>>0}let e4=function(){let e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof eL||"object"!=typeof eL.env||"1"!==eL.env.BUF_BIGINT_DISABLE)){let t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){let n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw Error("int64 invalid: ".concat(e));return n},uParse(e){let t="bigint"==typeof e?e:BigInt(e);if(t>a||t<n)throw Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}let t=e=>eB(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>eB(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),eX(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),eX(e)),dec:(e,t)=>{let i,n,a;return(n=0x80000000&(i=e$(e,t)).hi)&&(i=e0(i.lo,i.hi)),a=eZ(i.lo,i.hi),n?"-"+a:a},uDec:(e,t)=>eZ(e,t)}}();function e9(e,t,i){if(t===i)return!0;if(e==Q.BYTES){if(!(t instanceof Uint8Array)||!(i instanceof Uint8Array)||t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case Q.UINT64:case Q.FIXED64:case Q.INT64:case Q.SFIXED64:case Q.SINT64:return t==i}return!1}function e6(e,t){switch(e){case Q.BOOL:return!1;case Q.UINT64:case Q.FIXED64:case Q.INT64:case Q.SFIXED64:case Q.SINT64:return 0==t?e4.zero:"0";case Q.DOUBLE:case Q.FLOAT:return 0;case Q.BYTES:return new Uint8Array(0);case Q.STRING:return"";default:return 0}}function e5(e,t){switch(e){case Q.BOOL:return!1===t;case Q.STRING:return""===t;case Q.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(c=Q||(Q={}))[c.DOUBLE=1]="DOUBLE",c[c.FLOAT=2]="FLOAT",c[c.INT64=3]="INT64",c[c.UINT64=4]="UINT64",c[c.INT32=5]="INT32",c[c.FIXED64=6]="FIXED64",c[c.FIXED32=7]="FIXED32",c[c.BOOL=8]="BOOL",c[c.STRING=9]="STRING",c[c.BYTES=12]="BYTES",c[c.UINT32=13]="UINT32",c[c.SFIXED32=15]="SFIXED32",c[c.SFIXED64=16]="SFIXED64",c[c.SINT32=17]="SINT32",c[c.SINT64=18]="SINT64",(l=Y||(Y={}))[l.BIGINT=0]="BIGINT",l[l.STRING=1]="STRING",(d=X||(X={}))[d.Varint=0]="Varint",d[d.Bit64=1]="Bit64",d[d.LengthDelimited=2]="LengthDelimited",d[d.StartGroup=3]="StartGroup",d[d.EndGroup=4]="EndGroup",d[d.Bit32=5]="Bit32";class e8{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(eV(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return eq(e),e2(e,this.buf),this}bool(e){return this.buf.push(+!!e),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){eH(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){eV(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){eq(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return eq(e),e2(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=e4.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=e4.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=e4.enc(e);return eY(t.lo,t.hi,this.buf),this}sint64(e){let t=e4.enc(e),i=t.hi>>31;return eY(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=e4.uEnc(e);return eY(t.lo,t.hi,this.buf),this}}class e7{constructor(e,t){this.varint64=eQ,this.uint32=e3,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;
1if(t<=0||i<0||i>5)throw Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case X.Varint:for(;128&this.buf[this.pos++];);break;case X.Bit64:this.pos+=4;case X.Bit32:this.pos+=4;break;case X.LengthDelimited:let n=this.uint32();this.pos+=n;break;case X.StartGroup:for(;;){let[e,i]=this.tag();if(i===X.EndGroup){if(void 0!==t&&e!==t)throw Error("invalid end group tag");break}this.skip(i,e)}break;default:throw Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return e4.dec(...this.varint64())}uint64(){return e4.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,e4.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return e4.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return e4.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function te(e){let t=e.field.localName,i=Object.create(null);return i[t]=function(e){let t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return e6(t.T,t.L);case"message":let i=t.T,n=new i;return i.fieldWrapper?i.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ti=[];for(let e=0;e<tt.length;e++)ti[tt[e].charCodeAt(0)]=e;ti[45]=tt.indexOf("+"),ti[95]=tt.indexOf("/");let tn={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i=new Uint8Array(t),n=0,a=0,r,s=0;for(let t=0;t<e.length;t++){if(void 0===(r=ti[e.charCodeAt(t)]))switch(e[t]){case"=":a=0;case"\n":case"\r":case"	":case" ":continue;default:throw Error("invalid base64 string.")}switch(a){case 0:s=r,a=1;break;case 1:i[n++]=s<<2|(48&r)>>4,s=r,a=2;break;case 2:i[n++]=(15&s)<<4|(60&r)>>2,s=r,a=3;break;case 3:i[n++]=(3&s)<<6|r,a=0}}if(1==a)throw Error("invalid base64 string.");return i.subarray(0,n)},enc(e){let t="",i=0,n,a=0;for(let r=0;r<e.length;r++)switch(n=e[r],i){case 0:t+=tt[n>>2],a=(3&n)<<4,i=1;break;case 1:t+=tt[a|n>>4],a=(15&n)<<2,i=2;break;case 2:t+=tt[a|n>>6],t+=tt[63&n],i=0}return i&&(t+=tt[a],t+="=",1==i&&(t+="=")),t}};function ta(e,t){let i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function tr(e,t){eB(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function ts(e,t){let i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":if(e.opt||e.req)return void 0!==t[i];if("enum"==e.kind)return t[i]!==e.T.values[0].no;return!e5(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function to(e,t){let i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?e6(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function tc(e,t){if(null===e||"object"!=typeof e||!Object.getOwnPropertyNames(ez.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;let i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function tl(e,t){return tc(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}Q.DOUBLE,Q.FLOAT,Q.INT64,Q.UINT64,Q.INT32,Q.UINT32,Q.BOOL,Q.STRING,Q.BYTES;let td={ignoreUnknownFields:!1},tu={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},th=Symbol(),tp=Symbol();function tm(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function tg(e,t,i,n,a){let r=i.localName;if(i.repeated){if(eB("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw Error("cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(tm(t)));let s=e[r];for(let e of t){if(null===e)throw Error("cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(tm(e)));switch(i.kind){case"message":s.push(i.T.fromJson(e,n));break;case"enum":let t=tv(i.T,e,n.ignoreUnknownFields,!0);t!==tp&&s.push(t);break;
1case"scalar":try{s.push(tf(i.T,e,i.L,!0))}catch(n){let t="cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(tm(e));throw n instanceof Error&&n.message.length>0&&(t+=": ".concat(n.message)),Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw Error("cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(tm(t)));let s=e[r];for(let[e,r]of Object.entries(t)){let o;if(null===r)throw Error("cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: map value null"));try{o=function(e,t){if(e===Q.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return tf(e,t,Y.BIGINT,!0).toString()}(i.K,e)}catch(n){let e="cannot decode map key for field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(tm(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}switch(i.V.kind){case"message":s[o]=i.V.T.fromJson(r,n);break;case"enum":let c=tv(i.V.T,r,n.ignoreUnknownFields,!0);c!==tp&&(s[o]=c);break;case"scalar":try{s[o]=tf(i.V.T,r,Y.BIGINT,!0)}catch(n){let e="cannot decode map value for field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(tm(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":let s=i.T;if(null===t&&"google.protobuf.Value"!=s.typeName)return;let o=e[r];tc(o)?o.fromJson(t,n):(e[r]=o=s.fromJson(t,n),s.fieldWrapper&&!i.oneof&&(e[r]=s.fieldWrapper.unwrapField(o)));break;case"enum":let c=tv(i.T,t,n.ignoreUnknownFields,!1);switch(c){case th:to(i,e);break;case tp:break;default:e[r]=c}break;case"scalar":try{let n=tf(i.T,t,i.L,!1);n===th?to(i,e):e[r]=n}catch(n){let e="cannot decode field ".concat(a.typeName,".").concat(i.name," from JSON: ").concat(tm(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}function tf(e,t,i,n){if(null===t)return n?e6(e,i):th;switch(e){case Q.DOUBLE:case Q.FLOAT:if("NaN"===t)return NaN;if("Infinity"===t)return 1/0;if("-Infinity"===t)return-1/0;if(""===t||"string"==typeof t&&t.trim().length!==t.length||"string"!=typeof t&&"number"!=typeof t)break;let a=Number(t);if(Number.isNaN(a)||!Number.isFinite(a))break;return e==Q.FLOAT&&eH(a),a;case Q.INT32:case Q.FIXED32:case Q.SFIXED32:case Q.SINT32:case Q.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==Q.UINT32||e==Q.FIXED32?eV(r):eq(r),r;case Q.INT64:case Q.SFIXED64:case Q.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;let s=e4.parse(t);return i?s.toString():s;case Q.FIXED64:case Q.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;let o=e4.uParse(t);return i?o.toString():o;case Q.BOOL:if("boolean"!=typeof t)break;return t;case Q.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw Error("invalid UTF8")}return t;case Q.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return tn.dec(t)}throw Error()}function tv(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:th;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":let a=e.findName(t);if(void 0!==a)return a.no;if(i)return tp}throw Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(tm(t)))}function tk(e,t,i){if("map"==e.kind){eB("object"==typeof t&&null!=t);let n={},a=Object.entries(t);switch(e.V.kind){case"scalar":for(let[t,i]of a)n[t.toString()]=ty(e.V.T,i);break;case"message":for(let[e,t]of a)n[e.toString()]=t.toJson(i);break;case"enum":let r=e.V.T;for(let[e,t]of a)n[e.toString()]=tb(r,t,i.enumAsInteger)}return i.emitDefaultValues||a.length>0?n:void 0}if(e.repeated){eB(Array.isArray(t));let n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(ty(e.T,t[i]));break;case"enum":for(let a=0;a<t.length;a++)n.push(tb(e.T,t[a],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return ty(e.T,t);case"enum":return tb(e.T,t,i.enumAsInteger);case"message":return tl(e.T,t).toJson(i)}}function tb(e,t,i){var n;if(eB("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;let a=e.findNumber(t);return null!=(n=null==a?void 0:a.name)?n:t}function ty(e,t){switch(e){case Q.INT32:case Q.SFIXED32:case Q.SINT32:case Q.FIXED32:case Q.UINT32:return eB("number"==typeof t),t;case Q.FLOAT:case Q.DOUBLE:if(eB("number"==typeof t),Number.isNaN(t))return"NaN";if(t===1/0)return"Infinity";if(t===-1/0)return"-Infinity";return t;case Q.STRING:return eB("string"==typeof t),t;case Q.BOOL:return eB("boolean"==typeof t),t;case Q.UINT64:case Q.FIXED64:case Q.INT64:case Q.SFIXED64:case Q.SINT64:return eB("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case Q.BYTES:return eB(t instanceof Uint8Array),tn.enc(t)}}let tT=Symbol("@bufbuild/protobuf/unknown-fields"),tC={readUnknownFields:!0,readerFactory:e=>new e7(e)},tS={writeUnknownFields:!0,writerFactory:()=>new e8};function tE(e,t,i,n,a){let{repeated:r,localName:s}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=s&&delete e.value,e.case=s,s="value"),i.kind){case"scalar":case"enum":let o="enum"==i.kind?Q.INT32:i.T,c=tR;if("scalar"==i.kind&&i.L>0&&(c=tP),r){let i=e[s];if(n==X.LengthDelimited&&o!=Q.STRING&&o!=Q.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,o))}else i.push(c(t,o))}else e[s]=c(t,o);break;case"message":let l=i.T;r?e[s].push(tw(t,new l,a,i)):tc(e[s])?tw(t,e[s],a,i):(e[s]=tw(t,new l,a,i),!l.fieldWrapper||i.oneof||i.repeated||(e[
1s]=l.fieldWrapper.unwrapField(e[s])));break;case"map":let[d,u]=function(e,t,i){let n,a,r=t.uint32(),s=t.pos+r;for(;t.pos<s;){let[r]=t.tag();switch(r){case 1:n=tR(t,e.K);break;case 2:switch(e.V.kind){case"scalar":a=tR(t,e.V.T);break;case"enum":a=t.int32();break;case"message":a=tw(t,new e.V.T,i,void 0)}}}if(void 0===n&&(n=e6(e.K,Y.BIGINT)),"string"!=typeof n&&"number"!=typeof n&&(n=n.toString()),void 0===a)switch(e.V.kind){case"scalar":a=e6(e.V.T,Y.BIGINT);break;case"enum":a=e.V.T.values[0].no;break;case"message":a=new e.V.T}return[n,a]}(i,t,a);e[s][d]=u}}function tw(e,t,i,n){let a=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return a.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function tP(e,t){let i=tR(e,t);return"bigint"==typeof i?i.toString():i}function tR(e,t){switch(t){case Q.STRING:return e.string();case Q.BOOL:return e.bool();case Q.DOUBLE:return e.double();case Q.FLOAT:return e.float();case Q.INT32:return e.int32();case Q.INT64:return e.int64();case Q.UINT64:return e.uint64();case Q.FIXED64:return e.fixed64();case Q.BYTES:return e.bytes();case Q.FIXED32:return e.fixed32();case Q.SFIXED32:return e.sfixed32();case Q.SFIXED64:return e.sfixed64();case Q.SINT64:return e.sint64();case Q.UINT32:return e.uint32();case Q.SINT32:return e.sint32()}}function tI(e,t,i,n){eB(void 0!==t);let a=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?Q.INT32:e.T;if(a)if(eB(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,X.LengthDelimited).fork();let[,a]=tD(t);for(let t=0;t<n.length;t++)e[a](n[t]);e.join()}(i,r,e.no,t);else for(let n of t)tO(i,r,e.no,n);else tO(i,r,e.no,t);break;case"message":if(a)for(let a of(eB(Array.isArray(t)),t))t_(i,n,e,a);else t_(i,n,e,t);break;case"map":for(let[a,r]of(eB("object"==typeof t&&null!=t),Object.entries(t)))!function(e,t,i,n,a){e.tag(i.no,X.LengthDelimited),e.fork();let r=n;switch(i.K){case Q.INT32:case Q.FIXED32:case Q.UINT32:case Q.SFIXED32:case Q.SINT32:r=Number.parseInt(n);break;case Q.BOOL:eB("true"==n||"false"==n),r="true"==n}switch(tO(e,i.K,1,r),i.V.kind){case"scalar":tO(e,i.V.T,2,a);break;case"enum":tO(e,Q.INT32,2,a);break;case"message":eB(void 0!==a),e.tag(2,X.LengthDelimited).bytes(a.toBinary(t))}e.join()}(i,n,e,a,r)}}function t_(e,t,i,n){let a=tl(i.T,n);i.delimited?e.tag(i.no,X.StartGroup).raw(a.toBinary(t)).tag(i.no,X.EndGroup):e.tag(i.no,X.LengthDelimited).bytes(a.toBinary(t))}function tO(e,t,i,n){eB(void 0!==n);let[a,r]=tD(t);e.tag(i,a)[r](n)}function tD(e){let t=X.Varint;switch(e){case Q.BYTES:case Q.STRING:t=X.LengthDelimited;break;case Q.DOUBLE:case Q.FIXED64:case Q.SFIXED64:t=X.Bit64;break;case Q.FIXED32:case Q.SFIXED32:case Q.FLOAT:t=X.Bit32}return[t,Q[e].toLowerCase()]}function tM(e){if(void 0===e)return e;if(tc(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function tx(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class tA{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){let e;this.members=[];let t=this.members;for(let i of this.list())i.oneof?i.oneof!==e&&(e=i.oneof,t.push(e)):t.push(i)}return this.members}}function tN(e,t){let i=tU(e);return t?i:tq(tB(i))}let tL=tU;function tU(e){let t=!1,i=[];for(let n=0;n<e.length;n++){let a=e.charAt(n);switch(a){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(a),t=!1;break;default:t&&(t=!1,a=a.toUpperCase()),i.push(a)}}return i.join("")}let tj=new Set(["constructor","toString","toJSON","valueOf"]),tF=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),tB=e=>{if(tF.has(e))return"".concat(e,"$");return e},tq=e=>{if(tj.has(e))return"".concat(e,"$");return e};class tV{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=function(e){return tN(e,!1)}(e)}addField(e){eB(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}let tH=(u=e=>new tA(e,e=>(function(e){var t,i,n,a,r,s;let o,c=[];for(let l of"function"==typeof e?e():e){if(l.localName=tN(l.name,void 0!==l.oneof),l.jsonName=null!=(t=l.jsonName)?t:tL(l.name),l.repeated=null!=(i=l.repeated)&&i,"scalar"==l.kind&&(l.L=null!=(n=l.L)?n:Y.BIGINT),l.delimited=null!=(a=l.delimited)&&a,l.req=null!=(r=l.req)&&r,l.opt=null!=(s=l.opt)&&s,void 0===l.packed&&(l.packed="enum"==l.kind||"scalar"==l.kind&&l.T!=Q.BYTES&&l.T!=Q.STRING),void 0!==l.oneof){let e="string"==typeof l.oneof?l.oneof:l.oneof.name;o&&o.name==e||(o=new tV(e)),l.oneof=o,o.addField(l)}c.push(l)}return c})(e)),h=e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let i=t.localName;if(t.repeated){e[i]=[];continue}switch(t.kind){case"oneof":e[i]={case:void 0};break;case"enum":e[i]=0;break;case"map":e[i]={};break;case"scalar":e[i]=e6(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},td),e):td},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},tu),e):tu},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(tm(t)));n=null!=n?n:new e;let a=new Map,r=i.typeRegistry;for(let[s,o]of Object.entries(t)){let t=e.fields.findJsonName(s);if(t){if(t.oneof){if(null===o&&"scalar"==t.kind)continue;let i=a.get(t.oneof);if(void 0!==i)throw Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(s,'"'));a.set(t.oneof,s)}tg(n,o,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&s.startsWith("[")&&s.endsWith("]")){let a=r.findExtension(s.substring(1,s.length-1));if(a&&a.extendee.typeName==e.typeName){t=!0;let[e,r]=te(a);tg(e,o,a.field,i,a),function(e,t,i,n){tr(t,e);let a=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(ta(e,t)){let i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);for(let t of(e.getType().runtime.bin.discardUnknownFields(e),i))e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let s=r.writerFactory(),o=t.field;o.opt||o.repeated||"enum"!=o.kind&&"scalar"!=o.kind||(o=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(o,i,s,r);let c=a.readerFactory(s.finish());for(;c.pos<c.len;){let[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}(n,a,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(s,'" is unknown'))}}return n},writeMessage(e,t){let i,n=e.getType(),a={};try{for(i of n.fields.byNumber()){if(!ts(i,e)){var r;if(i.req)throw"required field not set";if(!t.emitDefaultValues||!((r=i).repeated||"map"==r.kind||!r.oneof&&"message"!=r.kind&&!r.opt&&!r.req))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],s=tk(i,n,t);void 0!==s&&(a[t.useProtoFieldName?i.name:i.jsonName]=s)}let s=t.typeRegistry;if(null==s?void 0:s.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let r=s.findExtensionFor(n.typeName,i.no);if(r&&ta(e,r)){let i=function(e,t,i){tr(t,e);let n=t.runtime.bin.makeReadOptions(i),a=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[r,s]=te(t);for(let e of a)t.runtime.bin.readField(r,n.readerFactory(e.data),t.field,e.wireType,n);return s()}(e,r,t),n=tk(r.field,i,t);void 0!==n&&(a[r.field.jsonName]=n)}}}catch(a){let e=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),t=a instanceof Error?a.message:String(a);throw Error(e+(t.length>0?": ".concat(t):""))}return a},readScalar:(e,t,i)=>tf(e,t,null!=i?i:Y.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t&&(i||e5(e,t)))return ty(e,t)},debug:tm},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},tC),e):tC},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},tS),e):tS},listUnknownFields(e){var t;return null!=(t=e[tT])?t:[]},discardUnknownFields(e){delete e[tT]},writeUnknownFields(e,t){let i=e[tT];if(i)for(let e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){Array.isArray(e[tT])||(e[tT]=[]),e[tT].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,a){let r,s,o=e.getType(),c=a?t.len:t.pos+i;for(;t.pos<c&&([r,s]=t.tag(),!0!==a||s!=X.EndGroup);){let i=o.fields.find(r);if(!i){let i=t.skip(s,r);
1n.readUnknownFields&&this.onUnknownField(e,r,s,i);continue}tE(e,t,i,s,n)}if(a&&(s!=X.EndGroup||r!==i))throw Error("invalid end group tag")},readField:tE,writeMessage(e,t,i){let n=e.getType();for(let a of n.fields.byNumber()){if(!ts(a,e)){if(a.req)throw Error("cannot encode field ".concat(n.typeName,".").concat(a.name," to binary: required field not set"));continue}let r=a.oneof?e[a.oneof.localName].value:e[a.localName];tI(a,r,t,i)}return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&tI(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:eG,initPartial(e,t){if(void 0!==e)for(let i of t.getType().fields.byMember()){let n=i.localName;if(null!=e[n])switch(i.kind){case"oneof":let a=e[n].case;if(void 0===a)continue;let r=i.findField(a),s=e[n].value;r&&"message"==r.kind&&!tc(s,r.T)?s=new r.T(s):r&&"scalar"===r.kind&&r.T===Q.BYTES&&(s=tx(s)),t[n]={case:a,value:s};break;case"scalar":case"enum":let o=e[n];i.T===Q.BYTES&&(o=i.repeated?o.map(tx):tx(o)),t[n]=o;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===Q.BYTES)for(let[i,a]of Object.entries(e[n]))t[n][i]=tx(a);else Object.assign(t[n],e[n]);break;case"message":let c=i.V.T;for(let i of Object.keys(e[n])){let a=e[n][i];c.fieldWrapper||(a=new c(a)),t[n][i]=a}}break;case"message":let l=i.T;if(i.repeated)t[n]=e[n].map(e=>tc(e,l)?e:new l(e));else{let i=e[n];l.fieldWrapper?"google.protobuf.BytesValue"===l.typeName?t[n]=tx(i):t[n]=i:t[n]=tc(i,l)?i:new l(i)}}}},equals:(e,t,i)=>t===i||!!t&&!!i&&e.fields.byMember().every(e=>{let n=t[e.localName],a=i[e.localName];if(e.repeated){if(n.length!==a.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,a[i]));case"scalar":return n.every((t,i)=>e9(e.T,t,a[i]));case"enum":return n.every((e,t)=>e9(Q.INT32,e,a[t]))}throw Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let r=n,s=a;return e.T.fieldWrapper&&(void 0===r||tc(r)||(r=e.T.fieldWrapper.wrapField(r)),void 0===s||tc(s)||(s=e.T.fieldWrapper.wrapField(s))),e.T.equals(r,s);case"enum":return e9(Q.INT32,n,a);case"scalar":return e9(e.T,n,a);case"oneof":if(n.case!==a.case)return!1;let o=e.findField(n.case);if(void 0===o)return!0;switch(o.kind){case"message":return o.T.equals(n.value,a.value);case"enum":return e9(Q.INT32,n.value,a.value);case"scalar":return e9(o.T,n.value,a.value)}throw Error("oneof cannot contain ".concat(o.kind));case"map":let c=Object.keys(n).concat(Object.keys(a));switch(e.V.kind){case"message":let l=e.V.T;return c.every(e=>l.equals(n[e],a[e]));case"enum":return c.every(e=>e9(Q.INT32,n[e],a[e]));case"scalar":let d=e.V.T;return c.every(e=>e9(d,n[e],a[e]))}}}),clone(e){let t=e.getType(),i=new t;for(let n of t.fields.byMember()){let t,a=e[n.localName];if(n.repeated)t=a.map(tM);else if("map"==n.kind)for(let[e,r]of(t=i[n.localName],Object.entries(a)))t[e]=tM(r);else t="oneof"==n.kind?n.findField(a.case)?{case:a.case,value:tM(a.value)}:{case:void 0}:tM(a);i[n.localName]=t}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return i}}),{newFieldList:u,initFields:h}),makeMessageType(e,t,i){var n,a;let r,s;return n=this,Object.setPrototypeOf((s=({[r=null!=(a=null==i?void 0:i.localName)?a:e.substring(e.lastIndexOf(".")+1)]:function(e){n.util.initFields(this),n.util.initPartial(e,this)}})[r]).prototype,new ez),Object.assign(s,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary:(e,t)=>new s().fromBinary(e,t),fromJson:(e,t)=>new s().fromJson(e,t),fromJsonString:(e,t)=>new s().fromJsonString(e,t),equals:(e,t)=>n.util.equals(s,e,t)}),s},makeEnum:function(e,t,i){let n={};for(let e of t){let t=eJ(e);n[t.localName]=t.no,n[t.no]=t.localName}return eG(n,e,t),n},makeEnumType:eK,getEnumType:function(e){let t=e[eW];return eB(t,"missing enum type on enum object"),t},makeExtension(e,t,i){var n;let a;return n=this,{typeName:e,extendee:t,get field(){if(!a){let t="function"==typeof i?i():i;t.name=e.split(".").pop(),t.jsonName="[".concat(e,"]"),a=n.util.newFieldList([t]).list()[0]}return a},runtime:n}}});class tW extends ez{constructor(e){super(),this.seconds=e4.zero,this.nanos=0,tH.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(tH.json.debug(e)));let i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw Error("cannot decode google.protobuf.Timestamp from JSON: invali
1d RFC 3339 string");let n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=e4.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){let t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return tW.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new tW({seconds:e4.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new tW().fromBinary(e,t)}static fromJson(e,t){return new tW().fromJson(e,t)}static fromJsonString(e,t){return new tW().fromJsonString(e,t)}static equals(e,t){return tH.util.equals(tW,e,t)}}tW.runtime=tH,tW.typeName="google.protobuf.Timestamp",tW.fields=tH.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);let tG=tH.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:tW},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:tK,repeated:!0},{no:5,name:"events",kind:"message",T:tz,repeated:!0}]),tK=tH.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:tJ,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),tJ=tH.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:tW},{no:3,name:"value",kind:"scalar",T:2}]),tz=tH.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:tW},{no:7,name:"normalized_end_timestamp",kind:"message",T:tW,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),tQ=tH.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),tY=tH.makeEnum("livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),tX=tH.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),tZ=tH.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),t$=tH.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),t0=tH.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),t1=tH.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),t2=tH.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),t3=tH.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),t4=tH.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),t9=tH.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),t6=tH.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),t5=tH.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),t8=tH.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:t7,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:iU}]),t7=tH.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),ie=tH.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:tH.getEnumType(t0),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),it=tH.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:tH.getEnumType(ii)},{no:4,name:"tracks",kind:"message",T:ic,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:ie},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:tH.getEnumType(ia)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:tH.getEnumType(t4)},{no:18,name:"kind_details",kind:"enum",T:tH.getEnumType(ir),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:il,repeated:!0}]),ii=tH.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ia=tH.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),ir=tH.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"}]),is=tH.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),io=tH.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:iu,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:tH.getEnumType(ih)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),ic=tH.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:tH.getEnumType(t$)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:tH.getEnumType(t0)},{no:10,name:"layers",kind:"message",T:iu,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:io,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:tH.getEnumType(is)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:iU},{no:19,name:"audio_features",kind:"enum",T:tH.getEnumType(t5),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:tH.getEnumType(tZ)}]),il=tH.makeMessageType("livekit.DataTrackInfo",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:tH.getEnumType(is)}]),id=tH.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),iu=tH.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:tH.getEnumType(t1)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}]),ih=tH.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),ip=tH.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:tH.getEnumType(im)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:iy,oneof:"value"},{no:3,name:"speaker",kind:"message",T:ik,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:iT,oneof:"value"},{no:7,name:"transcription",kind:"message",T:iC,oneof:"value"},{no:8,name:"metrics",kind:"message",T:tG,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:iE,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:iw,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:iP,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:iR,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:iq,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:iV,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:iH,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:ig,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),im=tH.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),ig=tH.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:tH.getEnumType(is)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),iv=tH.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:iy,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:iE,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:iw,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:iP,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:iR,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:iq,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:iV,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:iH,oneof:"value"}]),ik=tH.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:ib,repeated:!0}]),ib=tH.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),iy=tH.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),iT=tH.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),iC=tH.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:iS,repeated:!0}]),iS=tH.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),iE=tH.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),iw=tH.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),iP=tH.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),iR=tH.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:iI,oneof:"value"}]),iI=tH.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),i_=tH.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),iO=tH.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:tH.getEnumType(iD)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),iD=tH.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),iM=tH.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:tH.getEnumType(ix)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}
vendor: 16,384 bytes, line 1
1]),ix=tH.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),iA=tH.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:iN},{no:2,name:"screen",kind:"message",T:iN},{no:3,name:"resume_connection",kind:"enum",T:tH.getEnumType(t3)},{no:4,name:"disabled_codecs",kind:"message",T:iL},{no:5,name:"force_relay",kind:"enum",T:tH.getEnumType(t3)}]),iN=tH.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:tH.getEnumType(t3)}]),iL=tH.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:t7,repeated:!0},{no:2,name:"publish",kind:"message",T:t7,repeated:!0}]),iU=tH.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),ij=tH.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),iF=tH.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:tH.getEnumType(ij)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),iB=tH.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),iq=tH.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:tH.getEnumType(is)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:iF,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:iB,oneof:"content_header"}],{localName:"DataStream_Header"}),iV=tH.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),iH=tH.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),iW=tH.makeMessageType("livekit.FilterParams",()=>[{no:1,name:"include_events",kind:"scalar",T:9,repeated:!0},{no:2,name:"exclude_events",kind:"scalar",T:9,repeated:!0}]),iG=tH.makeMessageType("livekit.WebhookConfig",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"signing_key",kind:"scalar",T:9},{no:3,name:"filter_params",kind:"message",T:iW}]),iK=tH.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),iJ=tH.makeMessageType("livekit.RoomAgentDispatch",()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9}]),iz=tH.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),iQ=tH.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),iY=tH.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),iX=tH.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:nn,oneof:"message"},{no:2,name:"answer",kind:"message",T:nn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:i5,oneof:"message"},{no:4,name:"add_track",kind:"message",T:i0,oneof:"message"},{no:5,name:"mute",kind:"message",T:i8,oneof:"message"},{no:6,name:"subscription",kind:"message",T:nr,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:nc,oneof:"message"},{no:8,name:"leave",kind:"message",T:nu,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:np,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:nR,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:nO,oneof:"message"},{no:13,name:"simulate",kind:"message",T:nx,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:nm,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:nA,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:nl,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:nd,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:i1,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:i3,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:ns,oneof:"message"}]),iZ=tH.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:i7,oneof:"message"},{no:2,name:"answer",kind:"message",T:nn,oneof:"message"},{no:3,name:"offer",kind:"message",T:nn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:i5,oneof:"message"},{no:5,name:"update",kind:"message",T:na,oneof:"message"},{no:6,name:"track_published",kind:"message",T:nt,oneof:"message"},{no:8,name:"leave",kind:"message",T:nu,oneof:"message"},{no:9,name:"mute",kind:"message",T:i8,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:nf,oneof:"message"},{no:11,name:"room_update",kind:"message",T:nv,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:nb,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:nT,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:nE,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:nI,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ni,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:ne,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:nN,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:nj,oneof:"message"},{no:22,name:"request_response",kind:"message",T:nF,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:nq,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:n_,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:nK,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:nw,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:i2,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:i4,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:i9,oneof:"message"}]),i$=tH.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:iu,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:tH.getEnumType(ih)}]),i0=tH.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:tH.getEnumType(t$)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:tH.getEnumType(t0)},{no:9,name:"layers",kind:"message",T:iu,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:i$,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:tH.getEnumType(is)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:tH.getEnumType(tZ)},{no:17,name:"audio_features",kind:"enum",T:tH.getEnumType(t5),repeated:!0}]),i1=tH.makeMessageType("livekit.PublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:tH.getEnumType(is)}]),i2=tH.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:il}]),i3=tH.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),i4=tH.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:il}]),i9=tH.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:i6}}]),i6=tH.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}],{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),i5=tH.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:tH.getEnumType(iz)},{no:3,name:"final",kind:"scalar",T:8}]),i8=tH.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),i7=tH.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:t8},{no:2,name:"participant",kind:"message",T:it},{no:3,name:"other_participants",kind:"message",T:it,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ng,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:iA},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:iO},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:t7,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),ne=tH.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:ng,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:iA},{no:3,name:"server_info",kind:"message",T:iO},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),nt=tH.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ic}]),ni=tH.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),nn=tH.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),na=tH.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:it,repeated:!0}]),nr=tH.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:i_,repeated:!0}]),ns=tH.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:no,repeated:!0}]),no=tH.makeMessageType("livekit.UpdateDataSubscription.Update",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:id}],{localName:"UpdateDataSubscription_Update"}),nc=tH.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:tH.getEnumType(t1)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),nl=tH.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:tH.getEnumType(t5),repeated:!0}]),nd=tH.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),nu=tH.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:tH.getEnumType(t4)},{no:3,name:"action",kind:"enum",T:tH.getEnumType(nh)},{no:4,name:"regions",kind:"message",T:nL}]),nh=tH.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),np=tH.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:iu,repeated:!0}]),nm=tH.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),ng=tH.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),nf=tH.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:ib,repeated:!0}]),nv=tH.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:t8}]),nk=tH.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:tH.getEnumType(t2)},{no:3,name:"score",kind:"scalar",T:2}]),nb=tH.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:nk,repeated:!0}]),ny=tH.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:tH.getEnumType(iQ)}]),nT=tH.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:ny,repeated:!0}]),nC=tH.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:tH.getEnumType(t1)},{no:2,name:"enabled",kind:"scalar",T:8}]),nS=tH.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:nC,repeated:!0}]),nE=tH.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:nC,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:nS,repeated:!0}]),nw=tH.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:iK,repeated:!0}]),nP=tH.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),nR=tH.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:nP,repeated:!0}]),nI=tH.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),n_=tH.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:t8},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:it},{no:4,name:"other_participants",kind:"message",T:it,repeated:!0}]),nO=tH.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:nn},{no:2,name:"subscription",kind:"message",T:nr},{no:3,name:"publish_tracks",kind:"message",T:nt,repeated:!0},{no:4,name:"data_channels",kind:"message",T:nM,repeated:!0},{no:5,name:"offer",kind:"message",T:nn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:nD,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:i2,repeated:!0}]),nD=tH.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),nM=tH.makeMessageType("livekit.DataC
1hannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:tH.getEnumType(iz)}]),nx=tH.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:tH.getEnumType(iY),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),nA=tH.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),nN=tH.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),nL=tH.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:nU,repeated:!0}]),nU=tH.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),nj=tH.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:tH.getEnumType(t6)}]),nF=tH.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:tH.getEnumType(nB)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:i5,oneof:"request"},{no:5,name:"add_track",kind:"message",T:i0,oneof:"request"},{no:6,name:"mute",kind:"message",T:i8,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:nm,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:nl,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:nd,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:i1,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:i3,oneof:"request"}]),nB=tH.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),nq=tH.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),nV=tH.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}]),nH=tH.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:iM},{no:2,name:"connection_settings",kind:"message",T:nV},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:i0,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:nn},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:tH.getEnumType(t9)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:nO}]),nW=tH.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:tH.getEnumType(nG)},{no:2,name:"join_request",kind:"scalar",T:12}]),nG=tH.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),nK=tH.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]),nJ=tH.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),nz=tH.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),nQ=tH.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),nY=tH.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),nX=tH.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"}]),nZ=tH.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),n$=tH.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),n0=tH.makeMessageType("livekit.RoomCompositeEgressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:15,name:"audio_mixing",kind:"enum",T:tH.getEnumType(nZ)},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:n1,oneof:"output"},{no:7,name:"stream",kind:"message",T:n7,oneof:"output"},{no:10,name:"segments",kind:"message",T:n2,oneof:"output"},{no:8,name:"preset",kind:"enum",T:tH.getEnumType(n$),oneof:"options"},{no:9,name:"advanced",kind:"message",T:ae,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:n1,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:n7,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:n2,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:n3,repeated:!0},{no:16,name:"webhooks",kind:"message",T:iG,repeated:!0}]),n1=tH.makeMessageType("livekit.EncodedFileOutput",()=>[{no:1,name:"file_type",kind:"enum",T:tH.getEnumType(nJ)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:n4,oneof:"output"},{no:4,name:"gcp",kind:"message",T:n9,oneof:"output"},{no:5,name:"azure",kind:"message",T:n6,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:n5,oneof:"output"}]),n2=tH.makeMessageType("livekit.SegmentedFileOutput",()=>[{no:1,name:"protocol",kind:"enum",T:tH.getEnumType(nz)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:tH.getEnumType(nQ)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:n4,oneof:"output"},{no:6,name:"gcp",kind:"message",T:n9,oneof:"output"},{no:7,name:"azure",kind:"message",T:n6,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:n5,oneof:"output"}]),n3=tH.makeMessageType("livekit.ImageOutput",()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:tH.getEnumType(nY)},{no:6,name:"image_codec",kind:"enum",T:tH.getEnumType(tX)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:n4,oneof:"output"},{no:9,name:"gcp",kind:"message",T:n9,oneof:"output"},{no:10,name:"azure",kind:"message",T:n6,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:n5,oneof:"output"}]),n4=tH.makeMessageType("livekit.S3Upload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:11,name:"session_token",kind:"scalar",T:9},{no:12,name:"assume_role_arn",kind:"scalar",T:9},{no:13,name:"assume_role_external_id",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9},{no:10,name:"proxy",kind:"message",T:n8}]),n9=tH.makeMessageType("livekit.GCPUpload",()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"proxy",kind:"message",T:n8}]),n6=tH.makeMessageType("livekit.AzureBlobUpload",()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}]),n5=tH.makeMessageType("livekit.AliOSSUpload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}]),n8=tH.makeMessageType("livekit.ProxyConfig",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"password",kind:"scalar",T:9}]),n7=tH.makeMessageType("livekit.StreamOutput",()=>[{no:1,name:"protocol",kind:"enum",T:tH.getEnumType(nX)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}]),ae=tH.makeMessageType("livekit.EncodingOptions",()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:tH.getEnumType(tQ)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:tH.getEnumType(tY)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1}]),at=tH.makeMessageType("livekit.AutoParticipantEgress",()=>[{no:1,name:"preset",kind:"enum",T:tH.getEnumType(n$),oneof:"options"},{no:2,name:"advanced",kind:"message",T:ae,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:n1,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:n2,repeated:!0}]),ai=tH.makeMessageType("livekit.AutoTrackEgress",()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:n4,oneof:"output"},{no:3,name:"gcp",kind:"message",T:n9,oneof:"output"},{no:4,name:"azure",kind:"message",T:n6,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:n5,oneof:"output"}]),an=tH.makeMessageType("livekit.RoomEgress",()=>[{no:1,name:"room",kind:"message",T:n0},{no:3,name:"participant",kind:"message",T:at},{no:2,name:"tracks",kind:"message",T:ai}]);()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:3,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:11,name:"metadata",kind:"scalar",T:9},{no:5,name:"egress",kind:"message",T:an},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8},{no:10,name:"agents",kind:"message",T:iJ,repeated:!0}];var aa={exports:{}},ar=aa.exports,as=function(){var e;return Z?aa.exports:(Z=1,e=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],a={},r=null;function s(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),a=0;a<n.length;a++){var r=n[a];
1this[r]=a<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function l(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function d(n,a,r){var c;return"debug"===(c=n)&&(c="log"),typeof console!==t&&("trace"===c&&i?o:void 0!==console[c]?s(console,c):void 0!==console.log?s(console,"log"):e)||l.apply(this,arguments)}function u(e,i){var s,o,l,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),a=i.indexOf(n+"=");-1!==a&&(e=/^([^;]+)/.exec(i.slice(a+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||d,u.getLevel=function(){return null!=l?l:null!=o?o:s},u.setLevel=function(e,i){return l=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{window.localStorage[h]=i;return}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(l),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){if(l=null,typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(r!==u&&(s=m(r.getLevel())),c.call(u),r===u)for(var e in a)a[e].rebuild()},s=m(r?r.getLevel():"WARN");var g=p();null!=g&&(l=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw TypeError("You must supply a name when creating a logger.");var t=a[e];return t||(t=a[e]=new u(e,r.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=h),r},r.getLoggers=function(){return a},r.default=r,r},aa.exports?aa.exports=e():ar.log=e(),aa.exports)}();(p=$||($={}))[p.trace=0]="trace",p[p.debug=1]="debug",p[p.info=2]="info",p[p.warn=3]="warn",p[p.error=4]="error",p[p.silent=5]="silent",(m=ee||(ee={})).Default="livekit",m.Room="livekit-room",m.TokenSource="livekit-token-source",m.Participant="livekit-participant",m.Track="livekit-track",m.Publication="livekit-track-publication",m.Engine="livekit-engine",m.Signal="livekit-signal",m.PCManager="livekit-pc-manager",m.PCTransport="livekit-pc-transport",m.E2EE="lk-e2ee";let ao=as.getLogger("livekit");function ac(e){let t=as.getLogger(e);return t.setDefaultLevel(ao.getLevel()),t}Object.values(ee).map(e=>as.getLogger(e)),ao.setDefaultLevel($.info);let al=as.getLogger("lk-e2ee"),ad=[0,300,1200,2700,4800,7e3,7e3,7e3,7e3,7e3];class au{constructor(e){this._retryDelays=void 0!==e?[...e]:ad}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function ah(e,t,i,n){return new(i||(i=Promise))(function(a,r){function s(e){try{c(n.next(e))}catch(e){r(e)}}function o(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?a(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(s,o)}c((n=n.apply(e,t||[])).next())})}function ap(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,a){var r,s,o;r=n,s=a,o=(t=e[i](t)).done,Promise.resolve(t.value).then(function(e){r({value:e,done:o})},s)})}}}"function"==typeof SuppressedError&&SuppressedError;var am={exports:{}},ag=function(){if(et)return am.exports;et=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}am.exports=a,am.exports.once=function(e,t){return new Promise(function(i,n){var a,r,s;function o(i){e.removeListener(t,c),n(i)}function c(){"function"==typeof e.removeListener&&e.removeListener("error",o),i([].slice.call(arguments))}m(e,t,c,{once:!0}
1),"error"!==t&&(a=e,r=o,s={once:!0},"function"==typeof a.on&&m(a,"error",r,s))})},a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var r=10;function s(e){if("function"!=typeof e)throw TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){if(s(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),c=r[t]),void 0===c)c=r[t]=i,++e._eventsCount;else if("function"==typeof c?c=r[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(a=o(e))>0&&c.length>a&&!c.warned){c.warned=!0;var a,r,c,l=Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,console&&console.warn&&console.warn(l)}return e}function l(){if(!this.fired)return(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0==arguments.length)?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},a=l.bind(n);return a.listener=i,n.wrapFn=a,a}function u(e,t,i){var n=e._events;if(void 0===n)return[];var a=n[t];return void 0===a?[]:"function"==typeof a?i?[a.listener||a]:[a]:i?function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(a):p(a,a.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else if("function"==typeof e.addEventListener)e.addEventListener(t,function a(r){n.once&&e.removeEventListener(t,a),i(r)});else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}return Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),a.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},a.prototype.getMaxListeners=function(){return o(this)},a.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var a="error"===e,r=this._events;if(void 0!==r)a=a&&void 0===r.error;else if(!a)return!1;if(a){if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var s,o=Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else for(var l=c.length,d=p(c,l),n=0;n<l;++n)i(d[n],this,t);return!0},a.prototype.addListener=function(e,t){return c(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return c(this,e,t,!0)},a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var i,n,a,r,o;if(s(t),void 0===(n=this._events)||void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(a=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){o=i[r].listener,a=r;break}if(a<0)return this;0===a?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,a),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit
1("removeListener",e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0==arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0==arguments.length){var a,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(a=r[n])&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},a.prototype.listeners=function(e){return u(this,e,!0)},a.prototype.rawListeners=function(e){return u(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},a.prototype.listenerCount=h,a.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},am.exports}();let af=!0,av=!0;function ak(e,t,i){let n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function ab(e,t,i){if(!e.RTCPeerConnection)return;let n=e.RTCPeerConnection.prototype,a=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return a.apply(this,arguments);let r=e=>{let t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,r),a.apply(this,[e,r])};let r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(i))return r.apply(this,arguments);let n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function ay(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(af=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function aT(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(av=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function aC(){"object"==typeof window&&!af&&"u">typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}function aS(e,t){av&&console.warn(e+" is deprecated, please use "+t+" instead.")}function aE(e){return"[object Object]"===Object.prototype.toString.call(e)}function aw(e,t,i){let n=i?"outbound-rtp":"inbound-rtp",a=new Map;if(null===t)return a;let r=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&r.push(e)}),r.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&function e(t,i,n){!i||n.has(i.id)||(n.set(i.id,i),Object.keys(i).forEac
vendor: 42,128 bytes, line 1
1h(a=>{a.endsWith("Id")?e(t,t.get(i[a]),n):a.endsWith("Ids")&&i[a].forEach(i=>{e(t,t.get(i),n)})}))}(e,i,a)})}),a}function aP(e,t){let i=e&&e.navigator;if(!i.mediaDevices)return;let n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;let n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);let a=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[a("min",i)]=n.ideal,t.optional.push(e),(e={})[a("max",i)]=n.ideal):e[a("",i)]=n.ideal,t.optional.push(e)}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[a("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[a(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},a=function(e,a){if(t.version>=61)return a(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){let t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let r=e.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});let s=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&!(i.mediaDevices.getSupportedConstraints&&i.mediaDevices.getSupportedConstraints().facingMode&&!s)){let t;if(delete e.video.facingMode,"environment"===r.exact||"environment"===r.ideal?t=["back","rear"]:("user"===r.exact||"user"===r.ideal)&&(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let s=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=r.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),aC("chrome: "+JSON.stringify(e)),a(e)})}e.video=n(e.video)}return aC("chrome: "+JSON.stringify(e)),a(e)},r=function(e){return t.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=(function(e,t,n){a(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(r(e))})})}).bind(i),i.mediaDevices.getUserMedia){let e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return a(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(r(e))))}}}function aR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function aI(e){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)ab(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};let a=new Event("track");a.track=i.track,a.receiver=n,a.transceiver={receiver:n},a.streams=[t.stream],this.dispatchEvent(a)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};let a=new Event("track");a.track=i,a.receiver=n,a.transceiver={receiver:n},a.streams=[t.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}}function a_(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let a=i.apply(this,arguments);return a||(a=t(this,e),this._senders.push(a)),a};let n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);let t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function aO(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>aw(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),ab(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>aw(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e,t,i,n=arguments[0];return(this.getSenders().forEach(t=>{t.track===n&&(e?i=!0:e=t)}),this.getReceivers().forEach(e=>(e.track===n&&(t?i=!0:t=e),e.track===n)),i||e&&t)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():t?t.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function aD(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});let t=this.getSenders();i.apply(this,arguments);let n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};let a=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),a.apply(this,arguments)}}function aM(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return aD(e);let i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){let i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};let a=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],a=e._streams[n.id];i=i.replace(RegExp(a.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},a.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let a=this._streams[i.id];if(a)a.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){let e=arguments,t=arguments.length&&"function"==typeof arguments[0];return t?i.apply(this,[t=>{let i=r(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>r(this,e))}})[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e,t;let i;return arguments.length&&arguments[0].type?(arguments[0]=(e=this,t=arguments[0],i=t.sdp,Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],a=e._streams[n.id];i=i.replace(RegExp(n.id,"g"),a.id)}),new RTCSessionDescription({type:t.type,sdp:i})),s.apply(this,arguments)):s.apply(this,arguments)};let o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=o.get.apply(this);return""===e.type?e:r(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){let t;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ax(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]})}function aA(e,t){ab(e,"negotiationneeded",e=>{let i=e.target;if(!(t.version<72)&&(!i.getConfiguration||"plan-b"!==i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var aN=Object.freeze({__proto__:null,fixNegotiationNeeded:aA,shimAddTrackRemoveTrack:aM,shimAddTrackRemoveTrackWithNative:aD,shimGetSendersWithDtmf:a_,shimGetUserMedia:aP,shimMediaStream:aR,shimOnTrack:aI,shimPeerConnection:ax,shimSenderReceiverGetStats:aO});function aL(e,t){let i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){aS("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){let e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(e((i=JSON.parse(JSON.stringify(i))).audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){let t=n.prototype.getSettings;n.prototype.getSettings=function(){let i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){let t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(e(i=JSON.parse(JSON.stringify(i)),"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function aU(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function aj(e,t){if("object"!=typeof e||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]});let i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,a,r]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!a)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(a,r)}}function aF(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function aB(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),ab(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function aq(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){aS("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function aV(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function aH(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let i=(e=[...e]).length>0;i&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});let n=t.apply(this,arguments);if(i){let{sender:t}=n,i=t.getParameters();"encodings"in i&&(1!==i.encodings.length||0!==Object.keys(i.encodings[0]).length)||(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function aW(e){if(!("object"==typeof e&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function aG(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function aK(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var aJ=Object.freeze({__proto__:null,shimAddTransceiver:aH,shimCreateAnswer:aK,shimCreateOffer:aG,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){let e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:aW,shimGetUserMedia:aL,shimOnTrack:aU,shimPeerConnection:aj,shimRTCDataChannel:aV,shimReceiverGetStats:aB,shimRemoveStream:aq,shimSenderGetStats:aF});function az(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=Array(i>1?i-1:0),a=1;a<i;a++)n[a-1]=arguments[a];return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);let i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function aQ(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function aY(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,a=t.setLocalDescription,r=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],a=i.apply(this,[n]);return t?(a.then(e,t),Promise.resolve()):a},t.createAnswer=function(e,t){let i=arguments.length>=2?arguments[2]:arguments[0],a=n.apply(this,[i]);return t?(a.then(e,t),Promise.resolve()):a};let o=function(e,t,i){let n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,t.setRemoteDescription=o=function(e,t,i){let n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=function(e,t,i){let n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n}}function aX(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(aZ(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}).bind(t))}function aZ(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(t){return aE(t)?Object.keys(t).reduce(function(i,n){let a=aE(t[n]),r=a?e(t[n]):t[n],s=a&&!Object.keys(r).length;return void 0===r||s?i:Object.assign(i,{[n]:r})},{}):t}(e.video)}):e}function a$(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){let t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(aS("RTCIceServer.url","RTCIceServer.urls"),(n=JSON.parse(JSON.stringify(n))).urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function a0(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function a1(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function a2(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var a3=Object.freeze({__proto__:null,shimAudioContext:a2,shimCallbacksAPI:aY,shimConstraints:aZ,shimCreateOfferLegacy:a1,shimGetUserMedia:aX,shimLocalStreamsAPI:az,shimRTCIceServerUrls:a$,shimRemoteStreamsAPI:aQ,shimTrackEventTransceiver:a0}),a4={exports:{}},a9=function(){let e;return ei?a4.exports:(ei=1,(e={}).generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},e.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},e.getDescription=function(t){let i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){let i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(e=>0===e.indexOf(i))},e.parseCandidate=function(e){let t,i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},e.writeCandidate=function(e){let t=[];t.push(e.foundation);let i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},e.parseIceOptions=function(e){return e.substring(14).split(" ")},e.parseRtpMap=function(e){let t=e.substring(9).split(" "),i={payloadType:parseInt(t.shift(),10)};return i.name=(t=t[0].split("/"))[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},e.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);let i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},e.parseExtmap=function(e){let t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},e.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},e.parseFmtp=function(e){let t,i={},n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i[(t=n[e].trim().split("="))[0].trim()]=t[1];return i},e.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){let n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},e.parseRtcpFb=function(e){let t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},e.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},e.parseSsrcMedia=function(e){let t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},e.parseSsrcGroup=function(e){let t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},e.getMid=function(t){let i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(e){let t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},e.parseCryptoLine=function(e){let t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+("object"==typeof t.keyParams?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+"\r\n"},e.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;let t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){let n=e.matchPrefix(t+i,"a=ice-ufrag:")[0],a=e.matchPrefix(t+i,"a=ice-pwd:")[0];return n&&a?{usernameFragment:n.substring(12),password:a.substring(10)}:null},e.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},e.parseRtpParameters=function(t){let i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=e.splitLines(t)[0].split(" ");i.profile=n[2];for(let a=3;a<n.length;a++){let r=n[a],s=e.matchPrefix(t,"a=rtpmap:"+r+" ")[0];if(s){let n=e.parseRtpMap(s),a=e.matchPrefix(t,"a=fmtp:"+r+" ");switch(n.parameters=a.length?e.parseFmtp(a[0]):{},n.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+r+" ").map(e.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}e.matchPrefix(t,"a=extmap:").forEach(t=>{i.headerExtensions.push(e.parseExtmap(t))});let a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(e=>{a.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},e.writeRtpDescription=function(t,i){let n="";n+="m="+t+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(t=>{n+=e.writeRtpMap(t),n+=e.writeFmtp(t),n+=e.writeRtcpFb(t)});let a=0;return i.codecs.forEach(e=>{e.maxptime>a&&(a=e.maxptime)}),a>0&&(n+="a=maxptime:"+a+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(t=>{n+=e.writeExtmap(t)}),n},e.parseRtpEncodingParameters=function(t){let i,n=[],a=e.parseRtpParameters(t),r=-1!==a.fecMechanisms.indexOf("RED"),s=-1!==a.fecMechanisms.indexOf("ULPFEC"),o=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"cname"===e.attribute),c=o.length>0&&o[0].ssrc,l=e.matchPrefix(t,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));l.length>0&&l[0].length>1&&l[0][0]===c&&(i=l[0][1]),a.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&i&&(t.rtx={ssrc:i}),n.push(t),r&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:s?"red+ulpfec":"red"},n.push(t))}}),0===n.length&&c&&n.push({ssrc:c});let d=e.matchPrefix(t,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,n.forEach(e=>{e.maxBitrate=d})),n},e.parseRtcpParameters=function(t){let i={},n=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);let a=e.matchPrefix(t,"a=rtcp-rsize");return i.reducedSize=a.length>0,i.compound=0===a.length,i.mux=e.matchPrefix(t,"a=rtcp-mux").length>0,i},e.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},e.parseMsid=function(t){let i,n=e.matchPrefix(t,"a=msid:");if(1===n.length)return{stream:(i=n[0].substring(7).split(" "))[0],track:i[1]};let a=e.matchPrefix(t,"a=ssrc:").map(t=>e.parseSsrcMedia(t)).filter(e=>"msid"===e.attribute);if(a.length>0)return{stream:(i=a[0].value.split(" "))[0],track:i[1]}},e.parseSctpDescription=function(t){let i,n=e.parseMLine(t),a=e.matchPrefix(t,"a=max-message-size:");a.length>0&&(i=parseInt(a[0].substring(19),10)),isNaN(i)&&(i=65536);let r=e.matchPrefix(t,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};let s=e.matchPrefix(t,"a=sctpmap:");if(s.length>0){let e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},e.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,n){return"v=0\r\no="+(n||"thisisadapterortc")+" "+(t||e.generateSessionId())+" "+(void 0!==i?i:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},e.getDirection=function(t,i){let n=e.splitLines(t);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(e){return"0"===e.split(" ",2)[1]},e.parseMLine=function(t){let i=e.splitLines(t)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(t){let i=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(t){if("string"!=typeof t||0===t.length)return!1;let i=e.splitLines(t);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},a4.exports=e,a4.exports)}(),a6=a9&&a9.__esModule&&Object.prototype.hasOwnProperty.call(a9,"default")?a9.default:a9,a5=(g={__proto__:null,default:a6},[a9].forEach(function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach(function(t){if("default"!==t&&!(t in g)){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(g,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}})}),Object.freeze(g));function a8(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let i=new t(e),n=a6.parseCandidate(e.candidate);for(let e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,ab(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function a7(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||ab(e,"icecandidate",e=>{if(e.candidate){let t=a6.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[t.priority>>24])}return e})}function re(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});let i=function(e){if(!e||!e.sdp)return!1;let t=a6.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=a6.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})},n=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return -1;let i=parseInt(t[1],10);return i!=i?-1:i},a=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:0x7ffffff5:t.version<60?57===t.version?65535:65536:0x7ffffff5),i},r=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);let a=a6.matchPrefix(e.sdp,"a=max-message-size:");return a.length>0?n=parseInt(a[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=0x7ffffff5),n},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){let e,t=n(arguments[0]),i=a(t),s=r(arguments[0],t);e=0===i&&0===s?1/0:0===i||0===s?Math.max(i,s):Math.min(i,s);let o={};Object.defineProperty(o,"maxMessageSize",{get:()=>e}),this._sctp=o}return s.apply(this,arguments)}}function rt(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){let i=e.send;e.send=function(){let n=arguments[0],a=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&a>t.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}let i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=i.apply(this,arguments);return t(e,this),e},ab(e,"datachannel",e=>(t(e.channel,e.target),e))}function ri(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}
1),["setLocalDescription","setRemoteDescription"].forEach(e=>{let i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function rn(e,t){if(!e.RTCPeerConnection||"chrome"===t.browser&&t.version>=71||"safari"===t.browser&&t._safariVersion>=13.1)return;let i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){let i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function ra(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function rr(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(!(e={type:e.type,sdp:e.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var rs=Object.freeze({__proto__:null,removeExtmapAllowMixed:rn,shimAddIceCandidateNullOrEmpty:ra,shimConnectionState:ri,shimMaxMessageSize:re,shimParameterlessSetLocalDescription:rr,shimRTCIceCandidate:a8,shimRTCIceCandidateRelayProtocol:a7,shimSendThrowTypeError:rt});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},i=function(e){let t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;let{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){let e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}return i.mozGetUserMedia?(t.browser="firefox",t.version=parseInt(ak(i.userAgent,/Firefox\/(\d+)\./,1))):i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection?(t.browser="chrome",t.version=parseInt(ak(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2))):e.RTCPeerConnection&&i.userAgent.match(/AppleWebKit\/(\d+)\./)?(t.browser="safari",t.version=parseInt(ak(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=ak(i.userAgent,/Version\/(\d+(\.?\d+))/,1)):t.browser="Not a supported browser.",t}(e),n={browserDetails:i,commonShim:rs,extractVersion:ak,disableLog:ay,disableWarnings:aT,sdp:a5};switch(i.browser){case"chrome":if(!aN||!ax||!t.shimChrome){aC("Chrome shim is not included in this adapter release.");break}if(null===i.version){aC("Chrome shim can not determine version, not shimming.");break}aC("adapter.js shimming chrome."),n.browserShim=aN,ra(e,i),rr(e),aP(e,i),aR(e),ax(e,i),aI(e),aM(e,i),a_(e),aO(e),aA(e,i),a8(e),a7(e),ri(e),re(e,i),rt(e),rn(e,i);break;case"firefox":if(!aJ||!aj||!t.shimFirefox){aC("Firefox shim is not included in this adapter release.");break}aC("adapter.js shimming firefox."),n.browserShim=aJ,ra(e,i),rr(e),aL(e,i),aj(e,i),aU(e),aq(e),aF(e),aB(e),aV(e),aH(e),aW(e),aG(e),aK(e),a8(e),ri(e),re(e,i),rt(e);break;case"safari":if(!a3||!t.shimSafari){aC("Safari shim is not included in this adapter release.");break}aC("adapter.js shimming safari."),n.browserShim=a3,ra(e,i),rr(e),a$(e),a1(e),aY(e),az(e),aQ(e),a0(e),aX(e),a2(e),a8(e),a7(e),re(e,i),rt(e),rn(e,i);break;default:aC("Unsupported browser!")}}({window:"u"<typeof window?void 0:window});class ro extends(en=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}ro.resolve=e=>Reflect.get(en,"resolve",ro).call(ro,e);let rc=/version\/(\d+(\.?_?\d+)+)/i;function rl(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(void 0===e&&"u"<typeof navigator)return;let i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===n||t){let e=rd.find(e=>{let{test:t}=e;return t.test(i)});n=null==e?void 0:e.describe(i)}return n}let rd=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:ru(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:rh(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:ru(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:rh(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:ru(rc,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:rh(e)})}];function ru(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=t.match(e);return n&&n.length>=i&&n[i]||""}function rh(e){return e.includes("mac os")?ru(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}
1class rp extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==i?void 0:i.cause)&&(this.cause=null==i?void 0:i.cause)}}class rm extends rp{}(f=ea||(ea={}))[f.NotAllowed=0]="NotAllowed",f[f.ServerUnreachable=1]="ServerUnreachable",f[f.InternalError=2]="InternalError",f[f.Cancelled=3]="Cancelled",f[f.LeaveRequest=4]="LeaveRequest",f[f.Timeout=5]="Timeout",f[f.WebSocket=6]="WebSocket",f[f.ServiceNotFound=7]="ServiceNotFound";class rg extends rm{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=ea[t]}static notAllowed(e,t,i){return new rg(e,ea.NotAllowed,t,i)}static timeout(e){return new rg(e,ea.Timeout)}static leaveRequest(e,t){return new rg(e,ea.LeaveRequest,void 0,t)}static internal(e,t){return new rg(e,ea.InternalError,void 0,t)}static cancelled(e){return new rg(e,ea.Cancelled)}static serverUnreachable(e,t){return new rg(e,ea.ServerUnreachable,t)}static websocket(e,t,i){return new rg(e,ea.WebSocket,t,i)}static serviceNotFound(e,t){return new rg(e,ea.ServiceNotFound,void 0,t)}}class rf extends rp{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class rv extends rp{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class rk extends rp{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class rb extends rp{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class ry extends rp{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class rT extends rp{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class rC extends rm{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:nB[t]}}(v=er||(er={}))[v.AlreadyOpened=0]="AlreadyOpened",v[v.AbnormalEnd=1]="AbnormalEnd",v[v.DecodeFailed=2]="DecodeFailed",v[v.LengthExceeded=3]="LengthExceeded",v[v.Incomplete=4]="Incomplete",v[v.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",v[v.EncryptionTypeMismatch=8]="EncryptionTypeMismatch";class rS extends rm{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=er[t]}}class rE extends rp{constructor(e){super(18,e),this.name="SignalReconnectError"}}(k=es||(es={})).PermissionDenied="PermissionDenied",k.NotFound="NotFound",k.DeviceInUse="DeviceInUse",k.Other="Other",(b=es||(es={})).getFailure=function(e){if(e&&"name"in e)return"NotFoundError"===e.name||"DevicesNotFoundError"===e.name?b.NotFound:"NotAllowedError"===e.name||"PermissionDeniedError"===e.name?b.PermissionDenied:"NotReadableError"===e.name||"TrackStartError"===e.name?b.DeviceInUse:b.Other};class rw{}rw.setTimeout=function(){return setTimeout(...arguments)},rw.setInterval=function(){return setInterval(...arguments)},rw.clearTimeout=function(){return clearTimeout(...arguments)},rw.clearInterval=function(){return clearInterval(...arguments)},(y=eo||(eo={})).Connected="connected",y.Reconnecting="reconnecting",y.SignalReconnecting="signalReconnecting",y.Reconnected="reconnected",y.Disconnected="disconnected",y.ConnectionStateChanged="connectionStateChanged",y.Moved="moved",y.MediaDevicesChanged="mediaDevicesChanged",y.ParticipantConnected="participantConnected",y.ParticipantDisconnected="participantDisconnected",y.TrackPublished="trackPublished",y.TrackSubscribed="trackSubscribed",y.TrackSubscriptionFailed="trackSubscriptionFailed",y.TrackUnpublished="trackUnpublished",y.TrackUnsubscribed="trackUnsubscribed",y.TrackMuted="trackMuted",y.TrackUnmuted="trackUnmuted",y.LocalTrackPublished="localTrackPublished",y.LocalTrackUnpublished="localTrackUnpublished",y.LocalAudioSilenceDetected="localAudioSilenceDetected",y.ActiveSpeakersChanged="activeSpeakersChanged",y.ParticipantMetadataChanged="participantMetadataChanged",y.ParticipantNameChanged="participantNameChanged",y.ParticipantAttributesChanged="participantAttributesChanged",y.ParticipantActive="participantActive",y.RoomMetadataChanged="roomMetadataChanged",y.DataReceived="dataReceived",y.SipDTMFReceived="sipDTMFReceived",y.TranscriptionReceived="transcriptionReceived",y.ConnectionQualityChanged="connectionQualityChanged",y.TrackStreamStateChanged="trackStreamStateChanged",y.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",y.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",y.AudioPlaybackStatusChanged="audioPlaybackChanged",y.VideoPlaybackStatusChanged="videoPlaybackChanged",y.MediaDevicesError="mediaDevicesError",
1y.ParticipantPermissionsChanged="participantPermissionsChanged",y.SignalConnected="signalConnected",y.RecordingStatusChanged="recordingStatusChanged",y.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",y.EncryptionError="encryptionError",y.DCBufferStatusChanged="dcBufferStatusChanged",y.ActiveDeviceChanged="activeDeviceChanged",y.ChatMessage="chatMessage",y.LocalTrackSubscribed="localTrackSubscribed",y.MetricsReceived="metricsReceived",(T=ec||(ec={})).TrackPublished="trackPublished",T.TrackSubscribed="trackSubscribed",T.TrackSubscriptionFailed="trackSubscriptionFailed",T.TrackUnpublished="trackUnpublished",T.TrackUnsubscribed="trackUnsubscribed",T.TrackMuted="trackMuted",T.TrackUnmuted="trackUnmuted",T.LocalTrackPublished="localTrackPublished",T.LocalTrackUnpublished="localTrackUnpublished",T.LocalTrackCpuConstrained="localTrackCpuConstrained",T.LocalSenderCreated="localSenderCreated",T.ParticipantMetadataChanged="participantMetadataChanged",T.ParticipantNameChanged="participantNameChanged",T.DataReceived="dataReceived",T.SipDTMFReceived="sipDTMFReceived",T.TranscriptionReceived="transcriptionReceived",T.IsSpeakingChanged="isSpeakingChanged",T.ConnectionQualityChanged="connectionQualityChanged",T.TrackStreamStateChanged="trackStreamStateChanged",T.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",T.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",T.TrackCpuConstrained="trackCpuConstrained",T.MediaDevicesError="mediaDevicesError",T.AudioStreamAcquired="audioStreamAcquired",T.ParticipantPermissionsChanged="participantPermissionsChanged",T.PCTrackAdded="pcTrackAdded",T.AttributesChanged="attributesChanged",T.LocalTrackSubscribed="localTrackSubscribed",T.ChatMessage="chatMessage",T.Active="active",(C=el||(el={})).TransportsCreated="transportsCreated",C.Connected="connected",C.Disconnected="disconnected",C.Resuming="resuming",C.Resumed="resumed",C.Restarting="restarting",C.Restarted="restarted",C.SignalResumed="signalResumed",C.SignalRestarted="signalRestarted",C.Closing="closing",C.MediaTrackAdded="mediaTrackAdded",C.ActiveSpeakersUpdate="activeSpeakersUpdate",C.DataPacketReceived="dataPacketReceived",C.RTPVideoMapUpdate="rtpVideoMapUpdate",C.DCBufferStatusChanged="dcBufferStatusChanged",C.ParticipantUpdate="participantUpdate",C.RoomUpdate="roomUpdate",C.SpeakersChanged="speakersChanged",C.StreamStateChanged="streamStateChanged",C.ConnectionQualityUpdate="connectionQualityUpdate",C.SubscriptionError="subscriptionError",C.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",C.RemoteMute="remoteMute",C.SubscribedQualityUpdate="subscribedQualityUpdate",C.LocalTrackUnpublished="localTrackUnpublished",C.LocalTrackSubscribed="localTrackSubscribed",C.Offline="offline",C.SignalRequestResponse="signalRequestResponse",C.SignalConnected="signalConnected",C.RoomMoved="roomMoved",(S=ed||(ed={})).Message="message",S.Muted="muted",S.Unmuted="unmuted",S.Restarted="restarted",S.Ended="ended",S.Subscribed="subscribed",S.Unsubscribed="unsubscribed",S.CpuConstrained="cpuConstrained",S.UpdateSettings="updateSettings",S.UpdateSubscription="updateSubscription",S.AudioPlaybackStarted="audioPlaybackStarted",S.AudioPlaybackFailed="audioPlaybackFailed",S.AudioSilenceDetected="audioSilenceDetected",S.VisibilityChanged="visibilityChanged",S.VideoDimensionsChanged="videoDimensionsChanged",S.VideoPlaybackStarted="videoPlaybackStarted",S.VideoPlaybackFailed="videoPlaybackFailed",S.ElementAttached="elementAttached",S.ElementDetached="elementDetached",S.UpstreamPaused="upstreamPaused",S.UpstreamResumed="upstreamResumed",S.SubscriptionPermissionChanged="subscriptionPermissionChanged",S.SubscriptionStatusChanged="subscriptionStatusChanged",S.SubscriptionFailed="subscriptionFailed",S.TrackProcessorUpdate="trackProcessorUpdate",S.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",S.TranscriptionReceived="transcriptionReceived",S.TimeSyncUpdate="timeSyncUpdate",S.PreConnectBufferFlushed="preConnectBufferFlushed";class rP{constructor(e,t,i,n,a){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(void 0!==t&&void 0!==i)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:a};else throw TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}let rR=["vp8","h264"],rI=["vp8","h264","vp9","av1","h265"],r_=function(e){return!!rR.find(t=>t===e)};(E=eu||(eu={}))[E.PREFER_REGRESSION=0]="PREFER_REGRESSION",E[E.SIMULCAST=1]="SIMULCAST",E[E.REGRESSION=2]="REGRESSION",(w=eh||(eh={})).telephone={maxBitrate:12e3}
1,w.speech={maxBitrate:24e3},w.music={maxBitrate:48e3},w.musicStereo={maxBitrate:64e3},w.musicHighQuality={maxBitrate:96e3},w.musicHighQualityStereo={maxBitrate:128e3};let rO={h90:new rP(160,90,9e4,20),h180:new rP(320,180,16e4,20),h216:new rP(384,216,18e4,20),h360:new rP(640,360,45e4,20),h540:new rP(960,540,8e5,25),h720:new rP(1280,720,17e5,30),h1080:new rP(1920,1080,3e6,30),h1440:new rP(2560,1440,5e6,30),h2160:new rP(3840,2160,8e6,30)},rD={h120:new rP(160,120,7e4,20),h180:new rP(240,180,125e3,20),h240:new rP(320,240,14e4,20),h360:new rP(480,360,33e4,20),h480:new rP(640,480,5e5,20),h540:new rP(720,540,6e5,25),h720:new rP(960,720,13e5,30),h1080:new rP(1440,1080,23e5,30),h1440:new rP(1920,1440,38e5,30)},rM={h360fps3:new rP(640,360,2e5,3,"medium"),h360fps15:new rP(640,360,4e5,15,"medium"),h720fps5:new rP(1280,720,8e5,5,"medium"),h720fps15:new rP(1280,720,15e5,15,"medium"),h720fps30:new rP(1280,720,2e6,30,"medium"),h1080fps15:new rP(1920,1080,25e5,15,"medium"),h1080fps30:new rP(1920,1080,5e6,30,"medium"),original:new rP(0,0,7e6,30,"medium")};function rx(e,t,i){var n,a;let{optionsWithoutProcessor:r,audioProcessor:s,videoProcessor:o}=rq(null!=e?e:{}),c=null==t?void 0:t.processor,l=null==i?void 0:i.processor,d=null!=r?r:{};return!0===d.audio&&(d.audio={}),!0===d.video&&(d.video={}),d.audio&&(rA(d.audio,t),null!=(n=d.audio).deviceId||(n.deviceId={ideal:"default"}),(s||c)&&(d.audio.processor=null!=s?s:c)),d.video&&(rA(d.video,i),null!=(a=d.video).deviceId||(a.deviceId={ideal:"default"}),(o||l)&&(d.video.processor=null!=o?o:l)),d}function rA(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function rN(e){var t,i;let n={};if(e.video)if("object"==typeof e.video){let i={},a=e.video;Object.keys(a).forEach(e=>{"resolution"===e?rA(i,a.resolution):i[e]=a[e]}),n.video=i,null!=(t=n.video).deviceId||(t.deviceId={ideal:"default"})}else n.video=!!e.video&&{deviceId:{ideal:"default"}};else n.video=!1;return e.audio?"object"==typeof e.audio?(n.audio=e.audio,null!=(i=n.audio).deviceId||(i.deviceId={ideal:"default"})):n.audio={deviceId:{ideal:"default"}}:n.audio=!1,n}function rL(e){return ah(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){let i=rU();if(i){let n=i.createAnalyser();n.fftSize=2048;let a=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield rz(t),n.getByteTimeDomainData(a);let r=a.some(e=>128!==e&&0!==e);return i.close(),!r}return!1}()})}function rU(){var e;let t="u">typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){let i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"u">typeof window&&(null==(e=window.document)?void 0:e.body)){let e=()=>ah(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null==(t=window.document.body)||t.removeEventListener("click",e)}});i.addEventListener("statechange",()=>{var t;"closed"===i.state&&(null==(t=window.document.body)||t.removeEventListener("click",e))}),window.document.body.addEventListener("click",e)}return i}}function rj(e){return e===rW.Source.Microphone?"audioinput":e===rW.Source.Camera?"videoinput":void 0}function rF(e){return e.split("/")[1].toLowerCase()}function rB(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?rB(e.track):{})}}function rq(e){let t,i,n=Object.assign({},e);return"object"==typeof n.audio&&n.audio.processor&&(t=n.audio.processor,n.audio=Object.assign(Object.assign({},n.audio),{processor:void 0})),"object"==typeof n.video&&n.video.processor&&(i=n.video.processor,n.video=Object.assign(Object.assign({},n.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:void 0===n?n:"function"!=typeof structuredClone?JSON.parse(JSON.stringify(n)):"object"==typeof n&&null!==n?structuredClone(Object.assign({},n)):structuredClone(n)}}function rV(e,t){return e.width*e.height<t.width*t.height}let rH=[];(P=ep||(ep={}))[P.LOW=0]="LOW",P[P.MEDIUM=1]="MEDIUM",P[P.HIGH=2]="HIGH";class rW extends ag.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){var i;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=rW.StreamState.Active,this.isInBackgroun
1d=!1,this._currentBitrate=0,this.log=ao,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=ac(null!=(i=n.loggerName)?i:ee.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=rW.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null==(e=this.loggerContextCb)?void 0:e.call(this)),rB(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===rW.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===rW.Kind.Video&&this.addAppVisibilityListener(),!e&&("audio"===t&&(rH.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&rH.splice(rH.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),rG(this.mediaStreamTrack,e);let i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?ed.AudioPlaybackStarted:ed.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?ed.AudioPlaybackFailed:ed.VideoPlaybackFailed,t):"AbortError"===t.name?ao.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):ao.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(ed.ElementAttached,e),e}detach(e){try{if(e){rK(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(ed.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{rK(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(ed.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=ac(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),rH.forEach(e=>{e.parentElement||(t=!1)}),t&&rH.push(e)}}handleAppVisibilityChanged(){return ah(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==rW.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){r4()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){r4()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function rG(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,(n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks()).includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),r1()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(r1()||r$())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function rK(e,t){if(t.srcObject instanceof MediaStream){let i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}(I=r=(R=rW||(rW={})).Kind||(R.Kind={})).Audio="audio",I.Video="video",I.Unknown="unknown",(_=s=R.Source||(R.Source={})).Camera="camera",_.Microphone="microphone",_.ScreenShare="screen_share",_.ScreenShareAudio="screen_share_audio",_.Unknown="unknown",(O=o=R.StreamState||(R.StreamState={}
1)).Active="active",O.Paused="paused",O.Unknown="unknown",R.kindToProto=function(e){switch(e){case r.Audio:return t$.AUDIO;case r.Video:return t$.VIDEO;default:return t$.DATA}},R.kindFromProto=function(e){switch(e){case t$.AUDIO:return r.Audio;case t$.VIDEO:return r.Video;default:return r.Unknown}},R.sourceToProto=function(e){switch(e){case s.Camera:return t0.CAMERA;case s.Microphone:return t0.MICROPHONE;case s.ScreenShare:return t0.SCREEN_SHARE;case s.ScreenShareAudio:return t0.SCREEN_SHARE_AUDIO;default:return t0.UNKNOWN}},R.sourceFromProto=function(e){switch(e){case t0.CAMERA:return s.Camera;case t0.MICROPHONE:return s.Microphone;case t0.SCREEN_SHARE:return s.ScreenShare;case t0.SCREEN_SHARE_AUDIO:return s.ScreenShareAudio;default:return s.Unknown}},R.streamStateFromProto=function(e){switch(e){case iQ.ACTIVE:return o.Active;case iQ.PAUSED:return o.Paused;default:return o.Unknown}};let rJ="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function rz(e){return new ro(t=>rw.setTimeout(t,e))}function rQ(){return"addTransceiver"in RTCPeerConnection.prototype}function rY(){return"addTrack"in RTCPeerConnection.prototype}function rX(e){return"av1"===e||"vp9"===e}function rZ(e){return!(!document||r2())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function r$(){var e;return(null==(e=rl())?void 0:e.name)==="Firefox"}function r0(){let e=rl();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function r1(){var e;return(null==(e=rl())?void 0:e.name)==="Safari"}function r2(){let e=rl();return(null==e?void 0:e.name)==="Safari"||(null==e?void 0:e.os)==="iOS"}function r3(){var e,t;return!!r4()&&(null!=(t=null==(e=navigator.userAgentData)?void 0:e.mobile)?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function r4(){return"u">typeof document}function r9(){return"ReactNative"==navigator.product}function r6(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function r5(e){return r6(e)?e.hostname.split(".")[0]:null}function r8(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function r7(){if(!r9())return;let e=r8();if(e)return e.platform}function se(){if(r4())return window.devicePixelRatio;if(r9()){let e=r8();if(e)return e.devicePixelRatio}return 1}function st(e,t){let i=e.split("."),n=t.split("."),a=Math.min(i.length,n.length);for(let e=0;e<a;++e){let t=parseInt(i[e],10),r=parseInt(n[e],10);if(t>r)return 1;if(t<r)return -1;if(e===a-1&&t===r)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function si(e){for(let t of e)t.target.handleResize(t)}function sn(e){for(let t of e)t.target.handleVisibilityChanged(t)}let sa=null,sr=()=>(sa||(sa=new ResizeObserver(si)),sa),ss=null,so=()=>(ss||(ss=new IntersectionObserver(sn,{root:null,rootMargin:"0px"})),ss);function sc(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=document.createElement("canvas");a.width=e,a.height=t;let r=a.getContext("2d");null==r||r.fillRect(0,0,a.width,a.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());let[s]=a.captureStream().getTracks();if(!s)throw Error("Could not get empty media stream video track");return s.enabled=i,s}function sl(){if(!a){let e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);let n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[a]=n.stream.getAudioTracks(),!a)throw Error("Could not get empty media stream audio track");a.enabled=!1}return a.clone()}class sd{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>ah(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null==(e=this.onFinally)||e.call(this)})}}function su(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;
1if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function sh(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function sp(e){switch(e.reason){case ea.LeaveRequest:return e.context;case ea.Cancelled:return t4.CLIENT_INITIATED;case ea.NotAllowed:return t4.USER_REJECTED;case ea.ServerUnreachable:return t4.JOIN_FAILURE;default:return t4.UNKNOWN_REASON}}function sm(e){return void 0!==e?Number(e):void 0}function sg(e){return void 0!==e?BigInt(e):void 0}function sf(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function sv(e){return!!e&&e.kind==rW.Kind.Audio}function sk(e){return!!e&&e.kind==rW.Kind.Video}function sb(e){return sf(e)&&sk(e)}function sy(e){return sf(e)&&sv(e)}function sT(e){return!!e&&!e.isLocal}function sC(e){return sT(e)&&sk(e)}function sS(e){return e.endsWith("/")?e:"".concat(e,"/")}function sE(e,t){return e.pathname="".concat(sS(e.pathname)).concat(t),e}function sw(e){if("string"==typeof e)return iZ.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return iZ.fromBinary(new Uint8Array(e));throw Error("could not decode websocket message: ".concat(typeof e))}let sP="lk_e2ee";function sR(){return void 0!==window.RTCRtpScriptTransform}(D=em||(em={})).SetKey="setKey",D.RatchetRequest="ratchetRequest",D.KeyRatcheted="keyRatcheted",(eg||(eg={})).KeyRatcheted="keyRatcheted",(M=ef||(ef={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",M.EncryptionError="encryptionError",(ev||(ev={})).Error="cryptorError",ag.EventEmitter,(x=ek||(ek={}))[x.InvalidKey=0]="InvalidKey",x[x.MissingKey=1]="MissingKey",x[x.InternalError=2]="InternalError";class sI extends ag.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,i;let{kind:n,data:a}=e.data;switch(n){case"error":if(ao.error(a.error.message),a.uuid){let e=this.decryptDataRequests.get(a.uuid);if(null==e?void 0:e.reject){e.reject(a.error);break}let t=this.encryptDataRequests.get(a.uuid);if(null==t?void 0:t.reject){t.reject(a.error);break}}this.emit(ef.EncryptionError,a.error,a.participantIdentity);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===(null==(t=this.room)?void 0:t.localParticipant.identity))this.emit(ef.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){let e=null==(i=this.room)?void 0:i.getParticipantByIdentity(a.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(ef.ParticipantEncryptionStatusChanged,a.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(em.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break;case"decryptDataResponse":let r=this.decryptDataRequests.get(a.uuid);(null==r?void 0:r.resolve)&&r.resolve(a);break;case"encryptDataResponse":let s=this.encryptDataRequests.get(a.uuid);(null==s?void 0:s.resolve)&&s.resolve(a)}},this.onWorkerError=e=>{ao.error("e2ee worker encountered an error:",{error:e.error}),this.emit(ef.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||sR()))throw new rf("tried to setup end-to-e
1nd encryption on an unsupported browser");if(ao.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:al.getLevel()}};this.worker&&(ao.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ao.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):ao.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(el.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(eo.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==is.NONE,t.identity)),e.on(eo.ConnectionStateChanged,t=>{t===e_.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==is.NONE,e.identity)})})}).on(eo.TrackUnsubscribed,(e,t,i)=>{var n;let a={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null==(n=this.worker)||n.postMessage(a)}).on(eo.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(eo.SignalConnected,()=>{if(!this.room)throw TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(ec.LocalSenderCreated,(e,t)=>ah(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(ec.LocalTrackPublished,e=>{if(!sk(e.track)||!r2())return;let t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:rF(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(em.SetKey,e=>this.postKey(e)).on(em.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return ah(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");let t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},n=new sd;return n.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,n),this.worker.postMessage(i),n.promise})}handleEncryptedData(e,t,i,n){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");let a=crypto.randomUUID(),r=new sd;return r.onFinally=()=>{this.decryptDataRequests.delete(a)},this.decryptDataRequests.set(a,r),this.worker.postMessage({kind:"decryptDataRequest",data:{uuid:a,payload:e,iv:t,participantIdentity:i,keyIndex:n}}),r.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}})}postKey(e){var t;let{key:i,participantIdentity:n,keyIndex:a}=e;if(!this.worker)throw Error("could not set key, worker is missing");let r={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null==(t=this.room)?void 0:t.localParticipant.identity),key:i,keyIndex:a}};this.worker.postMessage(r)}postEnable(e,t){if(this.worker)this.worker.postMessage({kind:"enable",data:{enabled:e,participantIdentity:t}});else throw ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null==(t=this.room)?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:e}})}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?rF(i.mimeType):void 0)}}setupE2EESender(e,t){if(!sf(e)||!t){t||ao.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,n){return ah(this,void 0,void 0,function*(){if(this.worker){if(sR()&&!r0())e.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:t,codec:n});else{if(sP in e&&n)return void this.worker.postMessage({kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}});let a=e.writableStream,r=e.readableStream;if(!a||!r){let t=e.createEncodedStreams();e.writableStream=t.writable,a=t.writable,e.readableStream=t.readable,r=t.readable}let s={kind:"decode",data:{readableStream:r,writableStream:a,trackId:t,codec:n,participantIdentity:i,isReuse:sP in e}};this.worker.postMessage(s,[r,a])}e[sP]=!0}})}handleSender(e,t,i){var n;if(!(sP in e)&&this.worker){if(!(null==(n=this.room)?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(sR()&&!r0()){ao.info("initialize script transform");let n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{ao.info("initialize encoded streams");let n=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};
1this.worker.postMessage(a,[n.readable,n.writable])}e[sP]=!0}}}class s_{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new s_),this._instance}addFailedConnectionAttempt(e){var t;let i=r5(new URL(e));if(!i)return;let n=null!=(t=this.failedConnectionAttempts.get(i))?t:0;this.failedConnectionAttempts.set(i,n+1),this.backOffPromises.set(i,rz(Math.min(500*Math.pow(2,n),15e3)))}getBackOffPromise(e){let t=new URL(e),i=t&&r5(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),i=t&&r5(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}s_._instance=null;let sO="default";class sD{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new sD),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return ah(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;if((null==(n=sD.userMediaPromiseMap)?void 0:n.size)>0){ao.debug("awaiting getUserMedia promise");try{e?yield sD.userMediaPromiseMap.get(e):yield Promise.all(sD.userMediaPromiseMap.values())}catch(e){ao.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(i&&!(r1()&&t.hasDeviceInUse(e))&&(0===a.filter(t=>t.kind===e).length||a.some(t=>{let i=""===t.label,n=!e||t.kind===e;return i&&n}))){let t=yield navigator.mediaDevices.getUserMedia({video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}});a=yield navigator.mediaDevices.enumerateDevices(),t.getTracks().forEach(e=>{e.stop()})}return t._previousDevices=a,e&&(a=a.filter(t=>t.kind===e)),a}()})}normalizeDeviceId(e,t,i){return ah(this,void 0,void 0,function*(){if(t!==sO)return t;let n=yield this.getDevices(e),a=n.find(e=>e.deviceId===sO);if(!a)return void ao.warn("could not reliably determine default device");let r=n.find(e=>e.deviceId!==sO&&e.groupId===(null!=i?i:a.groupId));return r?null==r?void 0:r.deviceId:void ao.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?sD.userMediaPromiseMap.has(e):sD.userMediaPromiseMap.size>0}}sD.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],sD.userMediaPromiseMap=new Map,(A=eb||(eb={}))[A.WAITING=0]="WAITING",A[A.RUNNING=1]="RUNNING",A[A.COMPLETED=2]="COMPLETED";class sM{constructor(){this.pendingTasks=new Map,this.taskMutex=new eF,this.nextTaskIndex=0}run(e){return ah(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:eb.WAITING};this.pendingTasks.set(t.id,t);let i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=eb.RUNNING,yield e()}finally{t.status=eb.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return ah(this,void 0,void 0,function*(){return this.run(()=>ah(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class sx{get readyState(){return this.ws.readyState}constructor(e){var t,i;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null==(t=n.signal)?void 0:t.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const a=new WebSocket(e,null!=(i=n.protocols)?i:[]);a.binaryType="arraybuffer",this.ws=a;const r=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return a.close(e,t)};this.opened=new ro((e,t)=>{let i=()=>{t(rg.websocket("Encountered websocket error during connection establishment"))};a.onopen=()=>{e({readable:new ReadableStream({start(e){a.onmessage=t=>{let{data:i}=t;return e.enqueue(i)},a.onerror=t=>e.error(t)},cancel:r}),writable:new WritableStream({write(e){a.send(e)},abort(){a.close()},close:r}),protocol:a.protocol,extensions:a.extensions}),a.removeEventListener("error",i)},a.addEventListener("error",i)}),this.closed=new ro((e,t)=>{let i=()=>ah(this,void 0,void 0,function*(){let i=new ro(e=>{a.readyState===WebSocket.CLOSED||a.addEventListener("close",t=>{e(t)},{once:!0})}),n=yield ro.race([rz(250),i]);n?e(n):t(rg.websocket("Encountered unspecified websocket error without a timely close event"))});
1a.onclose=t=>{let{code:n,reason:r}=t;e({closeCode:n,reason:r}),a.removeEventListener("error",i)},a.addEventListener("error",i)}),n.signal&&(n.signal.onabort=()=>a.close()),this.close=r}}let sA=["syncState","trickle","offer","answer","simulate","leave"];(N=ey||(ey={}))[N.CONNECTING=0]="CONNECTING",N[N.CONNECTED=1]="CONNECTED",N[N.RECONNECTING=2]="RECONNECTING",N[N.DISCONNECTING=3]="DISCONNECTING",N[N.DISCONNECTED=4]="DISCONNECTED";class sN{get currentState(){return this.state}get isDisconnected(){return this.state===ey.DISCONNECTING||this.state===ey.DISCONNECTED}get isEstablishingConnection(){return this.state===ey.CONNECTING||this.state===ey.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.rtt=0,this.state=ey.DISCONNECTED,this.log=ao,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=ac(null!=(e=i.loggerName)?e:ee.Signal),this.loggerContextCb=i.loggerContextCb,this.useJSON=t,this.requestQueue=new sM,this.queuedRequests=[],this.closingLock=new eF,this.connectionLock=new eF,this.state=ey.DISCONNECTED}get logContext(){var e,t;return null!=(t=null==(e=this.loggerContextCb)?void 0:e.call(this))?t:{}}join(e,t,i,n){return ah(this,arguments,void 0,function(e,t,i,n){var a=this;let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){return a.state=ey.CONNECTING,a.options=i,yield a.connect(e,t,i,n,r)}()})}reconnect(e,t,i,n){return ah(this,void 0,void 0,function*(){return this.options?(this.state=ey.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}),void 0,this.useV0SignalPath)):void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)})}connect(e,t,i,n){return ah(this,arguments,void 0,function(e,t,i,n){var a=this;let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var s,o,c,l,d,u,h,p;let m,g,f,v,k,b=yield a.connectionLock.lock();a.connectOptions=i,a.useV0SignalPath=r;let y=(k=new iM({sdk:ix.JS,protocol:16,version:"2.17.1"}),r9()&&(k.os=null!=(s=r7())?s:""),k),T=(function(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=function(e,t){let i=new URL(e.startsWith("http")?e.replace(/^(http)/,"ws"):e);return t.forEach((e,t)=>{i.searchParams.set(t,e)}),sE(i,"rtc")}(e,t);return i?n:sE(n,"v1")})(e,r?(o=t,c=y,l=i,(m=new URLSearchParams).set("access_token",o),l.reconnect&&(m.set("reconnect","1"),l.sid&&m.set("sid",l.sid)),m.set("auto_subscribe",l.autoSubscribe?"1":"0"),m.set("sdk",r9()?"reactnative":"js"),m.set("version",c.version),m.set("protocol",c.protocol.toString()),c.deviceModel&&m.set("device_model",c.deviceModel),c.os&&m.set("os",c.os),c.osVersion&&m.set("os_version",c.osVersion),c.browser&&m.set("browser",c.browser),c.browserVersion&&m.set("browser_version",c.browserVersion),l.adaptiveStream&&m.set("adaptive_stream","1"),l.reconnectReason&&m.set("reconnect_reason",l.reconnectReason.toString()),(null==(d=navigator.connection)?void 0:d.type)&&m.set("network",navigator.connection.type),m):(u=t,h=y,p=i,(g=new URLSearchParams).set("access_token",u),f=new nH({clientInfo:h,connectionSettings:new nV({autoSubscribe:!!p.autoSubscribe,adaptiveStream:!!p.adaptiveStream}),reconnect:!!p.reconnect,participantSid:p.sid?p.sid:void 0}),p.reconnectReason&&(f.reconnectReason=p.reconnectReason),v=new nW({joinRequest:f.toBinary()}),g.set("join_request",btoa(new TextDecoder("utf-8").decode(v.toBinary()))),g),r).toString(),C=sE(new URL(sh(T)),"validate").toString();return new Promise((e,t)=>ah(a,void 0,void 0,function*(){var a,r;try{let s=!1,o=e=>ah(this,void 0,void 0,function*(){if(s)return;s=!0;let i=e instanceof Event?e.currentTarget:e,n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;let i=e.reason;switch(typeof i){case"string":return i;case"object":return i instanceof Error?i.message:t;default:return"toString"in i?i.toString():t}}(i,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),c(),t(rg.cancelled(n))});null==n||n.addEventListener("abort",o);let c=()=>{clearTimeout(l),null==n||n.removeEventListener("abort",o)},l=setTimeout(()=>{o(rg.timeout("room connection has timed out (signal)"))},i.websocketTimeout),d=(e,t)=>{this.handleSignalConnected(e,l,t)},u=new URL(T);u.searchParams.has("access_token")&&u.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(u),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new sx(T);try{this.ws.closed.then(e=>{var i;this.isEstablishingConnection&&t(rg.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),1e3!==e.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state})),this.state===ey.CONNECTED&&this.handleOnClose(null!=(i=e.reason)?i:"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(rg.internal("Websocket error during a (re)connection attempt: ".concat(e)))});
1let n=yield this.ws.opened.catch(e=>ah(this,void 0,void 0,function*(){if(this.state!==ey.CONNECTED){this.state=ey.DISCONNECTED,clearTimeout(l);let i=yield this.handleConnectionError(e,C);t(i);return}this.handleWSError(e),t(e)}));if(clearTimeout(l),!n)return;let s=n.readable.getReader();this.streamWriter=n.writable.getWriter();let o=yield s.read();if(s.releaseLock(),!o.value)throw rg.internal("no message received as first message");let c=sw(o.value),u=this.validateFirstMessage(c,null!=(a=i.reconnect)&&a);if(!u.isValid)return void t(u.error);(null==(r=c.message)?void 0:r.case)==="join"&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));let h=u.shouldProcessFirstMessage?c:void 0;d(n,h),e(u.response)}catch(e){t(e)}finally{c()}}finally{b()}}))}()})}startReadingLoop(e,t){return ah(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield rz(this.signalLatency));let{done:t,value:i}=yield e.read();if(t)break;let n=sw(i);this.handleSignalResponse(n)}})}close(){return ah(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([ey.DISCONNECTING||ey.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");let n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=ey.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});let t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,rz(250)])}}catch(t){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=ey.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:sU(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:sU(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new i5({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new i8({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return ah(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){let a=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new nm({requestId:a,metadata:e,name:t,attributes:n})}),a}()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new np({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new nR({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:e4.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new nA({timestamp:e4.parse(Date.now()),rtt:e4.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new nl({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new nu({reason:t4.CLIENT_INITIATED,action:nh.DISCONNECT})})}sendRequest(e){return ah(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){let n;if(!i&&(n=sA.indexOf(e.case)>=0,ao.trace("request allowed to bypass queue:",{canPass:n,req:e}),!n)&&t.state===ey.RECONNECTING)return void t.queuedRequests.push(()=>ah(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield rz(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);let a=new iX({message:e});try{t.useJSON?yield t.streamWriter.write(a.toJsonString()):yield t.streamWriter.write(a.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){var t,i;let n=e.message;if(void 0==n)return void this.log.debug("received unsupported message",this.logContext);let a=!1;if("answer"===n.case){let e=sL(n.value);this.onAnswer&&this.onAnswer(e,n.value.id,n.value.midToTrackId)}else if("offer"===n.case){let e=sL(n.value);this.onOffer&&this.onOffer(e,n.value.id,n.value.midToTrackId)}else if("trickle"===n.case){let e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!=(t=n.value.participants)?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!=(i=n.value.speakers)?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),a=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):"mediaSectionsRequirement"===n.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement
1(n.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));a||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return ah(this,void 0,void 0,function*(){if(this.state===ey.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){(this.clearPingTimeout(),this.pingTimeoutDuration)?this.pingTimeout=rw.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&rw.clearTimeout(this.pingTimeout)}startPingInterval(){(this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration)?(this.log.debug("start ping interval",this.logContext),this.pingInterval=rw.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&rw.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=ey.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,n,a,r,s;if((null==(i=e.message)?void 0:i.case)==="join")return{isValid:!0,response:e.message.value};if(this.state===ey.RECONNECTING&&(null==(n=e.message)?void 0:n.case)!=="leave")if((null==(a=e.message)?void 0:a.case)==="reconnect")return{isValid:!0,response:e.message.value};else return this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0};return this.isEstablishingConnection&&(null==(r=e.message)?void 0:r.case)==="leave"?{isValid:!1,error:rg.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:rg.internal("Unexpected first message")}:{isValid:!1,error:rg.internal("did not receive join response, got ".concat(null==(s=e.message)?void 0:s.case," instead"))}}handleConnectionError(e,t){return ah(this,void 0,void 0,function*(){try{let i=yield fetch(t);switch(i.status){case 404:return rg.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:let n=yield i.text();return rg.notAllowed(n,i.status)}if(e instanceof rg)return e;return rg.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(e){return e instanceof rg?e:rg.serverUnreachable(e instanceof Error?e.message:"server was not reachable")}})}}function sL(e){let t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function sU(e,t){return new nn({sdp:e.sdp,type:e.type,id:t})}class sj{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;)if(this.buffer[0].sequence<=e)this.pop();else break}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class sF{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();let n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){let t=this._map.get(e);if(t)return t.expiresAt<Date.now()?void this._map.delete(e):t.value}has(e){let t=this._map.get(e);
1return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){for(let[t,i]of(this.cleanup(),this._map.entries()))i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],i=this.asValueMap();for(let[n,a]of i.entries())t.push(e(a,n,i));return t}asValueMap(){let e=new Map;for(let[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var sB={},sq={},sV={exports:{}};function sH(){if(eT)return sV.exports;eT=1;var e=sV.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=(null!=e.raddr?" raddr %s rport %d":"%v%v")+(null!=e.tcptype?" tcptype %s":"%v"),null!=e.generation&&(t+=" generation %d"),t+=(null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","max
1MessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+((null!=e.id?"id=%s %s":"%v%s")+(null!=e.mediaClockValue?"=%s":"")+(null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":""))}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),sV.exports}var sW=function(){if(ew)return sB;ew=1;var e=function(){var e,t,i,n,a,r;return eC?sq:(eC=1,e=function(e){return String(Number(e))===e?Number(e):e},t=function(t,i,n,a){if(a&&!n)i[a]=e(t[1]);else for(var r=0;r<n.length;r+=1)null!=t[r+1]&&(i[n[r]]=e(t[r+1]))},i=function(e,i,n){var a=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:a&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:a?i[e.name]:i;t(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=sH(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/),sq.parse=function(e){var t={},r=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),s=r[r.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(a))return i(c,s,a)}}),t.media=r,t},r=function(t,i){var n=i.split(/=(.+)/,2);return 2===n.length?t[n[0]]=e(n[1]):1===n.length&&i.length>1&&(t[n[0]]=void 0),t},sq.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},sq.parseFmtpConfig=sq.parseParams,sq.parsePayloads=function(e){return e.toString().split(" ").map(Number)},sq.parseRemoteCandidates=function(t){for(var i=[],n=t.split(" ").map(e),a=0;a<n.length;a+=3)i.push({component:n[a],ip:n[a+1],port:n[a+2]});return i},sq.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})})},sq.parseSimulcastStreamList=function(t){return t.split(";").map(function(t){return t.split(",").map(function(t){var i,n=!1;return"~"!==t[0]?i=e(t):(i=e(t.substring(1,t.length)),n=!0),{scid:i,paused:n}})})},sq)}(),t=function(){if(eE)return eS;eE=1;var e=sH(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,a=n.length;return e.replace(t,function(e){if(i>=a)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var a=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var s=t.names[r];t.name?a.push(n[t.name][s]):a.push(n[t.names[r]])}else a.push(n[t.name]);return i.apply(null,a)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return eS=function(t,i){i=i||{}
1,null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var s=i.outerOrder||a,o=i.innerOrder||r,c=[];return s.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})}),t.media.forEach(function(t){c.push(n("m",e.m[0],t)),o.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){c.push(n(i,e,t))})})})}),c.join("\r\n")+"\r\n"}}();return sB.grammar=sH(),sB.write=t,sB.parse=e.parse,sB.parseParams=e.parseParams,sB.parseFmtpConfig=e.parseFmtpConfig,sB.parsePayloads=e.parsePayloads,sB.parseRemoteCandidates=e.parseRemoteCandidates,sB.parseImageAttributes=e.parseImageAttributes,sB.parseSimulcastStreamList=e.parseSimulcastStreamList,sB}();function sG(e,t,i){void 0===t&&(t=50),void 0===i&&(i={});var n,a,r,s=null!=(n=i.isImmediate)&&n,o=null!=(a=i.callback)&&a,c=i.maxWait,l=Date.now(),d=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise(function(a,u){var h=s&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,l=Date.now(),!s){var t=e.apply(n,i);o&&o(t),d.forEach(function(e){return(0,e.resolve)(t)}),d=[]}},function(){if(void 0!==c){var e=Date.now()-l;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return o&&o(p),a(p)}d.push({resolve:a,reject:u})})};return u.cancel=function(e){void 0!==r&&clearTimeout(r),d.forEach(function(t){return(0,t.reject)(e)}),d=[]},u}let sK="negotiationStarted",sJ="negotiationComplete",sz="rtpVideoPayloadTypes";class sQ extends ag.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.log=ao,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=sG(e=>ah(this,void 0,void 0,function*(){this.emit(sK);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=ac(null!=(t=i.loggerName)?t:ee.PCTransport),this.loggerOptions=i,this.config=e,this._pc=this.createPC(),this.offerLock=new eF}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null==(t=this.onIceCandidate)||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null==(t=this.onIceCandidateError)||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null==(t=this.onIceConnectionStateChange)||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null==(t=this.onSignalingStatechange)||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null==(t=this.onConnectionStateChange)||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null==(t=this.onDataChannel)||t.call(this,e)},e.ontrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null==(t=(e=this.loggerOptions).loggerContextCb)?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return ah(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return ah(this,void 0,void 0,function*(){var i,n,a;let r;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;if("offer"===e.type){let t,i,r,s,{stereoMids:o,nackMids:c}=(n=e,t=[],i=[],r=sW.parse(null!=(a=n.sdp)?a:""),s=0,r.media.forEac
1h(e=>{var n;let a=sZ(e.mid);"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),(null==(n=e.rtcpFb)?void 0:n.some(e=>e.payload===s&&"nack"===e.type))&&i.push(a),e.fmtp.some(e=>e.payload===s&&(e.config.includes("sprop-stereo=1")&&t.push(a),!0)))}),{stereoMids:t,nackMids:i});this.remoteStereoMids=o,this.remoteNackMids=c}else if("answer"===e.type){let t=sW.parse(null!=(i=e.sdp)?i:"");t.media.forEach(e=>{let t=sZ(e.mid);"audio"===e.type&&this.trackBitrates.some(i=>{if(!i.transceiver||t!=i.transceiver.mid)return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===i.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;let a=!1;for(let t of e.fmtp)if(t.payload===n){t.config=t.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),i.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*i.maxbr)),a=!0;break}return!a&&i.maxbr>0&&e.fmtp.push({payload:n,config:"maxaveragebitrate=".concat(1e3*i.maxbr)}),!0})}),r=sW.write(t)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit
1(sJ),e.sdp&&sW.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(sz,e.rtp)})),!0})}createAndSendOffer(e){return ah(this,void 0,void 0,function*(){var t;let i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){let t=this._pc.remoteDescription;if((null==e?void 0:e.iceRestart)&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0;return}}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);let i=this.latestOfferId+1;this.latestOfferId=i;let n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));let a=sW.parse(null!=(t=n.sdp)?t:"");if(a.media.forEach(e=>{sX(e),"audio"===e.type?sY(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i||(rX(t.codec)&&!r1()&&this.ensureVideoDDExtensionForSVC(e,a),!rX(t.codec)))return!0;let n=Math.round(.7*t.maxbr);for(let t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,sW.write(a)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return ah(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),i=sW.parse(null!=(e=t.sdp)?e:"");return i.media.forEach(e=>{sX(e),"audio"===e.type&&sY(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,sW.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new rb("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new rb("PC closed, cannot configure");return null==(t=this._pc)?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null==(e=this._pc)?void 0:e.removeTrack)}removeTrack(e){var t;return null==(t=this._pc)?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.connectionState)?t:"closed"}getICEConnectionState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.iceConnectionState)?t:"closed"}getSignallingState(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.signalingState)?t:"closed"}getTransceivers(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.getTransceivers())?t:[]}getSenders(){var e,t;return null!=(t=null==(e=this._pc)?void 0:e.getSenders())?t:[]}getLocalDescription(){var e;return null==(e=this._pc)?void 0:e.localDescription}getRemoteDescription(){var e;return null==(e=this.pc)?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return ah(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;let a=null==(e=i.get(t))?void 0:e.remoteCandidateId;if(void 0!==a)return n.get(a)})}setMungedSDP(e,t,i){return ah(this,void 0,void 0,function*(){if(t){let n=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(a){let t="unknown error";a instanceof Error?t=a.message:"string"==typeof a&&(t=a);let n={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(n.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:n})),new ry(t)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null==(i=e.ext)?void 0:i.some(e=>e.uri===rJ))){if(0===this.ddExtID){let e=0;
1t.media.forEach(t=>{var i;"video"===t.type&&(null==(i=t.ext)||i.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null==(n=e.ext)||n.push({value:this.ddExtID,uri:rJ})}}}function sY(e,t,i){let n=sZ(e.mid),a=0;e.rtp.some(e=>"opus"===e.codec&&(a=e.payload,!0)),a>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(n)&&!e.rtcpFb.some(e=>e.payload===a&&"nack"===e.type)&&e.rtcpFb.push({payload:a,type:"nack"}),(t.includes(n)||1===t.length&&"all"===t[0])&&e.fmtp.some(e=>e.payload===a&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function sX(e){if(e.connection){let t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function sZ(e){return"number"==typeof e?e.toFixed(0):e}let s$={audioPreset:eh.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:rM.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!0,preConnectBuffer:!1},s0={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},s1={deviceId:{ideal:"default"},resolution:rO.h720.resolution},s2={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new au,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},s3={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};(L=eP||(eP={}))[L.NEW=0]="NEW",L[L.CONNECTING=1]="CONNECTING",L[L.CONNECTED=2]="CONNECTED",L[L.FAILED=3]="FAILED",L[L.CLOSING=4]="CLOSING",L[L.CLOSED=5]="CLOSED";class s4{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var n;this.peerConnectionTimeout=s3.peerConnectionTimeout,this.log=ao,this.updateState=()=>{var e,t;let i=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>"connected"===e)?this.state=eP.CONNECTED:n.some(e=>"failed"===e)?this.state=eP.FAILED:n.some(e=>"connecting"===e)?this.state=eP.CONNECTING:n.every(e=>"closed"===e)?this.state=eP.CLOSED:n.some(e=>"closed"===e)?this.state=eP.CLOSING:n.every(e=>"new"===e)&&(this.state=eP.NEW),i!==this.state&&(this.log.debug("pc state change: from ".concat(eP[i]," to ").concat(eP[this.state]),this.logContext),null==(e=this.onStateChange)||e.call(this,this.state,this.publisher.getConnectionState(),null==(t=this.subscriber)?void 0:t.getConnectionState()))},this.log=ac(null!=(n=i.loggerName)?n:ee.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new sQ(e,i),this._mode=t,"publisher-only"!==t&&(this.subscriber=new sQ(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null==(t=this.onIceCandidate)||t.call(this,e,iz.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null==(t=this.onDataChannel)||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null==(t=this.onIceCandidate)||t.call(this,e,iz.PUBLISHER)},this.publisher.onTrack=e=>{var t;null==(t=this.onTrack)||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null==(i=this.onPublisherOffer)||i.call(this,e,t)},this.state=eP.NEW,this.connectionLock=new eF,this.remoteOfferLock=new eF}get logContext(){var e,t;return Object.assign({},null==(t=(e=this.loggerOptions).loggerContextCb)?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return ah(this,void 0,void 0,function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null==(e=this.subscriber)?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return ah(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return ah(this,void 0,void 0,function*(){var i;t===iz.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null==(i=this.subscriber)?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return ah(this,void 0,void 0,function*(){var i,n,a;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null==(i=this.subscriber)?void 0:i.getSignallingState().toString()}));let r=yield this.remoteOfferLock.lock();try{if(!(yield null==(n=this.subscriber)?void 0:n.setRemoteDescription(e,t)))return;return yield null==(a=this.subscriber)?void 0:a.createAndSetAnswer()}finally{r()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),null==(i=this.subscriber)||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return ah(this,void 0,void 0,function*(){var i;let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null==(i=this.requiredTransports)?void 0:i.map(i=>
1this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return ah(this,void 0,void 0,function*(){return new ro((t,i)=>ah(this,void 0,void 0,function*(){let n=setTimeout(()=>{i(new ry("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(n),i(new ry("negotiation aborted"))}),this.publisher.once(sK,()=>{e.signal.aborted||this.publisher.once(sJ,()=>{clearTimeout(n),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(n),e instanceof Error?i(e):i(Error(String(e)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){let t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e);return null==t?void 0:t.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===iz.PUBLISHER||e===iz.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return ah(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,a)=>ah(i,void 0,void 0,function*(){let i=()=>{this.log.warn("abort transport connection",this.logContext),rw.clearTimeout(r),a(rg.cancelled("room connection has been cancelled"))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);let r=rw.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),a(rg.internal("could not establish pc connection"))},n);for(;this.state!==eP.CONNECTED;)if(yield rz(50),null==t?void 0:t.signal.aborted)return void a(rg.cancelled("room connection has been cancelled"));rw.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class s9{static fetchRegionSettings(e,t,i){return ah(this,void 0,void 0,function*(){let n=yield s9.fetchLock.lock();try{var a;let n=yield fetch("".concat((a=e,"".concat(a.protocol.replace("ws","http"),"//").concat(a.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(n.ok){let e=function(e){var t;let i=e.get("Cache-Control");if(i){let e=null==(t=i.match(/(?:^|[,\s])max-age=(\d+)/))?void 0:t[1];if(e)return parseInt(e,10)}}(n.headers);return{regionSettings:yield n.json(),updatedAtInMs:Date.now(),maxAgeInMs:e?1e3*e:5e3}}if(401===n.status)throw rg.notAllowed("Could not fetch region settings: ".concat(n.statusText),n.status);throw rg.internal("Could not fetch region settings: ".concat(n.statusText))}catch(e){if(e instanceof rg)throw e;if(null==i?void 0:i.aborted)throw rg.cancelled("Region fetching was aborted");throw rg.serverUnreachable("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e))}finally{n()}})}static scheduleRefetch(e,t,i){return ah(this,void 0,void 0,function*(){clearTimeout(s9.settingsTimeouts.get(e.hostname)),s9.settingsTimeouts.set(e.hostname,setTimeout(()=>ah(this,void 0,void 0,function*(){try{let i=yield s9.fetchRegionSettings(e,t);s9.updateCachedRegionSettings(e,t,i)}catch(n){if(n instanceof rg&&n.reason===ea.NotAllowed)return void ao.debug("token is not valid, cancelling auto region refresh");ao.debug("auto refetching of region settings failed",{error:n}),s9.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){s9.cache.set(e.hostname,i),s9.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){let t=s9.settingsTimeouts.get(e);t&&(clearTimeout(t),s9.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=s9.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{let t=s9.connectionTrackers.get(e);t&&0===t.connectionCount&&(ao.debug("stopping region refetch after disconnect delay",{hostname:e}),s9.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){let t=s9.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){let e=this.serverUrl.hostname,t=s9.connectionTrackers.get(e);t||(t={connectionCount:0},s9.connectionTrackers.set(e,t)),t.connectionCount++,s9.cancelCleanup(e)}notifyDisconnected(){let e=this.serverUrl.hostname,t=s9.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&s9.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return r6(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return ah(this,void 0,void 0,function*(){return s9.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return ah(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=s9.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),s9.updateCachedRegionSettings(this.serverUrl,this.token,t));
1let i=t.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(!(i.length>0))return null;{let e=i[0];return this.attemptedRegions.push(e),ao.debug("next region: ".concat(e.region)),e.url}})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){s9.updateCachedRegionSettings(this.serverUrl,this.token,e)}}s9.cache=new Map,s9.settingsTimeouts=new Map,s9.connectionTrackers=new Map,s9.fetchLock=new eF;class s6 extends Error{constructor(e,t,i){super(t),this.code=e,this.message=s8(t,s6.MAX_MESSAGE_BYTES),this.data=i?s8(i,s6.MAX_DATA_BYTES):void 0}static fromProto(e){return new s6(e.code,e.message,e.data)}toProto(){return new iI({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new s6(s6.ErrorCode[e],s6.ErrorMessage[e],t)}}function s5(e){return new TextEncoder().encode(e).length}function s8(e,t){if(s5(e)<=t)return e;let i=0,n=e.length,a=new TextEncoder;for(;i<n;){let r=Math.floor((i+n+1)/2);a.encode(e.slice(0,r)).length<=t?i=r:n=r-1}return e.slice(0,i)}function s7(e,t){let i,n;return t?("bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp)?0:(i-n)*8e3/(e.timestamp-t.timestamp):0}s6.MAX_MESSAGE_BYTES=256,s6.MAX_DATA_BYTES=15360,s6.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},s6.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};let oe="u">typeof MediaRecorder;class ot{constructor(){throw Error("MediaRecorder is not available in this environment")}}let oi=oe?MediaRecorder:ot;class on extends oi{constructor(e,t){let i,n;if(!oe)throw Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);const a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",r),null==n||n.close(),n=void 0},r=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",r),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>ah(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer)i=new Uint8Array((yield t.data.arrayBuffer()));else if(t.data.byteArray)i=t.data.byteArray;else throw Error("no data available!");void 0!==n&&e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",r)}}class oa extends rW{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments.length>4?arguments[4]:void 0;super(e,t,a),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=sG(()=>ah(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>ah(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit
1(ed.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new eF,this.pauseUpstreamLock=new eF,this.trackChangeLock=new eF,this.trackChangeLock.lock().then(t=>ah(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==rW.Kind.Video)return;let{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!=(t=null==(e=this.processor)?void 0:e.processedTrack)?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return ah(this,void 0,void 0,function*(){var i;let n;if(e!==this._mediaStreamTrack||t){if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{rK(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(rG(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&(null==(i=this.sender.transport)?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{rG(null!=n?n:e,t)}))}})}waitForDimensions(){return ah(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===rW.Kind.Audio)throw Error("cannot get dimensions for audio tracks");(null==(i=rl())?void 0:i.os)==="iOS"&&(yield rz(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield rz(50)}throw new rv("unable to get track dimensions after timeout")}()})}setDeviceId(e){return ah(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===su(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),su(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return ah(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){if(e.source===rW.Source.ScreenShare)return;let{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),a=e.kind===rW.Kind.Audio?"audioinput":"videoinput";return t?sD.getInstance().normalizeDeviceId(a,i,n):i}()})}mute(){return ah(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return ah(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return ah(this,void 0,void 0,function*(){let i=yield this.trackChangeLock.lock();try{let i,n;if(!this.sender)throw new rv("unable to replace an unpublished track");return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return ah(this,void 0,void 0,function*(){this.manuallyStopped=!1;let t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);let{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var a=0,n=Object.getOwnPropertySymbols(e);a<n.length;a++)0>t.indexOf(n[a])&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(i[n[a]]=e[n[a]]);return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let a={audio:!1,video:!1};this.kind===rW.Kind.Video?a.video=!t&&!i||{deviceId:t,facingMode:i}:a.audio=!t||Object.assign({deviceId:t}
1,n),this.attachedElements.forEach(e=>{rK(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();let r=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===rW.Kind.Video&&(yield r.applyConstraints(n)),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=e,this.emit(ed.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),(this.isMuted!==e||this._mediaStreamTrack.enabled===e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ed.Muted:ed.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return ah(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),r3()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null==(e=this.processor)||e.destroy(),this.processor=void 0}pauseUpstream(){return ah(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(ed.UpstreamPaused,this);let t=rl();if((null==t?void 0:t.name)==="Safari"&&0>st(t.version,"12.0"))throw new rf("pauseUpstream is not supported on Safari < 12.");(null==(e=this.sender.transport)?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return ah(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(ed.UpstreamResumed,this),(null==(e=this.sender.transport)?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return ah(this,void 0,void 0,function*(){var e;if(null==(e=this.sender)?void 0:e.getStats)return yield this.sender.getStats()})}setProcessor(e){return ah(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;let a=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);let a=document.createElement(t.kind),r={kind:t.kind,track:t._mediaStreamTrack,element:a,audioContext:t.audioContext};if(yield e.init(r),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(rG(t._mediaStreamTrack,a),a.muted=!0,a.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{a.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=a,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&i&&(rK(t._mediaStreamTrack,e),rG(t.processor.processedTrack,e));yield null==(n=t.sender)?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(ed.TrackProcessorUpdate,t.processor)}finally{a()}}()})}getProcessor(){return this.processor}stopProcessor(){return ah(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){let i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}}()})}internalStopProcessor(){return ah(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null==(i=e.processor.processedTrack)||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null==(n=e.processorElement)||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(ed.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(!oe)return void this.log.warn("MediaRecorder is not available, cannot start prec
1onnect buffer",this.logContext);if(this.localTrackRecorder)return void this.log.warn("preconnect buffer already started");{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new on(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},1e4)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null==(e=this.localTrackRecorder)?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null==(e=this.localTrackRecorder)?void 0:e.mimeType}}class or extends oa{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0;super(e,rW.Kind.Audio,t,i,a),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>ah(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=s7(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ed.AudioTrackFeatureUpdate,this,t5.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ed.AudioTrackFeatureUpdate,this,t5.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return ah(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source===rW.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return ah(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;let t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==su(this._constraints.deviceId);return this.source===rW.Source.Microphone&&(this.stopOnMute||"ended"===this._mediaStreamTrack.readyState||t)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return ah(this,void 0,void 0,function*(){let t;if(e){let i=rN({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e){let t=Object.create(null,{restart:{get:()=>super.restart}});return ah(this,void 0,void 0,function*(){let i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){!r4()||this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}setProcessor(e){return ah(this,void 0,void 0,function*(){var t;let i=yield this.trackChangeLock.lock();try{if(!r9()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());let i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null==(t=this.sender)?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit
1(ed.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return ah(this,void 0,void 0,function*(){var e;let t;if(null==(e=this.sender)?void 0:e.getStats)return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return ah(this,void 0,void 0,function*(){let e=yield rL(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(ed.AudioSilenceDetected)),e})}}let os=Object.values(rO),oo=Object.values(rD),oc=Object.values(rM),ol=[rO.h180,rO.h360],od=[rD.h180,rD.h360],ou=["q","h","f"];function oh(e,t,i,n){var a,r,s;let o,c=null==n?void 0:n.videoEncoding;e&&(c=null==n?void 0:n.screenShareEncoding);let l=null==n?void 0:n.simulcast,d=null==n?void 0:n.scalabilityMode,u=null==n?void 0:n.videoCodec;if(!c&&!l&&!d||!t||!i)return[{}];c||(c=function(e,t,i,n){let a=function(e,t,i){if(e)return oc;let n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?os:oo}(e,t,i),{encoding:r}=a[0],s=Math.max(t,i);for(let e=0;e<a.length;e+=1){let t=a[e];if(r=t.encoding,t.width>=s)break}if(n)switch(n){case"av1":case"h265":(r=Object.assign({},r)).maxBitrate=.7*r.maxBitrate;break;case"vp9":(r=Object.assign({},r)).maxBitrate=.85*r.maxBitrate}return r}(e,t,i,u),ao.debug("using video encoding",c));let h=c.maxFramerate,p=new rP(t,i,c.maxBitrate,c.maxFramerate,c.priority);if(d&&rX(u)){let e=new of(d),t=[];if(e.spatial>3)throw Error("unsupported scalabilityMode: ".concat(d));let i=rl();if(r2()||r9()||(null==i?void 0:i.name)==="Chrome"&&0>st(null==i?void 0:i.version,"113")){let n="h"==e.suffix?2:3,a=((s=i)||(s=rl()),(null==s?void 0:s.name)==="Safari"&&st(s.version,"18.3")>0||(null==s?void 0:s.os)==="iOS"&&!!(null==s?void 0:s.osVersion)&&st(s.osVersion,"18.3")>0);for(let i=0;i<e.spatial;i+=1)t.push({rid:ou[2-i],maxBitrate:c.maxBitrate/Math.pow(n,i),maxFramerate:p.encoding.maxFramerate,scaleResolutionDownBy:a?Math.pow(2,i):void 0});t[0].scalabilityMode=d}else t.push({maxBitrate:c.maxBitrate,maxFramerate:p.encoding.maxFramerate,scalabilityMode:d});return p.encoding.priority&&(t[0].priority=p.encoding.priority,t[0].networkPriority=p.encoding.priority),ao.debug("using svc encoding",{encodings:t}),t}if(!l)return[c];let m=[];if((m=e?null!=(a=og(null==n?void 0:n.screenShareSimulcastLayers))?a:op(e,p):null!=(r=og(null==n?void 0:n.videoSimulcastLayers))?r:op(e,p)).length>0){let e=m[0];m.length>1&&([,o]=m);let n=Math.max(t,i);if(n>=960&&o)return om(t,i,[e,o,p],h);if(n>=480)return om(t,i,[e,p],h)}return om(t,i,[p])}function op(e,t){if(e)return[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(e=>{var i,n;return new rP(Math.floor(t.width/e.scaleResolutionDownBy),Math.floor(t.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!=(i=t.encoding.maxFramerate)?i:30)/(null!=(n=e.fps)?n:30))))),e.fps,t.encoding.priority)});let{width:i,height:n}=t,a=i>n?i/n:n/i;return Math.abs(a-16/9)<Math.abs(a-4/3)?ol:od}function om(e,t,i,n){let a=[];if(i.forEach((i,r)=>{if(r>=ou.length)return;let s=Math.min(e,t),o={rid:ou[r],scaleResolutionDownBy:Math.max(1,s/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(o.maxFramerate=c);let l=r$()||0===r;i.encoding.priority&&l&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),a.push(o)}),r9()&&"ios"===r7()){let e;a.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;a.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,ao.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ao.info('Setting framerate of encoding "'.concat(null!=(n=i.rid)?n:"",'" to ').concat(e)),i.maxFramerate=e)})}return a}function og(e){if(e)return e.sort((e,t)=>{let{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class of{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!=(e=this.suffix
1)?e:"")}}class ov extends oa{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,rW.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>ah(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(ed.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;let a=null==(n=this.prevStats)?void 0:n.get(i);e+=s7(t,a)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new eF}get isSimulcast(){return!!this.sender&&!!(this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!r4())return;let i=null==(t=this.sender)?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return ah(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var t,i,n,a,r,s,o=!0,c=ap(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);o=!0)a=s.value,o=!1,yield null==(r=a.sender)?void 0:r.replaceTrack(null)}catch(e){i={error:e}}finally{try{!o&&!t&&(n=c.return)&&(yield n.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return ah(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var t,i,n,a,r,s,o=!0,c=ap(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);o=!0)a=s.value,o=!1,yield null==(r=a.sender)?void 0:r.replaceTrack(a.mediaStreamTrack)}catch(e){i={error:e}}finally{try{!o&&!t&&(n=c.return)&&(yield n.call(c))}finally{if(i)throw i.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return ah(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source!==rW.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return ah(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;return this.source!==rW.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}setTrackMuted(e){for(let t of(super.setTrackMuted(e),this.simulcastCodecs.values()))t.mediaStreamTrack.enabled=!e}getSenderStats(){return ah(this,void 0,void 0,function*(){var e;if(!(null==(e=this.sender)?void 0:e.getStats))return[];let t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){let a={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!=(n=e.rid)?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(a.jitter=r.jitter,a.packetsLost=r.packetsLost,a.roundTripTime=r.roundTripTime),t.push(a)}}),t.sort((e,t)=>
1{var i,n;return(null!=(i=t.frameWidth)?i:0)-(null!=(n=e.frameWidth)?n:0)}),t})}setPublishingQuality(e){let t=[];for(let i=ep.LOW;i<=ep.HIGH;i+=1)t.push(new nC({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(rX(this.codec),t)}restartTrack(e){return ah(this,void 0,void 0,function*(){let t;if(e){let i=rN({video:e});"boolean"!=typeof i.video&&(t=i.video)}yield this.restart(t),this.isCpuConstrained=!1;try{for(var i,n,a,r,s,o,c=!0,l=ap(this.simulcastCodecs.values());!(i=(o=yield l.next()).done);c=!0)r=o.value,c=!1,r.sender&&(null==(s=r.sender.transport)?void 0:s.state)!=="closed"&&(r.mediaStreamTrack=this.mediaStreamTrack.clone(),yield r.sender.replaceTrack(r.mediaStreamTrack))}catch(e){n={error:e}}finally{try{!c&&!i&&(a=l.return)&&(yield a.call(l))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return ah(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){if(yield t.setProcessor.call(i,e,n),null==(c=i.processor)?void 0:c.processedTrack)try{for(var a,r,s,o,c,l,d,u=!0,h=ap(i.simulcastCodecs.values());!(a=(d=yield h.next()).done);u=!0)o=d.value,u=!1,yield null==(l=o.sender)?void 0:l.replaceTrack(i.processor.processedTrack)}catch(e){r={error:e}}finally{try{!u&&!a&&(s=h.return)&&(yield s.call(h))}finally{if(r)throw r.error}}}()})}setDegradationPreference(e){return ah(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);let i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){let i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return ah(this,void 0,void 0,function*(){var t,i,n,a,r,s,o;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(rX(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,i=ap(e);!(a=(n=yield i.next()).done);t=!0)if(o=n.value,t=!1,this.codec&&this.codec!==o.codec){let e=this.simulcastCodecs.get(o.codec);if(this.log.debug("try setPublishingCodec for ".concat(o.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:e})),e&&e.sender)e.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(o.codec),this.logContext),yield ok(e.sender,e.encodings,o.qualities,this.senderLock,rX(o.codec),this.log,this.logContext));else for(let e of o.qualities)if(e.enabled){c.push(o.codec);break}}else yield this.setPublishingLayers(rX(o.codec),o.qualities)}catch(e){r={error:e}}finally{try{!t&&!a&&(s=i.return)&&(yield s.call(i))}finally{if(r)throw r.error}}return c})}setPublishingLayers(e,t){return ah(this,void 0,void 0,function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield ok(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))})}prioritizePerformance(){return ah(this,void 0,void 0,function*(){if(!this.sender)throw Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!=(i=this.mediaStreamTrack.getSettings().height)?i:360)/360)),scalabilityMode:0===t&&rX(this.codec)?"L1T3":void 0,maxFramerate:15*(0===t),maxBitrate:0===t?e.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return ah(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),r3()&&this.isInBackgroun
1d&&this.source===rW.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ok(e,t,i,n,a,r,s){return ah(this,void 0,void 0,function*(){let o=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:e,qualities:i,senderEncodings:t}));try{let n=e.getParameters(),{encodings:o}=n;if(!o)return;if(o.length!==t.length)return void r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:o,senderEncodings:t}));let c=!1;a&&i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0),o.forEach((e,n)=>{var a;let o=null!=(a=e.rid)?a:"";""===o&&(o="q");let l=ob(o),d=i.find(e=>e.quality===l);d&&e.active!==d.enabled&&(c=!0,e.active=d.enabled,r.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled"),s),r$()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(n.encodings=o,r.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}})}function ob(e){switch(e){case"f":default:return ep.HIGH;case"h":return ep.MEDIUM;case"q":return ep.LOW}}function oy(e,t,i,n){if(!i)return[new iu({quality:ep.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){let n=new of(i[0].scalabilityMode),a=[],r="h"==n.suffix?1.5:2,s="h"==n.suffix?2:3;for(let o=0;o<n.spatial;o+=1)a.push(new iu({quality:Math.min(ep.HIGH,n.spatial-1)-o,width:Math.ceil(e/Math.pow(r,o)),height:Math.ceil(t/Math.pow(r,o)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(s,o)):0,ssrc:0}));return a}return i.map(i=>{var n,a,r;let s=null!=(n=i.scaleResolutionDownBy)?n:1;return new iu({quality:ob(null!=(a=i.rid)?a:""),width:Math.ceil(e/s),height:Math.ceil(t/s),bitrate:null!=(r=i.maxBitrate)?r:0,ssrc:0})})}let oT="_lossy",oC="_reliable",oS="leave-reconnect";(U=eR||(eR={}))[U.New=0]="New",U[U.Connected=1]="Connected",U[U.Disconnected=2]="Disconnected",U[U.Reconnecting=3]="Reconnecting",U[U.Closed=4]="Closed";class oE extends ag.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=s3.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=eR.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=ao,this.reliableDataSequence=1,this.reliableMessageBuffer=new sj,this.reliableReceivedState=new sF(3e4),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>ah(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===oC)t.reliableDCSub=i;else{if(i.label!==oT)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>ah(this,void 0,void 0,function*(){var t,i,n,a,r;let s=yield this.dataProcessLock.lock();try{let s;if(e.data instanceof ArrayBuffer)s=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));s=yield e.data.arrayBuffer()}let o=ip.fromBinary(new Uint8Array(s));if(o.sequence>0&&""!==o.participantSid){let e=this.reliableReceivedState.get(o.participantSid);if(e&&o.sequence<=e)return;this.reliableReceivedState.set(o.participantSid,o.sequence)}if((null==(t=o.value)?void 0:t.case)==="speaker")this.emit(el.ActiveSpeakersUpdate,o.value.value.speakers);else if((null==(i=o.value)?void 0:i.case)==="encryptedPacket"){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);let e=yield null==(n=this.e2eeManager)?void 0:n.handleEncryptedData(o.value.value.encryptedValue,o.value.value.iv,o.participantIdentity,o.value.value.keyIndex),t=iv.fromBinary(e.payload),i=new ip({value:t.value,participantIdentity:o.participantIdentity,participantSid:o.participantSid});(null==(a=i.value)?void 0:a.case)==="user"&&ow(i,i.value.value),this.emit
1(el.DataPacketReceived,i,o.value.value.encryptionType)}else(null==(r=o.value)?void 0:r.case)==="user"&&ow(o,o.value.value),this.emit(el.DataPacketReceived,o,is.NONE)}finally{s()}}),this.handleDataError=e=>{let t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){let{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{let t=0===e.currentTarget.maxRetransmits?im.LOSSY:im.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());let i=e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(el.Disconnected),this.close()},n=Date.now()-this.reconnectStart,a=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null===a?i(n):(e===oS&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=rw.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),a))},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===eR.Connected&&e();let i=()=>{this.off(el.Disconnected,n),e()},n=()=>{this.off(el.Restarted,i),t()};this.once(el.Restarted,i),this.once(el.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{if(e===im.RELIABLE){let t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}let t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(el.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>ah(this,void 0,void 0,function*(){!this.url||(yield fetch(sh(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===ey.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===ey.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(t9.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>ah(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(sh(this.url),{method:"HEAD"}),rz(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=ac(null!=(t=e.loggerName)?t:ee.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new sN(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new eF,this.dataProcessLock=new eF,this.dcBufferStatus=new Map([[im.LOSSY,!0],[im.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(el.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(el.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(el.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(el.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(el.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(el.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(el.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(el.SignalRequestResponse,e)}get logContext(){var e,t,i,n,a,r;return{room:null==(t=null==(e=this.latestJoinResponse)?void 0:e.room)?void 0:t.name,roomID:null==(n=null==(i=this.latestJoinResponse)?void 0:i.room)?void 0:n.sid,participant:null==(r=null==(a=this.latestJoinResponse)?void 0:a.participant)?void 0:r.identity,pID:this.participantSid}}join(e,t,i,n){return ah(this,arguments,void 0,function(e,t,i,n){var a=this;let r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){a.url=e,a.token=t,a.signalOpts=i,a.maxJoinAttempts=i.maxRetries;try{a.joinAttempts+=1,a.setupSignalClientCallbacks();let s=yield a.client.join(e,t,i,n,r);return a._isClosed=!1,a.latestJoinResponse=s,a.subscriberPrimary=s.subscriberPrimary,a.pcManager||(yield a.configure(s,!r)),(!a.subscriberPrimary||s.fastPublish)&&a.negotiate().catch(e=>{ao.error(e,a.logContext)}),a.registerOnLineListener(),a.clientConfiguration=s.clientConfiguration,a.emit(el.SignalConnected,s),s}catch(s){if(s instanceof rg){if(s.reason===ea.ServerUnreachable){if(a.log.warn("Couldn't connect to server, attempt ".concat(a.joinAttempts," of ").concat(a.maxJoinAttempts),a.logContext),a.joinAttempts<a.maxJoinAttempts)return a.join(e,t,i,n,r)}else if(s.reason===ea.ServiceNotFound)return a.log.warn("Initial connection failed: ".concat(s.message," – Retrying")),a.join(e,t,i,n,!0)}throw s}}()})}close(){return ah(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed)return void e();
1try{this._isClosed=!0,this.joinAttempts=0,this.emit(el.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return ah(this,void 0,void 0,function*(){var e;yield null==(e=this.pcManager)?void 0:e.close(),this.pcManager=void 0;let t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new sj,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return ah(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new rv("a track with the same ID has already been published");return new Promise((t,i)=>{let n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(rg.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null==(e=this.reliableDCSub)?void 0:e.readyState}getConnectedServerAddress(){return ah(this,void 0,void 0,function*(){var e;return null==(e=this.pcManager)?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return ah(this,void 0,void 0,function*(){var i,n,a;if(this.pcManager&&this.pcManager.currentState!==eP.NEW)return;this.participantSid=null==(i=e.participant)?void 0:i.sid;let r=this.makeRTCConfiguration(e);this.pcManager=new s4(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(el.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>ah(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===eP.CONNECTED){let t=this.pcState===eR.New;this.pcState=eR.Connected,t&&this.emit(el.Connected,e)}else t===eP.FAILED&&(this.pcState===eR.Connected||this.pcState===eR.Reconnecting)&&(this.pcState=eR.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?t9.RR_SUBSCRIBER_FAILED:t9.RR_PUBLISHER_FAILED));let a=this.client.isDisconnected||this.client.currentState===ey.RECONNECTING,r=[eP.FAILED,eP.CLOSING,eP.CLOSED].includes(t);a&&r&&!this._isClosed&&this.emit(el.Offline)}),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(el.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(a=null==(n=e.serverInfo)?void 0:n.protocol)&&a>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>ah(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>
1{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>ah(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;let n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null==(t=e.track)?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));let{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(el.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(el.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,null==(t=this.regionUrlProvider)||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(el.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(el.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null==(t=e.participant)?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(el.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;let n={direction:"recvonly"};for(let i=0;i<e.numAudios;i++)null==(t=this.pcManager)||t.addPublisherTransceiverOfKind("audio",n);for(let t=0;t<e.numVideos;t++)null==(i=this.pcManager)||i.addPublisherTransceiverOfKind("video",n);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",t9.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:e.regions})),e.action){case nh.DISCONNECT:this.emit(el.Disconnected,null==e?void 0:e.reason),this.close();break;case nh.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(oS);break;case nh.RESUME:this.handleDisconnect(oS)}}}makeRTCConfiguration(e){var t;let i=Object.assign({},this.rtcConfig);if((null==(t=this.signalOpts)?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){let t=[];e.iceServers.forEach(e=>{let i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===t3.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(oT,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(oC,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(im.LOSSY);e&&(e.bufferedAmountLowThreshold=Math.min(Math.max(this.lossyDataStatByterate/10,8192),262144))},1e3))}createSender(e,t,i){return ah(this,void 0,void 0,function*(){if(rQ())return yield this.createTransceiverRTCRtpSender(e,t,i);if(rY())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new rb("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,n){return ah(this,void 0,void 0,function*(){if(rQ())return this.createSimulcastTransceiverSender(e,t,i,n);if(rY())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new rb("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return ah(this,void 0,void 0,function*(){if(!this.pcManager)throw new rb("publisher is closed");let n=[];e.mediaStream&&n.push(e.mediaStream),sk(e)&&(e.codec=t.videoCodec);let a={direction:"sendonly",streams:n};return i&&(a.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,a)).sender})}createSimulcastTransceiverSender(e,t,i,n){return ah(this,void 0,void 0,function*(){if(!this.pcManager)throw new rb("publisher is closed");let a={direction:"sendonly"};n&&(a.sendEncodings=n);let r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,a);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender})}createRTCRtpSender(e){return ah(this,void 0,void 0,function*(){if(!this.pcManager)throw new rb("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return ah(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed){if(this.attemptingReconnect)return void ao.warn("already attempting reconnect, returning early",this.logContext);((null==(t=this.clientConfiguration)?void 0:t.resumeConnection)===t3.DISABLED||(null!=(n=null==(i=this.pcManager)?void 0:i.currentState)?n:eP.NEW)===eP.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let e=!0;t instanceof rb?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),e=!1):t instanceof rE||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",t9.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit
1(el.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return ah(this,void 0,void 0,function*(){var t,i,n;try{let i;if(!this.url||!this.token)throw new rb("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(el.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new rE;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(e){if(e instanceof rg&&e.reason===ea.NotAllowed)throw new rb("could not reconnect, token might be expired");throw new rE}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(this.client.setReconnected(),this.emit(el.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==ey.CONNECTED)throw new rE("Signal connection got severed during reconnect");null==(t=this.regionUrlProvider)||t.resetAttempts(),this.emit(el.Restarted)}catch(t){let e=yield null==(i=this.regionUrlProvider)?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null==(n=this.regionUrlProvider)||n.resetAttempts(),t}})}resumeConnection(e){return ah(this,void 0,void 0,function*(){var t;let i;if(!this.url||!this.token)throw new rb("could not reconnect, url or token not saved");if(!this.pcManager)throw new rb("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(el.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(t){let e="";if(t instanceof Error&&(e=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof rg&&t.reason===ea.NotAllowed)throw new rb("could not reconnect, token might be expired");if(t instanceof rg&&t.reason===ea.LeaveRequest)throw t;throw new rE(e)}
1if(this.emit(el.SignalResumed),i){let e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==ey.CONNECTED)throw new rE("Signal connection got severed during reconnect");this.client.setReconnected(),(null==(t=this.reliableDC)?void 0:t.readyState)==="open"&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(el.Resumed)})}waitForPCInitialConnection(e,t){return ah(this,void 0,void 0,function*(){if(!this.pcManager)throw new rb("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return ah(this,void 0,void 0,function*(){this.pcState=eR.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield rz(2e3),!this.pcManager)throw new rb("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=eR.Connected}catch(e){throw this.pcState=eR.Disconnected,rg.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,n){return ah(this,void 0,void 0,function*(){let a=new ip({destinationIdentities:[e],kind:im.RELIABLE,value:{case:"rpcResponse",value:new iR({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(a,im.RELIABLE)})}publishRpcAck(e,t){return ah(this,void 0,void 0,function*(){let i=new ip({destinationIdentities:[e],kind:im.RELIABLE,value:{case:"rpcAck",value:new iP({requestId:t})}});yield this.sendDataPacket(i,im.RELIABLE)})}sendDataPacket(e,t){return ah(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=function(e){var t,i,n,a,r;if((null==(t=e.value)?void 0:t.case)!=="sipDtmf"&&(null==(i=e.value)?void 0:i.case)!=="metrics"&&(null==(n=e.value)?void 0:n.case)!=="speaker"&&(null==(a=e.value)?void 0:a.case)!=="transcription"&&(null==(r=e.value)?void 0:r.case)!=="encryptedPacket")return new iv({value:e.value})}(e);if(t){let i=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new ig({encryptedValue:i.payload,iv:i.iv,keyIndex:i.keyIndex})}}}t===im.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===im.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100==0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return ah(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(im.RELIABLE);let t=this.dataChannelForKind(im.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(im.RELIABLE)})}waitForBufferStatusLow(e){return new ro((t,i)=>ah(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let n=()=>i(new rb("engine closed"));for(this.once(el.Closing,n);!this.dcBufferStatus.get(e);)yield rz(10);this.off(el.Closing,n),t()}}))}ensureDataTransportConnected(e){return ah(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new rb("PC manager is closed");let a=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!a)throw rg.internal("".concat(r," connection not set"));let s=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),s=!0),s||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(s=!0),s&&t.negotiate().catch(e=>{ao.error(e,t.logContext)});let o=t.dataChannelForKind(e,i);if((null==o?void 0:o.readyState)==="open")return;let c=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<c;){if(a.isICEConnected&&(null==(n=t.dataChannelForKind(e,i))?void 0:n.readyState)==="open")return;yield rz(50)}throw rg.internal("could not establish ".concat(r," connection, state: ").concat(a.getICEConnectionState()))}()})}ensurePublisherConnected(e){return ah(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===eP.CONNECTED&&!!this.client.ws&&this.client.ws.readyState!==WebSocket.CLOSED}negotiate(){return ah(this,void 0,void 0,function*(){return new ro((e,t)=>ah(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new ry("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();let i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new ry("cannot negotiate on closed engine")),this.on(el.Closing,n),this.pcManager.publisher.once(sz,e=>{let t=new Map;
1e.forEach(e=>{let i=e.codec.toLowerCase();rI.includes(i)&&t.set(e.payload,i)}),this.emit(el.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(e){e instanceof ry&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",t9.RR_UNKNOWN),e instanceof Error?t(e):t(Error(String(e)))}finally{this.off(el.Closing,n)}}))})}dataChannelForKind(e,t){if(t){if(e===im.LOSSY)return this.lossyDCSub;if(e===im.RELIABLE)return this.reliableDCSub}else{if(e===im.LOSSY)return this.lossyDC;if(e===im.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n,a,r;let s;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);let o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=null==(i=this.pcManager.subscriber)?void 0:i.getRemoteDescription(),d=null==(n=this.pcManager.subscriber)?void 0:n.getLocalDescription(),u=null==(r=null==(a=this.signalOpts)?void 0:a.autoSubscribe)||r,h=[],p=[];e.forEach(e=>{e.isDesired!==u&&h.push(e.trackSid),e.isEnabled||p.push(e.trackSid)}),this.client.sendSyncState(new nO({answer:"publisher-only"===this.pcManager.mode?c?sU({sdp:c.sdp,type:c.type}):void 0:d?sU({sdp:d.sdp,type:d.type}):void 0,offer:"publisher-only"===this.pcManager.mode?o?sU({sdp:o.sdp,type:o.type}):void 0:l?sU({sdp:l.sdp,type:l.type}):void 0,subscription:new nr({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:(s=[],t.forEach(e=>{void 0!==e.track&&s.push(new nt({cid:e.track.mediaStreamID,track:e.trackInfo}))}),s),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new nD({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,i)=>{(null==t?void 0:t.id)!==void 0&&null!==t.id&&e.push(new nM({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(im.LOSSY),iz.PUBLISHER),t(this.dataChannelForKind(im.RELIABLE),iz.PUBLISHER),t(this.dataChannelForKind(im.LOSSY,!0),iz.SUBSCRIBER),t(this.dataChannelForKind(im.RELIABLE,!0),iz.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&rw.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){r4()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){r4()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;let i=null==(t=this.pcManager)?void 0:t.getMidForReceiver(e);if(i){let e=Object.entries(this.midToTrackId).find(e=>{let[t]=e;return t===i});if(e)return e[1]}}}function ow(e,t){let i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;let n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}class oP{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(e&&this.bytesReceived<this.totalByteSize)throw new rS("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),er.Incomplete);else if(this.bytesReceived>this.totalByteSize)throw new rS("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),er.LengthExceeded)}}constructor(e,t,i,n){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class oR extends oP{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null==(t=this.onProgress)||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader(),t=new sd,i=null,n=null;if(this.signal){let e=this.signal;n=()=>{var i;null==(i=t.reject)||i.call(t,e.reason)},e.addEventListener("abort",n),i=e}let a=()=>{e.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>ah(this,void 0,void 0,function*(){var i,n;try{let{done:a,value:r}=yield Promise.race([e.read(),t.promise,null!=(n=null==(i=this.outOfBandFailureRejectingFuture)?void 0:i.promise)?n:new Promise(()=>{})]);if(a)return this.validateBytesReceived(!0),{done:!0,value:void 0};return this.handleChunkReceived(r),{done:!1,value:r.content}}catch(e){throw a(),e}}),return(){return ah(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return ah(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,a,r;let s=new Set,o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,l=!0,d=ap(o);!(i=(c=yield d.next()).done);l=!0)r=c.value,l=!1,s.add(r)}catch(e){n={error:e}}finally{try{!l&&!i&&(a=d.return)&&(yield a.call(d))}finally{if(n)throw n.error}}return Array.from(s)}()})}}class oI extends oP{constructor(e,t,i,n){super(e,t,i,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let i=sm(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let a=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null==(t=this.onProgress)||t.call(this,a)}[Symbol.asyncIterator](){let e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0}),i=new sd,n=null,a=null;if(this.signal){let e=this.signal;a=()=>{var t;null==(t=i.reject)||t.call(i,e.reason)},e.addEventListener("abort",a),n=e}let r=()=>{e.releaseLock(),n&&a&&n.removeEventListener("abort",a),this.signal=void 0};return{next:()=>ah(this,void 0,void 0,function*(){var n,a;try{let{done:r,value:s}=yield Promise.race([e.read(),i.promise,null!=(a=null==(n=this.outOfBandFailureRejectingFuture)?void 0:n.promise)?a:new Promise(()=>{})]);if(r)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(s);try{e=t.decode(s.content)}catch(e){throw new rS("Cannot decode datastream chunk ".concat(s.chunkIndex," as text: ").concat(e),er.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw r(),e}}),return(){return ah(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return ah(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,a,r;let s="",o=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,l=!0,d=ap(o);!(i=(c=yield d.next()).done);l=!0)r=c.value,l=!1,s+=r}catch(e){n={error:e}}finally{try{!l&&!i&&(a=d.return)&&(yield a.call(d))}finally{if(n)throw n.error}}return s}()})}}class o_{constructor(){this.log=ao,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new rS('A text stream handler for topic "'.concat(e,'" has already been set.'),er.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new rS('A byte stream handler for topic "'.concat(e,'" has already been set.'),er.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}
1validateParticipantHasNoActiveDataStreams(e){var t,i,n,a;let r=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),s=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(r.length>0||s.length>0){let o=new rS("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),er.AbnormalEnd);for(let[e,n]of s)null==(i=(t=n.outOfBandFailureRejectingFuture).reject)||i.call(t,o),this.byteStreamControllers.delete(e);for(let[e,t]of r)null==(a=(n=t.outOfBandFailureRejectingFuture).reject)||a.call(n,o),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return ah(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return ah(this,void 0,void 0,function*(){var n;if("byteHeader"===e.contentHeader.case){let a,r=this.byteStreamHandlers.get(e.topic);if(!r)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s=new sd;s.promise.catch(e=>{this.log.error(e)});let o={id:e.streamId,name:null!=(n=e.contentHeader.value.name)?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:sm(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(a=i,this.textStreamControllers.has(e.streamId))throw new rS("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),er.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:s})}});r(new oR(o,c,sm(e.totalLength),s),{identity:t})}else if("textHeader"===e.contentHeader.case){let n,a=this.textStreamHandlers.get(e.topic);if(!a)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let r=new sd;r.promise.catch(e=>{this.log.error(e)});let s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},o=new ReadableStream({start:i=>{if(n=i,this.textStreamControllers.has(e.streamId))throw new rS("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),er.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:r})}});a(new oI(s,o,sm(e.totalLength),r),{identity:t})}})}handleStreamChunk(e,t){let i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new rS("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),er.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new rS("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),er.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e))}handleStreamTrailer(e,t){let i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new rS("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),er.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new rS("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),er.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class oO{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return ah(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null==(e=this.onClose)||e.call(this)})}}class oD extends oO{}class oM extends oO{}class ox{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return ah(this,void 0,void 0,function*(){var i;let n=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,r=null==(i=null==t?void 0:t.attachments)?void 0:i.map(()=>crypto.randomUUID()),s=Array(r?r.length+1:1).fill(0),o=(e,i)=>{var n;s[i]=e;let a=s.reduce((e,t)=>
1e+t,0);null==(n=null==t?void 0:t.onProgress)||n.call(t,a)},c=yield this.streamText({streamId:n,totalSize:a,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:r,attributes:null==t?void 0:t.attributes});return yield c.write(e),o(1,0),yield c.close(),(null==t?void 0:t.attachments)&&r&&(yield Promise.all(t.attachments.map((e,i)=>ah(this,void 0,void 0,function*(){return this._sendFile(r[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,i+1)}})})))),c.info})}streamText(e){return ah(this,void 0,void 0,function*(){var t,i,n;let a=null!=(t=null==e?void 0:e.streamId)?t:crypto.randomUUID(),r={id:a,mimeType:"text/plain",timestamp:Date.now(),topic:null!=(i=null==e?void 0:e.topic)?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes,encryptionType:(null==(n=this.engine.e2eeManager)?void 0:n.isDataChannelEncryptionEnabled)?is.GCM:is.NONE,attachedStreamIds:null==e?void 0:e.attachedStreamIds},s=new iq({streamId:a,mimeType:r.mimeType,topic:r.topic,timestamp:sg(r.timestamp),totalLength:sg(null==e?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new iF({version:null==e?void 0:e.version,attachedStreamIds:r.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:(null==e?void 0:e.type)==="update"?ij.UPDATE:ij.CREATE})}}),o=null==e?void 0:e.destinationIdentities,c=new ip({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(c,im.RELIABLE);let l=0,d=this.engine,u=new WritableStream({write(e){return ah(this,void 0,void 0,function*(){for(let t of function(e){let t=[],i=new TextEncoder().encode(e);for(;i.length>15e3;){let e=15e3;for(;e>0;){let t=i[e];if(void 0!==t&&(192&t)!=128)break;e--}t.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&t.push(i),t}(e)){let e=new ip({destinationIdentities:o,value:{case:"streamChunk",value:new iV({content:t,streamId:a,chunkIndex:sg(l)})}});yield d.sendDataPacket(e,im.RELIABLE),l+=1}})},close(){return ah(this,void 0,void 0,function*(){let e=new ip({destinationIdentities:o,value:{case:"streamTrailer",value:new iH({streamId:a})}});yield d.sendDataPacket(e,im.RELIABLE)})},abort(e){console.log("Sink error:",e)}}),h=()=>ah(this,void 0,void 0,function*(){yield p.close()});d.once(el.Closing,h);let p=new oD(u,r,()=>this.engine.off(el.Closing,h));return p})}sendFile(e,t){return ah(this,void 0,void 0,function*(){let i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return ah(this,void 0,void 0,function*(){var n;let a=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!=(n=null==i?void 0:i.mimeType)?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=t.stream().getReader();for(;;){let{done:e,value:t}=yield r.read();if(e)break;yield a.write(t)}return yield a.close(),a.info})}streamBytes(e){return ah(this,void 0,void 0,function*(){var t,i,n,a,r,s;let o=null!=(t=null==e?void 0:e.streamId)?t:crypto.randomUUID(),c=null==e?void 0:e.destinationIdentities,l={id:o,mimeType:null!=(i=null==e?void 0:e.mimeType)?i:"application/octet-stream",topic:null!=(n=null==e?void 0:e.topic)?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!=(a=null==e?void 0:e.name)?a:"unknown",encryptionType:(null==(r=this.engine.e2eeManager)?void 0:r.isDataChannelEncryptionEnabled)?is.GCM:is.NONE},d=new ip({destinationIdentities:c,value:{case:"streamHeader",value:new iq({totalLength:sg(null!=(s=l.size)?s:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:sg(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new iB({name:l.name})}})}});yield this.engine.sendDataPacket(d,im.RELIABLE);let u=0,h=new eF,p=this.engine,m=this.log;return new oM(new WritableStream({write(e){return ah(this,void 0,void 0,function*(){let t=yield h.lock(),i=0;try{for(;i<e.byteLength;){let t=e.slice(i,i+15e3),n=new ip({destinationIdentities:c,value:{case:"streamChunk",value:new iV({content:t,streamId:o,chunkIndex:sg(u)})}});yield p.sendDataPacket(n,im.RELIABLE),u+=1,i+=t.byteLength}}finally{t()}})},close(){return ah(this,void 0,void 0,function*(){let e=new ip({destinationIdentities:c,value:{case:"streamTrailer",value:new iH({streamId:o})}});yield p.sendDataPacket(e,im.RELIABLE)})},abort(e){m.error("Sink error:",e)}}),l)})}}class oA extends rW{constructor(e,t,i,n,a){super(e,i,a),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit
1(e?ed.Muted:ed.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(ed.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return ah(this,void 0,void 0,function*(){var e;if(null==(e=this.receiver)?void 0:e.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver)if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;else this.log.warn("Playout delay not supported in this browser");else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),2e3)),"u">typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());let i=null==(t=this.receiver)?void 0:t.getSynchronizationSources()[0];if(i){let{timestamp:e,rtpTimestamp:t}=i;
1t&&this.rtpTimestamp!==t&&(this.emit(ed.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class oN extends oA{constructor(e,t,i,n,a,r){super(e,t,rW.Kind.Audio,i,r),this.monitorReceiver=()=>ah(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=s7(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],a&&(this.sinkId=a.deviceId)}setVolume(e){var t;for(let i of this.attachedElements)this.audioContext?null==(t=this.gainNode)||t.gain.setTargetAtTime(e,0,.1):i.volume=e;r9()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(r9())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return ah(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(rZ(t))return t.setSinkId(e)}))})}attach(e){let t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&rZ(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(ed.AudioPlaybackFailed,Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(ed.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null==(e=this.gainNode)||e.disconnect(),null==(t=this.sourceNode)||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return ah(this,void 0,void 0,function*(){let e;if(this.receiver&&this.receiver.getStats)return(yield this.receiver.getStats()).forEach(t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})}),e})}}class oL extends oA{constructor(e,t,i,n,a){super(e,t,rW.Kind.Video,i,a),this.elementInfos=[],this.monitorReceiver=()=>ah(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=s7(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=sG(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===rW.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?rK(this._mediaStreamTrack,t):rG(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){let t=new oU(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);for(let t of this.elementInfos.filter(t=>t===e))t.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);for(let e of t=super.detach())this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null==(e=this.prevStats)?void 0:e.decoderImplementation}getReceiverStats(){return ah(this,void 0,void 0,function*(){let e;if(!this.receiver||!this.receiver.getStats)return;let t=yield this.receiver.getStats(),i="",n=new Map;return t.forEach(t=>
1{"inbound-rtp"===t.type?(i=t.codecId,e={type:"video",streamId:t.id,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation}):"codec"===t.type&&n.set(t.id,t)}),e&&""!==i&&n.get(i)&&(e.mimeType=n.get(i).mimeType),e})}stopObservingElement(e){for(let t of this.elementInfos.filter(t=>t.element===e))this.stopObservingElementInfo(t)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return ah(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;let n=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),a=(null==(i=null==(t=this.adaptiveStreamSettings)?void 0:t.pauseVideoInBackground)||!!i)&&this.isInBackground,r=this.elementInfos.some(e=>e.pictureInPicture),s=this.elementInfos.some(e=>e.visible)&&!a||r;if(this.lastVisible!==s||e){if(!s&&Date.now()-n<100)return void rw.setTimeout(()=>{this.updateVisibility()},100);this.lastVisible=s,this.emit(ed.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let i=0,n=0,a=this.getPixelDensity();for(let e of this.elementInfos){let t=e.width()*a,r=e.height()*a;t+r>i+n&&(i=t,n=r)}((null==(e=this.lastDimensions)?void 0:e.width)!==i||(null==(t=this.lastDimensions)?void 0:t.height)!==n)&&(this.lastDimensions={width:i,height:n},this.emit(ed.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=null==(e=this.adaptiveStreamSettings)?void 0:e.pixelDensity;return"screen"===t?se():t?t:se()>2?2:1}}class oU{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=oj(this.element),this.visibilityChangedAt=Date.now(),null==(t=this.handleVisibilityChanged)||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null==(t=null==(e=window.documentPictureInPicture)?void 0:e.window)||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=oj(this.element),null==(i=this.handleVisibilityChanged)||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=oj(this.element),null==(e=this.handleVisibilityChanged)||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:oF(e),this.isPiP=r4()&&oj(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=oF(this.element),this.isPiP=oj(this.element),this.element.handleResize=()=>{var e;null==(e=this.handleResize)||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,so().observe(this.element),sr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null==(e=window.documentPictureInPicture)||e.addEventListener("enter",this.onEnterPiP),null==(i=null==(t=window.documentPictureInPicture)?void 0:t.window)||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,a;null==(e=so())||e.unobserve(this.element),null==(t=sr())||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null==(i=window.documentPictureInPicture)||i.removeEventListener("enter",this.onEnterPiP),null==(a=null==(n=window.documentPictureInPicture)?void 0:n.window)||a.removeEventListener("pagehide",this.onLeavePiP)}}function oj(e){var t,i;return document.pictureInPictureElement===e||null!=(t=window.documentPictureInPicture)&&!!t.window&&oF(e,null==(i=window.documentPictureInPicture)?void 0:i.window)}function oF(e,t){let i=t||window,n=e.offsetTop,a=e.offsetLeft,r=e.offsetWidth,s=e.offsetHeight,{hidden:o}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,a+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&a<i.pageXOffset+i.innerWidth&&n+s>i.pageYOffset&&a+r>i.pageXOffset&&!o&&"none"!==c}class oB extends ag.EventEmitter{constructor(e,t,i,n){var a;super(),this.metadataMuted=!1,this.encryption=is.NONE,this.log=ao,this.handleMuted=()=>
1{this.emit(ed.Muted)},this.handleUnmuted=()=>{this.emit(ed.Unmuted)},this.log=ac(null!=(a=null==n?void 0:n.loggerName)?a:ee.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=rW.Source.Unknown}setTrack(e){this.track&&(this.track.off(ed.Muted,this.handleMuted),this.track.off(ed.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ed.Muted,this.handleMuted),e.on(ed.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null==(e=this.loggerContextCb)?void 0:e.call(this)),rB(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==is.NONE}get audioTrack(){if(sv(this.track))return this.track}get videoTrack(){if(sk(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=rW.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===rW.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(F=(j=oB||(oB={})).SubscriptionStatus||(j.SubscriptionStatus={})).Desired="desired",F.Subscribed="subscribed",F.Unsubscribed="unsubscribed",(B=j.PermissionStatus||(j.PermissionStatus={})).Allowed="allowed",B.NotAllowed="not_allowed";class oq extends oB{get isUpstreamPaused(){var e;return null==(e=this.track)?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(ed.Ended)},this.handleCpuConstrained=()=>{this.track&&sk(this.track)&&this.emit(ed.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(ed.Ended,this.handleTrackEnded),this.track.off(ed.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ed.Ended,this.handleTrackEnded),e.on(ed.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return ah(this,void 0,void 0,function*(){var e;return null==(e=this.track)?void 0:e.mute()})}unmute(){return ah(this,void 0,void 0,function*(){var e;return null==(e=this.track)?void 0:e.unmute()})}pauseUpstream(){return ah(this,void 0,void 0,function*(){var e;yield null==(e=this.track)?void 0:e.pauseUpstream()})}resumeUpstream(){return ah(this,void 0,void 0,function*(){var e;yield null==(e=this.track)?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(!sv(this.track))return[];{let t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(t5.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(t5.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(t5.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(t5.TF_STEREO),(null==(e=this.options)?void 0:e.dtx)||i.add(t5.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(t5.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}}}function oV(e,t){return ah(this,void 0,void 0,function*(){null!=e||(e={});let i=!1,{audioProcessor:n,videoProcessor:a,optionsWithoutProcessor:r}=rq(e),s=r.audio,o=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),a&&"object"==typeof r.video&&(r.video.processor=a),e.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){let e=r.audio.deviceId;r.audio.deviceId={exact:e},i=!0,s=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:e}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){let e=r.video.deviceId;r.video.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:e}})}!0===r.audio?r.audio={deviceId:"default"}:"object"==typeof r.audio&&null!==r.audio&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),!0===r.video?r.video={deviceId:"default"}:"object"!=typeof r.video||r.video.deviceId||(r.video.deviceId="default");let c=rx(r,s0,s1),l=rN(c),d=navigator.mediaDevices.getUserMedia(l);
1r.audio&&(sD.userMediaPromiseMap.set("audioinput",d),d.catch(()=>sD.userMediaPromiseMap.delete("audioinput"))),r.video&&(sD.userMediaPromiseMap.set("videoinput",d),d.catch(()=>sD.userMediaPromiseMap.delete("videoinput")));try{let e=yield d;return yield Promise.all(e.getTracks().map(i=>ah(this,void 0,void 0,function*(){let r,s="audio"===i.kind,o=s?c.audio:c.video;"boolean"!=typeof o&&o||(o={});let d=s?l.audio:l.video;"boolean"!=typeof d&&(r=d);let u=i.getSettings().deviceId;(null==r?void 0:r.deviceId)&&su(r.deviceId)!==u?r.deviceId=u:r||(r={deviceId:u});let h=function(e,t,i){switch(e.kind){case"audio":return new or(e,t,!1,void 0,i);case"video":return new ov(e,t,!1,i);default:throw new rv("unsupported track type: ".concat(e.kind))}}(i,r,t);return h.kind===rW.Kind.Video?h.source=rW.Source.Camera:h.kind===rW.Kind.Audio&&(h.source=rW.Source.Microphone),h.mediaStream=e,sv(h)&&n?yield h.setProcessor(n):sk(h)&&a&&(yield h.setProcessor(a)),h})))}catch(n){if(!i)throw n;return oV(Object.assign(Object.assign({},e),{audio:s,video:o}),t)}})}function oH(e){return ah(this,void 0,void 0,function*(){return(yield oV({audio:null==e||e,video:!1}
1))[0]})}(q=eI||(eI={})).Excellent="excellent",q.Good="good",q.Poor="poor",q.Lost="lost",q.Unknown="unknown";class oW extends ag.EventEmitter{get logContext(){var e,t;return Object.assign({},null==(t=null==(e=this.loggerOptions)?void 0:e.loggerContextCb)?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return(null==(e=this.permissions)?void 0:e.agent)||this.kind===ia.AGENT}get isActive(){var e;return(null==(e=this.participantInfo)?void 0:e.state)===ii.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,a,r){var s;let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:ia.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=eI.Unknown,this.log=ao,this.log=ac(null!=(s=null==r?void 0:r.loggerName)?s:ee.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=a?a:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new sd,this.once(ec.Active,()=>{var e,t;null==(t=null==(e=this.activeFuture)?void 0:e.resolve)||t.call(e),this.activeFuture=void 0})),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;let t=this.getTrackPublication(rW.Source.Camera);return!(null==(e=null==t?void 0:t.isMuted)||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(rW.Source.Microphone);return!(null==(e=null==t?void 0:t.isMuted)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(rW.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return(!this.participantInfo||this.participantInfo.sid!==e.sid||!(this.participantInfo.version>e.version))&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===ii.ACTIVE&&(null==(t=this.participantInfo)?void 0:t.state)!==ii.ACTIVE&&this.emit(ec.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(ec.ParticipantMetadataChanged,i)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(ec.ParticipantNameChanged,e)}_setAttributes(e){let t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});let n=[...Object.keys(t),...Object.keys(e)],a={};for(let r of n)e[r]!==t[r]&&(a[r]=null!=(i=t[r])?i:"");return a}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(ec.AttributesChanged,t)}setPermissions(e){var t,i,n,a,r,s;let o=this.permissions,c=e.canPublish!==(null==(t=this.permissions)?void 0:t.canPublish)||e.canSubscribe!==(null==(i=this.permissions)?void 0:i.canSubscribe)||e.canPublishData!==(null==(n=this.permissions)?void 0:n.canPublishData)||e.hidden!==(null==(a=this.permissions)?void 0:a.hidden)||e.recorder!==(null==(r=this.permissions)?void 0:r.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null==(i=this.permissions)?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null==(s=this.permissions)?void 0:s.canSubscribeMetrics);return this.permissions=e,c&&this.emit(ec.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ec.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case t2.EXCELLENT:return eI.Excellent;case t2.GOOD:return eI.Good;case t2.POOR:return eI.Poor;case t2.LOST:return eI.Lost;default:return eI.Unknown}}
1(e),t!==this._connectionQuality&&this.emit(ec.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null==(t=(e=this.activeFuture).reject)||t.call(e,Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>sv(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){switch(e.on(ed.Muted,()=>{this.emit(ec.TrackMuted,e)}),e.on(ed.Unmuted,()=>{this.emit(ec.TrackUnmuted,e)}),e.track&&(e.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case rW.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case rW.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class oG extends oW{constructor(e,t,i,n,a,r){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=is.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new sd)},this.handleReconnected=()=>{var e,t;null==(t=null==(e=this.reconnectFuture)?void 0:e.resolve)||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,a,r;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null==(t=null==(e=this.reconnectFuture)?void 0:e.reject)||t.call(e,Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null==(n=(i=this.signalConnectedFuture).reject)||n.call(i,Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null==(r=null==(a=this.activeAgentFuture)?void 0:a.reject)||r.call(a,Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new sd),null==(i=(t=this.signalConnectedFuture).resolve)||i.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:i,message:n}=e,a=this.pendingSignalRequests.get(t);a&&(i!==nB.OK&&a.reject(new rC(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=s6.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let a=e.value.value;this.handleIncomingRpcAck(a.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>(function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new nP({participantIdentity:null!=(t=e.participantIdentity)?t:"",participantSid:null!=(i=e.participantSid)?i:"",allTracks:null!=(n=e.allowAll)&&n,trackSids:e.allowedTrackSids||[]})})(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{(void 0===t&&(t=!0),e.sid)?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),rB(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),rB(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),rB(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({}
1,this.logContext),rB(t))),this.emit(ec.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>ah(this,void 0,void 0,function*(){if(!(null==(o=this.roomOptions)?void 0:o.dynacast))return;let t=this.videoTrackPublications.get(e.trackSid);if(!t)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!t.videoTrack)return;let i=yield t.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var n,a,r,s,o,c,l=!0,d=ap(i);!(n=(c=yield d.next()).done);l=!0)s=c.value,l=!1,r_(s)&&(this.log.debug("publish ".concat(s," for ").concat(t.videoTrack.sid),Object.assign(Object.assign({},this.logContext),rB(t))),yield this.publishAdditionalCodecForTrack(t.videoTrack,s,t.options))}catch(e){a={error:e}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(a)throw a.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>ah(this,void 0,void 0,function*(){if(e.source===rW.Source.ScreenShare||e.source===rW.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),rB(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(sy(e)||sb(e))try{if(r4())try{let t=yield null==navigator?void 0:navigator.permissions.query({name:e.source===rW.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),rB(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),rB(e))),sy(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),rB(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=a,this.roomOutgoingDataStreamManager=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==is.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(el.RemoteMute,(e,t)=>{let i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null==(t=this.signalConnectedFuture)?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(el.Connected,this.handleReconnected).on(el.SignalConnected,this.handleSignalConnected).on(el.SignalRestarted,this.handleReconnected).on(el.SignalResumed,this.handleReconnected).on(el.Restarting,this.handleReconnecting).on(el.Resuming,this.handleReconnecting).on(el.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(el.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(el.Closing,this.handleClosing).on(el.SignalRequestResponse,this.handleSignalRequestResponse).on(el.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return ah(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return ah(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return ah(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return ah(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:a}=e;return function*(){return new ro((e,r)=>ah(t,void 0,void 0,function*(){var t,s;try{let o=!1,c=yield this.engine.client.sendUpdateLocalMetadata(null!=(t=null!=i?i:this.metadata)?t:"",null!=(s=null!=n?n:this.name)?s:"",a),l=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),o=!0},values:{name:n,metadata:i,attributes:a}});performance.now()-l<5e3&&!o;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!a||Object.entries(a).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))){this.pendingSignalRequests.delete(c),e();return}yield rz(50)}r(new rC("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error?r(e):r(Error(String(e)))}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(rW.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(rW.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(rW.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return ah(this,void 0,void 0,function*(){this.encryptionType=e?is.GCM:is.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,n){return ah(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(e);if(t)if(a)yield a.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case rW.Source.Camera:t=yield this.createTracks({video:null==i||i});break;case rW.Source.Microphone:t=yield this.createTracks({audio:null==i||i});break;case rW.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new rv(e)}}
1catch(i){throw null==t||t.forEach(e=>{e.stop()}),i instanceof Error&&this.emit(ec.MediaDevicesError,i,rj(e)),this.pendingPublishing.delete(e),i}for(let n of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===rW.Source.Microphone&&sv(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{let e=[];for(let i of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),rB(i))),e.push(this.publishTrack(i,n));let i=yield Promise.all(e);[a]=i}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==a?void 0:a.track)&&this.pendingPublishing.has(e)&&((a=yield this.waitForPendingPublicationOfSource(e))||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===rW.Source.ScreenShare){a=yield this.unpublishTrack(a.track);let e=this.getTrackPublication(rW.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return ah(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(rW.Source.Camera)||this.pendingPublishing.has(rW.Source.Microphone))){this.pendingPublishing.add(rW.Source.Camera),this.pendingPublishing.add(rW.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(rW.Source.Camera),this.pendingPublishing.delete(rW.Source.Microphone)}}})}createTracks(e){return ah(this,void 0,void 0,function*(){var t,i;null!=e||(e={});let n=rx(e,null==(t=this.roomOptions)?void 0:t.audioCaptureDefaults,null==(i=this.roomOptions)?void 0:i.videoCaptureDefaults);try{return(yield oV(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(sv(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=rW.Source.Microphone,this.emit(ec.AudioStreamAcquired)),sk(e)&&(this.cameraError=void 0,e.source=rW.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return ah(this,void 0,void 0,function*(){var t,i,n;let a,r;if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new rf("getDisplayMedia not supported");
1void 0!==e.resolution||(null==(a=rl())?void 0:a.name)==="Safari"&&a.version.startsWith("17.")||(null==a?void 0:a.os)==="iOS"&&(null==a?void 0:a.osVersion)&&st(a.osVersion,"17")>=0||(e.resolution=rM.h1080fps30.resolution);let s=(r=null==(i=(t=e).video)||i,t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(r="boolean"==typeof r?{}:r,r=r1()?Object.assign(Object.assign({},r),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):Object.assign(Object.assign({},r),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:null!=(n=t.audio)&&n,video:r,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}),o=yield navigator.mediaDevices.getDisplayMedia(s),c=o.getVideoTracks();if(0===c.length)throw new rv("no video track found");let l=new ov(c[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});l.source=rW.Source.ScreenShare,e.contentHint&&(l.mediaStreamTrack.contentHint=e.contentHint);let d=[l];if(o.getAudioTracks().length>0){this.emit(ec.AudioStreamAcquired);let e=new or(o.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=rW.Source.ScreenShareAudio,d.push(e)}return d})}publishTrack(e,t){return ah(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return ah(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var a,r;let s,o;if(sy(e)&&e.setAudioContext(i.audioContext),yield null==(a=i.reconnectFuture)?void 0:a.promise,i.republishPromise&&!n&&(yield i.republishPromise),sf(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)s=e.getConstraints();else{let t;switch(s=e.constraints,e.source){case rW.Source.Microphone:t="audioinput";break;case rW.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(s=Object.assign(Object.assign({},s),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new or(e,s,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new ov(e,s,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new rv("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(o=t)}),o)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),rB(o))),o;let c=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t),l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,d=null!=(r=c.forceStereo)?r:l;d&&(void 0===c.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),rB(e))),void 0===c.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!=c.dtx||(c.dtx=!1),null!=c.red||(c.red=!1)),!function(){let e=rl(),t="17.2";if(e)if("Safari"!==e.name&&"iOS"!==e.os)return!0;else if("iOS"===e.os&&e.osVersion&&st(e.osVersion,t)>=0)return!0;else if("Safari"===e.name&&st(e.version,t)>=0)return!0;else return!1}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),c.simulcast=!1),c.source&&(e.source=c.source);let u=new Promise((t,n)=>ah(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ey.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:rB(e)}));let i=!1,a=setTimeout(()=>{i=!0,e.stop(),n(new rT("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(a),i)return;let r=yield this.publish(e,c,d);t(r)}else try{let i=yield this.publish(e,c,d);t(i)}catch(e){n(e)}}catch(e){n(e)}}));i.pendingPublishPromises.set(e,u);try{return yield u}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new sd),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),rB(e))),!1;let{canPublish:t,canPublishSources:i}=this.permissions;return!!(t&&(0===i.length||i.map(e=>(function(e){switch(e){case t0.CAMERA:return rW.Source.Camera;case t0.MICROPHONE:return rW.Source.Microphone;case t0.SCREEN_SHARE:return rW.Source.ScreenShare;case t0.SCREEN_SHARE_AUDIO:return rW.Source.ScreenShareAudio;default:return rW.Source.Unknown}})(e)).includes(e.source)))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),rB(e))),!1)}publish(e,t,i){return ah(this,void 0,void 0,function*(){var n,a,r,s,o,
1c,l,d,u,h;let p,m;if(!this.hasPermissionsToPublish(e))throw new rT("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>sf(e)&&t.source===e.source)&&e.source!==rW.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),rB(e))),t.stopMicTrackOnMute&&sv(e)&&(e.stopOnMute=!0),e.source===rW.Source.ScreenShare&&r$()&&(t.simulcast=!1),"av1"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||r1()||r$())return!1;let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/av1"===i.mimeType.toLowerCase()){t=!0;break}}return t}()&&(t.videoCodec=void 0),"vp9"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||r$())return!1;if(r1()){let e=rl();if((null==e?void 0:e.version)&&0>st(e.version,"16")||(null==e?void 0:e.os)==="iOS"&&(null==e?void 0:e.osVersion)&&0>st(e.osVersion,"16"))return!1}let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/vp9"===i.mimeType.toLowerCase()){t=!0;break}}return t}()&&(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec="vp8"),this.enabledPublishVideoCodecs.length>0&&!this.enabledPublishVideoCodecs.some(e=>t.videoCodec===rF(e.mime))&&(t.videoCodec=rF(this.enabledPublishVideoCodecs[0].mime));let g=t.videoCodec;e.on(ed.Muted,this.onTrackMuted),e.on(ed.Unmuted,this.onTrackUnmuted),e.on(ed.Ended,this.handleTrackEnded),e.on(ed.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ed.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ed.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let f=[],v=!(null==(n=t.dtx)||n),k=e.getSourceTrackSettings();k.autoGainControl&&f.push(t5.TF_AUTO_GAIN_CONTROL),k.echoCancellation&&f.push(t5.TF_ECHO_CANCELLATION),k.noiseSuppression&&f.push(t5.TF_NOISE_SUPPRESSION),k.channelCount&&k.channelCount>1&&f.push(t5.TF_STEREO),v&&f.push(t5.TF_NO_DTX),sy(e)&&e.hasPreConnectBuffer&&f.push(t5.TF_PRECONNECT_BUFFER);let b=new i0({cid:e.mediaStreamTrack.id,name:t.name,type:rW.kindToProto(e.kind),muted:e.isMuted,source:rW.sourceToProto(e.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null==(a=t.red)||a),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:f});if(e.kind===rW.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(n){let t=null!=(s=null==(r=this.roomOptions.videoCaptureDefaults)?void 0:r.resolution)?s:rO.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),rB(e)),{dims:i}))}b.width=i.width,b.height=i.height,sb(e)&&(rX(g)&&(e.source===rW.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),rB(e))))),t.scalabilityMode=null!=(o=t.scalabilityMode)?o:"L3T3_KEY"),b.simulcastCodecs=[new i$({codec:g,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:"vp8"}),t.backupCodec&&g!==t.backupCodec.codec&&b.encryption===is.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),b.simulcastCodecs.push(new i$({codec:t.backupCodec.codec,cid:""})))),p=oh(e.source===rW.Source.ScreenShare,b.width,b.height,t),b.layers=oy(b.width,b.height,p,rX(t.videoCodec))}else e.kind===rW.Kind.Audio&&(p=[{maxBitrate:null==(c=t.audioPreset)?void 0:c.maxBitrate,priority:null!=(d=null==(l=t.audioPreset)?void 0:l.priority)?d:"high",networkPriority:null!=(h=null==(u=t.audioPreset)?void 0:u.priority)?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new rb("cannot publish track when not connected");let y=()=>ah(this,void 0,void 0,function*(){var i,n;if(!this.engine.pcManager)throw new rb("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,p),this.emit(ec.LocalSenderCreated,e.sender,e),sb(e)&&(null!=t.degradationPreference||(t.degradationPreference=e.source===rW.Source.ScreenShare||e.constraints.height&&su(e.constraints.height)>=1080?"maintain-resolution":"balanced"),e.setDegradationPreference(t.degradationPreference)),p)if(r$()&&e.kind===rW.Kind.Audio){let t;for(let i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null==(i=p[0])?void 0:i.maxBitrate)?p[0].maxBitrate/1e3:0}
1)}else e.codec&&rX(e.codec)&&(null==(n=p[0])?void 0:n.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:b.cid,codec:e.codec,maxbr:p[0].maxBitrate/1e3});yield this.engine.negotiate()}),T=new Promise((t,i)=>ah(this,void 0,void 0,function*(){var n;try{m=yield this.engine.addTrack(b),t(m)}catch(t){e.sender&&(null==(n=this.engine.pcManager)?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),rB(e)),{error:t}))})),i(t)}}));if(this.enabledPublishVideoCodecs.length>0)m=(yield Promise.all([T,y()]))[0];else{let i;if((m=yield T).codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===rW.Kind.Video){let n=rF(i);n!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),rB(e)),{codec:n})),t.videoCodec=n,p=oh(e.source===rW.Source.ScreenShare,b.width,b.height,t))}yield y()}let C=new oq(e.kind,m,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(C.on(ed.CpuConstrained,e=>this.onTrackCpuConstrained(e,C)),C.options=t,e.sid=m.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:p,trackInfo:m})),sb(e)?e.startMonitor(this.engine.client):sy(e)&&e.startMonitor(),this.addTrackPublication(C),this.emit(ec.LocalTrackPublished,C),sy(e)&&m.audioFeatures.includes(t5.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();this.on(ec.LocalTrackSubscribed,t=>{if(t.trackSid===m.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),rB(e))),e.stopPreConnectBuffer()}}),t&&new Promise((n,a)=>ah(this,void 0,void 0,function*(){try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),rB(e)));let m=setTimeout(()=>{a(Error("agent not active within 10 seconds"))},1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),rB(e)));let f=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:C.trackSid,sampleRate:String(null!=(l=k.sampleRate)?l:"48000"),channels:String(null!=(d=k.channelCount)?d:"1")}});try{for(var r,s,o,c,l,d,u,h=!0,p=ap(t);!(r=(u=yield p.next()).done);h=!0)c=u.value,h=!1,yield f.write(c)}catch(e){s={error:e}}finally{try{!h&&!r&&(o=p.return)&&(yield o.call(p))}finally{if(s)throw s.error}}yield f.close(),n()}catch(e){a(e)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),rB(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),rB(e)),{error:t}))})}return C})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return ah(this,void 0,void 0,function*(){var n;let a;if(this.encryptionType!==is.NONE)return;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(a=t)}),!a)throw new rv("track is not published");if(!sb(e))throw new rv("track is not a video track");let r=Object.assign(Object.assign({},null==(n=this.roomOptions)?void 0:n.publishDefaults),i),s=function(e,t,i){var n,a,r,s;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&ao.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;let o=e.mediaStreamTrack.getSettings(),c=null!=(n=o.width)?n:null==(a=e.dimensions)?void 0:a.width,l=null!=(r=o.height)?r:null==(s=e.dimensions)?void 0:s.height;return e.source===rW.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),oh(e.source===rW.Source.ScreenShare,c,l,i)}(e,t,r);if(!s)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),rB(e)));let o=e.addSimulcastTrack(t,s);if(!o)return;let c=new i0({cid:o.mediaStreamTrack.id,type:rW.kindToProto(e.kind),muted:e.isMuted,source:rW.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=oy(c.width,c.height,s),!this.engine||this.engine.isClosed)throw new rb("cannot publish track when not connected");let l=()=>ah(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,r,s),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:s,trackInfo:d}))})}unpublishTrack(e,t){return ah(this,void 0,void 0,function*(){var i,n;if(sf(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),rB(e))),yield t)}let a=this.getPublicationForTrack(e),r=a?rB(a):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!a||!a.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(e=a.track).off(ed.Muted,this.onTrackMuted),e.off(ed.Unmuted,this.onTrackUnmuted),e.off(ed.Ended,this.handleTrackEnded),e.off(ed.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ed.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ed.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null==(n=null==(i=this.roomOptions)?void 0:i.stopLocalTrackOnUnpublish)||n),t?e.stop():e.stopMonitor();let s=!1,o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<eP.FAILED&&o)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",s=!0);if(this.engine.removeTrack(o)&&(s=!0),sb(e)){for(let[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(s=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:e}))}switch(this.trackPublications.delete(a.trackSid),a.kind){case rW.Kind.Audio:this.audioTrackPublications.delete(a.trackSid);break;case rW.Kind.Video:this.videoTrackPublications.delete(a.trackSid)}
1return this.emit(ec.LocalTrackUnpublished,a),a.setTrack(void 0),s&&(yield this.engine.negotiate()),a})}unpublishTracks(e){return ah(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return ah(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new ro((n,a)=>ah(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>ah(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),i&&!t.isMuted&&t.source!==rW.Source.ScreenShare&&t.source!==rW.Source.ScreenShareAudio&&(sy(t)||sb(t))&&!t.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),n()}catch(e){e instanceof Error?a(e):a(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return ah(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){let n=i.reliable?im.RELIABLE:im.LOSSY,a=i.destinationIdentities,r=i.topic,s=new ip({kind:n,value:{case:"user",value:new iy({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:r})}});yield t.engine.sendDataPacket(s,n)}()})}publishDtmf(e,t){return ah(this,void 0,void 0,function*(){let i=new ip({kind:im.RELIABLE,value:{case:"sipDtmf",value:new iT({code:e,digit:t})}});yield this.engine.sendDataPacket(i,im.RELIABLE)})}sendChatMessage(e,t){return ah(this,void 0,void 0,function*(){let i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new ip({value:{case:"chatMessage",value:new iE(Object.assign(Object.assign({},i),{timestamp:e4.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,im.RELIABLE),this.emit(ec.ChatMessage,i),i})}editChatMessage(e,t){return ah(this,void 0,void 0,function*(){let i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new ip({value:{case:"chatMessage",value:new iE(Object.assign(Object.assign({},i),{timestamp:e4.parse(i.timestamp),editTimestamp:e4.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,im.RELIABLE),this.emit(ec.ChatMessage,i),i})}sendText(e,t){return ah(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return ah(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return ah(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return ah(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:n,responseTimeout:a=15e3}=e;return new ro((e,r)=>ah(this,void 0,void 0,function*(){var s,o,c,l;if(s5(n)>15360)return void r(s6.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null==(o=null==(s=this.engine.latestJoinResponse)?void 0:s.serverInfo)?void 0:o.version)&&0>st(null==(l=null==(c=this.engine.latestJoinResponse)?void 0:c.serverInfo)?void 0:l.version,"1.8.0"))return void r(s6.builtIn("UNSUPPORTED_SERVER"));let d=Math.max(a,8e3),u=crypto.randomUUID();yield this.publishRpcRequest(t,u,i,n,d);let h=setTimeout(()=>{this.pendingAcks.delete(u),r(s6.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(u),clearTimeout(p)},7e3);this.pendingAcks.set(u,{resolve:()=>{clearTimeout(h)},participantIdentity:t});let p=setTimeout(()=>{this.pendingResponses.delete(u),r(s6.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(u,{resolve:(t,i)=>{clearTimeout(p),this.pendingAcks.has(u)&&(this.log.warn("RPC response received before ack",u),this.pendingAcks.delete(u),clearTimeout(h)),i?r(i):e(null!=t?t:"")},participantIdentity:t})}))}
1registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){let n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,a){return ah(this,void 0,void 0,function*(){let r=new ip({destinationIdentities:[e],kind:im.RELIABLE,value:{case:"rpcRequest",value:new iw({id:t,method:i,payload:n,responseTimeoutMs:a,version:1})}});yield this.engine.sendDataPacket(r,im.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,s6.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,i;let n=this.trackPublications.get(e.sid);if(n){let a=n.isMuted||null!=(i=null==(t=n.track)?void 0:t.isUpstreamPaused)&&i;a!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),rB(n)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(e.sid,a))}}),!0)}setActiveAgent(e){var t,i,n,a;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null==(i=null==(t=this.activeAgentFuture)?void 0:t.resolve)||i.call(t,e):null==(a=null==(n=this.activeAgentFuture)?void 0:n.reject)||a.call(n,Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new sd),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{let n=i.track;n&&(e instanceof MediaStreamTrack?(sy(n)||sb(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return ah(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield rz(20)}})}}class oK extends oB{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(ed.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let n=new nr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new i_({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ed.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?oB.SubscriptionStatus.Unsubscribed:super.isSubscribed?oB.SubscriptionStatus.Subscribed:oB.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?oB.PermissionStatus.Allowed:oB.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&!e!==this.requestedDisabled&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null==(t=this.requestedVideoDimensions)?void 0:t.width)!==e.width||(null==(i=this.requestedVideoDimensions)?void 0:i.height)!==e.height)&&(sC(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&sC(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!=(e=this.requestedMaxQuality)?e:ep.HIGH}setTrack(e){let t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(ed.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(ed.VisibilityChanged,this.handleVisibilityChange),n.off(ed.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit
1(ed.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ed.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ed.VisibilityChanged,this.handleVisibilityChange),e.on(ed.Ended,this.handleEnded),this.emit(ed.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(ed.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?ed.Muted:ed.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(ed.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ed.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return sC(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new nc({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===rW.Kind.Video){let a=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(a)rV(this.videoDimensionsAdaptiveStream,a)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),a=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){var t,i,n;let e=(t=this.trackInfo,i=this.requestedMaxQuality,null==(n=t.layers)?void 0:n.find(e=>e.quality===i));e&&rV(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),a=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),a=this.videoDimensionsAdaptiveStream;a?(e.width=Math.ceil(a.width),e.height=Math.ceil(a.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:ep.HIGH})),e.quality=ep.HIGH)}this.emit(ed.UpdateSettings,e)}}class oJ extends oW{static fromParticipantInfo(e,t,i){return new oJ(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,a,r,s){let o=arguments.length>7&&void 0!==arguments[7]?arguments[7]:ia.STANDARD;super(t,i||"",n,a,r,s,o),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(ed.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),rB(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(ed.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(ed.SubscriptionPermissionChanged,t=>{this.emit(ec.TrackSubscriptionPermissionChanged,e,t)}),e.on(ed.SubscriptionStatusChanged,t=>{this.emit(ec.TrackSubscriptionStatusChanged,e,t)}),e.on(ed.Subscribed,t=>{this.emit(ec.TrackSubscribed,t,e)}),e.on(ed.Unsubscribed,t=>{this.emit(ec.TrackUnsubscribed,t,e)}),e.on(ed.SubscriptionFailed,t=>{this.emit(ec.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rW.Source.Microphone;this.volumeMap.set(t,e);let i=this.getTrackPublication(t);
1i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rW.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,a,r){let s,o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(t=>{o||e.kind!==t.kind.toString()||(o=t)}),!o){if(0===r){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(ec.TrackSubscriptionFailed,t);return}void 0===r&&(r=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,a,r-1)},150);return}if("ended"===e.readyState){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),rB(o))),this.emit(ec.TrackSubscriptionFailed,t);return}return(s="video"===e.kind?new oL(e,t,n,a):new oN(e,t,n,this.audioContext,this.audioOutput)).source=o.source,s.isMuted=o.isMuted,s.setMediaStream(i),s.start(),o.setTrack(s),this.volumeMap.has(o.source)&&sT(s)&&sv(s)&&s.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,a;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{let t=rW.kindFromProto(e.type);if(!t)return;(r=new oK(t,e,null==(n=this.signalClient.connectOptions)?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null==(a=this.loggerOptions)?void 0:a.loggerName})).updateInfo(e),i.set(e.sid,r);let s=Array.from(this.trackPublications.values()).find(e=>e.source===(null==r?void 0:r.source));s&&r.source!==rW.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:rB(s),newTrack:rB(r)})),this.addTrackPublication(r)}t.set(e.sid,r)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),rB(e))),this.unpublishTrack(e.trackSid,!0))}
1),i.forEach(e=>{this.emit(ec.TrackPublished,e)}),!0}unpublishTrack(e,t){let i=this.trackPublications.get(e);if(!i)return;let{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case rW.Kind.Audio:this.audioTrackPublications.delete(e);break;case rW.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(ec.TrackUnpublished,i)}setAudioOutput(e){return ah(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(i=>{var n;sv(i.track)&&sT(i.track)&&t.push(i.track.setSinkId(null!=(n=e.deviceId)?n:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}(V=e_||(e_={})).Disconnected="disconnected",V.Connecting="connecting",V.Connected="connected",V.Reconnecting="reconnecting",V.SignalReconnecting="signalReconnecting";class oz extends ag.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,i,n,a,r;if(super(),t=this,this.state=e_.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ao,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,i)=>ah(this,void 0,void 0,function*(){var n;if(!(!("u"<typeof RTCPeerConnection)&&(rQ()||rY())))if(r9())throw Error("WebRTC isn't detected, have you called registerGlobals?");else throw Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");let a=yield this.disconnectLock.lock();if(this.state===e_.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),a(),Promise.resolve();if(this.connectFuture)return a(),this.connectFuture.promise;this.setAndEmitConnectionState(e_.Connecting),(null==(n=this.regionUrlProvider)?void 0:n.getServerUrl().toString())!==sS(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),r6(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new s9(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null==(t=this.regionUrlProvider)||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));let r=(n,s,o)=>ah(this,void 0,void 0,function*(){var c,l;this.abortController&&this.abortController.abort();let d=new AbortController;this.abortController=d,null==a||a();try{if(yield s_.getInstance().getBackOffPromise(e),d.signal.aborted)throw rg.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=o?o:e,t,i,d),this.abortController=void 0,n()}catch(t){if(this.regionUrlProvider&&t instanceof rg&&t.reason!==ea.Cancelled&&t.reason!==ea.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null==(c=this.abortController)?void 0:c.signal)}catch(e){if(e instanceof rg&&(401===e.status||e.reason===ea.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),s(e);return}}[ea.InternalError,ea.ServerUnreachable,ea.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),s_.getInstance().addFailedConnectionAttempt(e)),!i||(null==(l=this.abortController)?void 0:l.signal.aborted)?(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,sp(t)),s(t)):(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(),yield r(n,s,i))}else{let e=t4.UNKNOWN_REASON;t instanceof rg&&(e=sp(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),s(t)}}}),s=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new sd((e,t)=>{r(e,t,s)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,a,r)=>ah(this,void 0,void 0,function*(){var s,o,c;let l=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof a.adaptiveStream||a.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.signal,!a.singlePeerConnection),d=l.serverInfo;if(d||(d={version:l.serverVersion,region:l.serverRegion}),this.serverInfo=d,this.log.debug("connected to Livekit Server ".concat(Object.entries(d).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", ")),{room:null==(s=l.room)?void 0:s.name,roomSid:null==(o=l.room)?void 0:o.sid,identity:null==(c=l.participant)?void 0:c.identity}),!d.version)throw new rk("unknown server version");return"0.15.1"===d.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),a.dynacast=!1),l}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>ah(this,void 0,void 0,function*(){var a,r;this.state===e_.Reconnecting||this.isResuming||(null==(a=this.engine)?void 0:a.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null==(r=this.regionUrlProvider)?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},s3),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit
1(eo.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();let e=n.signal.aborted?rg.cancelled("Signal connection aborted"):rg.serverUnreachable("could not establish signal connection");throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof rg&&(e.reason=t.reason,e.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),rg.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}r4()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),r4()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(e_.Connected),this.emit(eo.Connected),s_.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return ah(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n,a;let r=yield e.disconnectLock.lock();try{if(e.state===e_.Disconnected)return void e.log.debug("already disconnected",e.logContext);if(e.log.info("disconnect from room",Object.assign({},e.logContext)),e.state===e_.Connecting||e.state===e_.Reconnecting||e.isResuming){let t="Abort connection attempt due to user initiated disconnect";e.log.warn(t,e.logContext),null==(i=e.abortController)||i.abort(t),null==(a=null==(n=e.connectFuture)?void 0:n.reject)||a.call(n,rg.cancelled("Client initiated disconnect")),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,t4.CLIENT_INITIATED),e.engine=void 0}finally{r()}}()})},this.onPageLeave=()=>ah(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>ah(this,void 0,void 0,function*(){let e=[],t=rl();if(t&&"iOS"===t.os){let t="livekit-dummy-audio-el",i=document.getElementById(t);if(!i){(i=document.createElement("audio")).id=t,i.autoplay=!0,i.hidden=!0;let e=sl();e.enabled=!0;let n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(i),this.once(eo.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}
1this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>ah(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null==(i=t.track)||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{for(let e of(this.clearConnectionReconcile(),this.isResuming=!1,this.remoteParticipants.values()))this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(e_.Reconnecting)&&this.emit(eo.Reconnecting)},this.handleSignalRestarted=e=>ah(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(e_.Connected),this.emit(eo.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!=(t=this.sidToIdentity.get(e.sid))?t:"");let i=this.remoteParticipants.get(e.identity);e.state===ii.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{let t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEac
1h(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(eo.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});let i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(eo.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;let n=rW.streamStateFromProto(e.state);i.track.setStreamState(n),n!==i.track.streamState&&(t.emit(ec.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(eo.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let i=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(i,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(i,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(i,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(i,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,i);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i,n)=>{this.emit(eo.DataReceived,t.payload,e,i,t.topic,n),null==e||e.emit(ec.DataReceived,t.payload,i,n)},this.handleSipDtmf=(e,t)=>{this.emit(eo.SipDTMFReceived,t,e),null==e||e.emit(ec.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{var i;let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),a=null==n?void 0:n.trackPublications.get(t.trackId),r=(i=this.transcriptionReceivedTimes,t.segments.map(e=>{var t;let{id:n,text:a,language:r,startTime:s,endTime:o,final:c}=e,l=null!=(t=i.get(n))?t:Date.now(),d=Date.now();return c?i.delete(n):i.set(n,l),{id:n,text:a,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:d}}));null==a||a.emit(ed.TranscriptionReceived,r),null==n||n.emit(ec.TranscriptionReceived,r,a),this.emit(eo.TranscriptionReceived,r,n,a)},this.handleChatMessage=(e,t)=>{let i=function(e){let{id:t,timestamp:i,message:n,editTimestamp:a}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:a?Number.parseInt(a.toString()):void 0,message:n}}(t);this.emit(eo.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(eo.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(eo.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(eo.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(eo.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit
1(eo.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>ah(this,void 0,void 0,function*(){var e;(null==(e=rl())?void 0:e.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(eo.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(eo.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(eo.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(eo.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(eo.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(eo.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(eo.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(eo.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null==(t=null==e?void 0:e.onPublish)||t.call(e,this)},this.onLocalTrackPublished=e=>ah(this,void 0,void 0,function*(){var t,i,n,a,r,s;null==(t=e.track)||t.on(ed.TrackProcessorUpdate,this.onTrackProcessorUpdate),null==(i=e.track)||i.on(ed.Restarted,this.onLocalTrackRestarted),null==(r=null==(a=null==(n=e.track)?void 0:n.getProcessor())?void 0:a.onPublish)||r.call(a,this),this.emit(eo.LocalTrackPublished,e,this.localParticipant),sy(e.track)&&(yield e.track.checkForSilence())&&this.emit(eo.LocalAudioSilenceDetected,e);let o=yield null==(s=e.track)?void 0:s.getDeviceId(!1),c=rj(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit(eo.ActiveDeviceChanged,c,o))}),this.onLocalTrackUnpublished=e=>{var t,i;null==(t=e.track)||t.off(ed.TrackProcessorUpdate,this.onTrackProcessorUpdate),null==(i=e.track)||i.off(ed.Restarted,this.onLocalTrackRestarted),this.emit(eo.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>ah(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),i=rj(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(eo.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(eo.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(eo.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(eo.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(eo.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},s2),e),this.log=ac(null!=(i=this.options.loggerName)?i:ee.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},s0),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},s1),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},s$),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new o_,this.outgoingDataStreamManager=new ox(this.engine,this.log),this.disconnectLock=new eF,this.localParticipant=new oG("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",su(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",su(this.options.audioCaptureDefaults.deviceId)),(null==(n=this.options.audioOutput)?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",su(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),r4()){const e=new AbortController;null==(r=null==(a=navigator.mediaDevices)?void 0:a.addEventListener)||r.call(a,"devicechange",this.handleDeviceChange,{signal:e.signal}),oz.cleanupRegistry&&oz.cleanupRegistry.register(this,()=>{e.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}
1registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return ah(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;let t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new sI(i,t),this.e2eeManager.on(ef.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(eo.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(ef.EncryptionError,(e,t)=>{let i=t?this.getParticipantByIdentity(t):void 0;this.emit(eo.EncryptionError,e,i)}),null==(e=this.e2eeManager)||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null==(e=this.roomInfo)?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.activeRecording)&&t}getSid(){return this.state===e_.Disconnected?ro.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?ro.resolve(this.roomInfo.sid):new ro((e,t)=>{let i=t=>{""!==t.sid&&(this.engine.off(el.RoomUpdate,i),e(t.sid))};this.engine.on(el.RoomUpdate,i),this.once(eo.Disconnected,()=>{this.engine.off(el.RoomUpdate,i),t(new rb("Room disconnected before room server id was available"))})})}get name(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.name)?t:""}get metadata(){var e;return null==(e=this.roomInfo)?void 0:e.metadata}get numParticipants(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.numParticipants)?t:0}get numPublishers(){var e,t;return null!=(t=null==(e=this.roomInfo)?void 0:e.numPublishers)?t:0}maybeCreateEngine(){(!this.engine||this.engine.isClosed)&&(this.engine=new oE(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(el.ParticipantUpdate,this.handleParticipantUpdates).on(el.RoomUpdate,this.handleRoomUpdate).on(el.SpeakersChanged,this.handleSpeakersChanged).on(el.StreamStateChanged,this.handleStreamStateUpdate).on(el.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(el.SubscriptionError,this.handleSubscriptionError).on(el.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(el.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(el.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(el.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(el.DataPacketReceived,this.handleDataPacket).on(el.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(e_.SignalReconnecting)&&this.emit(eo.SignalReconnecting)}).on(el.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(e_.Connected)&&this.emit(eo.Reconnected)}).on(el.SignalResumed,()=>{this.bufferedEvents=[],(this.state===e_.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(el.Restarting,this.handleRestarting).on(el.SignalRestarted,this.handleSignalRestarted).on(el.Offline,()=>{this.setAndEmitConnectionState(e_.Reconnecting)&&this.emit(eo.Reconnecting)}).on(el.DCBufferStatusChanged,(e,t)=>{this.emit(eo.DCBufferStatusChanged,e,t)}).on(el.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});t?(this.localParticipant.emit(ec.LocalTrackSubscribed,t),this.emitWhenConnected(eo.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)}).on(el.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEac
1h((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(eo.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return sD.getInstance().getDevices(e,t)}prepareConnection(e,t){return ah(this,void 0,void 0,function*(){if(this.state===e_.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(r6(new URL(e))&&t){this.regionUrlProvider=new s9(e,t);let i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===e_.Disconnected&&(this.regionUrl=i,yield fetch(sh(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(sh(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return ah(this,void 0,void 0,function*(){let i,n=()=>ah(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new nx({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new nx({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new nx({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new nx({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>ah(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new nx({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>ah(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new nx({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new nx({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>ah(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new nu({reason:t4.CLIENT_INITIATED,action:nh.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw Error("subscriber-bandwidth requires a number as argument");i=new nx({scenario:{case:"subscriberBandwidth",value:sg(t)}});break;case"leave-full-reconnect":i=new nx({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return ah(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];return function*(){var a,r,s,o,c,l;let d=!0,u=!1,h=n?{exact:t}:t;if("audioinput"===e){u=0===i.localParticipant.audioTrackPublications.size;let t=null!=(a=i.getActiveDevice(e))?a:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=h;let n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===rW.Source.Microphone);try{d=(yield Promise.all(n.map(e=>{var t;return null==(t=e.audioTrack)?void 0:t.setDeviceId(h)}))).every(e=>!0===e)}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}let r=n.some(e=>{var t,i;return null!=(i=null==(t=e.track)?void 0:t.isMuted)&&i});d&&r&&(u=!0)}else if("videoinput"===e){u=0===i.localParticipant.videoTrackPublications.size;let t=null!=(r=i.getActiveDevice(e))?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=h;let n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===rW.Source.Camera);try{d=(yield Promise.all(n.map(e=>{var t;return null==(t=e.videoTrack)?void 0:t.setDeviceId(h)}
1))).every(e=>!0===e)}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}let a=n.some(e=>{var t,i;return null!=(i=null==(t=e.track)?void 0:t.isMuted)&&i});d&&a&&(u=!0)}else if("audiooutput"===e){if(u=!0,!rZ()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!=(s=yield sD.getInstance().normalizeDeviceId("audiooutput",t))?s:""),null!=(l=i.options).audioOutput||(l.audioOutput={});let n=null!=(o=i.getActiveDevice(e))?o:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null==(c=i.audioContext)||c.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return u&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(eo.ActiveDeviceChanged,e,t)),d}()})}setupLocalParticipantEvents(){this.localParticipant.on(ec.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ec.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ec.AttributesChanged,this.onLocalAttributesChanged).on(ec.TrackMuted,this.onLocalTrackMuted).on(ec.TrackUnmuted,this.onLocalTrackUnmuted).on(ec.LocalTrackPublished,this.onLocalTrackPublished).on(ec.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ec.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ec.MediaDevicesError,this.onMediaDevicesError).on(ec.AudioStreamAcquired,this.startAudio).on(ec.ChatMessage,this.onLocalChatMessageSent).on(ec.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null==(e=this.engine)||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){var n;let a,r;if(this.state===e_.Connecting||this.state===e_.Reconnecting){let n=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,i),a()},a=()=>{this.off(eo.Reconnected,n),this.off(eo.Connected,n),this.off(eo.Disconnected,a)};this.once(eo.Reconnected,n),this.once(eo.Connected,n),this.once(eo.Disconnected,a);return}if(this.state===e_.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);let s=(r=(n=t.id).split("|")).length>1?[r[0],n.substr(r[0].length+1)]:[n,""],o=s[0],c=s[1],l=e.id;if(c&&c.startsWith("TR")&&(l=c),o===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);let d=Array.from(this.remoteParticipants.values()).find(e=>e.sid===o);if(!d)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o),this.logContext);if(!l.startsWith("TR")){let e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(o),this.logContext);l=e}l.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(o,", streamId: ").concat(c,", trackId: ").concat(l),Object.assign(Object.assign({},this.logContext),{rpID:o,streamId:c,trackId:l})),this.options.adaptiveStream&&(a="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});let u=d.addSubscribedMediaTrack(e,l,t,i,a);(null==u?void 0:u.isEncrypted)&&!this.e2eeManager&&this.emit(eo.EncryptionError,Error("Encrypted ".concat(u.source," track received from participant ").concat(d.sid,", but room does not have encryption enabled!")))}handleDisconnect(){var e,t;let i=!(arguments.length>0)||void 0===arguments[0]||arguments[0],n=arguments.length>1?arguments[1]:void 0;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==e_.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();
1try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(e=>{var t,n,a;e.track&&this.localParticipant.unpublishTrack(e.track,i),i?(null==(t=e.track)||t.detach(),null==(n=e.track)||n.stop()):null==(a=e.track)||a.stopMonitor()}),this.localParticipant.off(ec.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ec.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ec.AttributesChanged,this.onLocalAttributesChanged).off(ec.TrackMuted,this.onLocalTrackMuted).off(ec.TrackUnmuted,this.onLocalTrackUnmuted).off(ec.LocalTrackPublished,this.onLocalTrackPublished).off(ec.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ec.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ec.MediaDevicesError,this.onMediaDevicesError).off(ec.AudioStreamAcquired,this.startAudio).off(ec.ChatMessage,this.onLocalChatMessageSent).off(ec.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),r4()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null==(t=null==(e=navigator.mediaDevices)?void 0:e.removeEventListener)||t.call(e,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e_.Disconnected),this.emit(eo.Disconnected,n)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(eo.ParticipantDisconnected,t),t.setDisconnected(),null==(i=this.localParticipant)||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,n,a,r){return ah(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==r)return void(yield this.engine.publishRpcResponse(e,t,null,s6.builtIn("UNSUPPORTED_VERSION")));let s=this.rpcHandlers.get(i);if(!s)return void(yield this.engine.publishRpcResponse(e,t,null,s6.builtIn("UNSUPPORTED_METHOD")));let o=null,c=null;try{let r=yield s({requestId:t,callerIdentity:e,payload:n,responseTimeout:a});s5(r)>15360?(o=s6.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=r}catch(e){e instanceof s6?o=e:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),o=s6.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,o)})}selectDefaultDevices(){return ah(this,void 0,void 0,function*(){var e,t,i;let n=sD.getInstance().previousDevices,a=yield sD.getInstance().getDevices(void 0,!1),r=rl();if((null==r?void 0:r.name)==="Chrome"&&"iOS"!==r.os)for(let e of a){let t=n.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(eo.ActiveDeviceChanged,e.kind,e.deviceId)}for(let r of["audiooutput","audioinput","videoinput"]){let s="audioinput"===r?rW.Source.Microphone:"videoinput"===r?rW.Source.Camera:rW.Source.Unknown,o=this.localParticipant.getTrackPublication(s);if(o&&(null==(e=o.track)?void 0:e.isUserProvided))continue;let c=a.filter(e=>e.kind===r),l=this.getActiveDevice(r);if(l===(null==(t=n.filter(e=>e.kind===r)[0])?void 0:t.deviceId)&&c.length>0&&(null==(i=c[0])?void 0:i.deviceId)!==l){yield this.switchActiveDevice(r,c[0].deviceId);continue}("audioinput"!==r||r2())&&"videoinput"!==r&&(!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(r))||"audiooutput"===r&&r2()||(yield this.switchActiveDevice(r,c[0].deviceId)))}})}acquireAudioContext(){return ah(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!=(e=rU())?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEac
1h(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),rz(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}let i=(null==(t=this.audioContext)?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(eo.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?oJ.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new oJ(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null==(i=this.options.audioOutput)?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}let i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(eo.ParticipantConnected,i),i.on(ec.TrackPublished,e=>{this.emitWhenConnected(eo.TrackPublished,e,i)}).on(ec.TrackSubscribed,(e,t)=>{e.kind===rW.Kind.Audio?(e.on(ed.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(ed.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===rW.Kind.Video&&(e.on(ed.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(ed.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(eo.TrackSubscribed,e,t,i)}).on(ec.TrackUnpublished,e=>{this.emit(eo.TrackUnpublished,e,i)}).on(ec.TrackUnsubscribed,(e,t)=>{this.emit(eo.TrackUnsubscribed,e,t,i)}).on(ec.TrackMuted,e=>{this.emitWhenConnected(eo.TrackMuted,e,i)}).on(ec.TrackUnmuted,e=>{this.emitWhenConnected(eo.TrackUnmuted,e,i)}).on(ec.ParticipantMetadataChanged,e=>{this.emitWhenConnected(eo.ParticipantMetadataChanged,e,i)}).on(ec.ParticipantNameChanged,e=>{this.emitWhenConnected(eo.ParticipantNameChanged,e,i)}).on(ec.AttributesChanged,e=>{this.emitWhenConnected(eo.ParticipantAttributesChanged,e,i)}).on(ec.ConnectionQualityChanged,e=>{this.emitWhenConnected(eo.ConnectionQualityChanged,e,i)}).on(ec.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(eo.ParticipantPermissionsChanged,e,i)}).on(ec.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(eo.TrackSubscriptionStatusChanged,e,t,i)}).on(ec.TrackSubscriptionFailed,(e,t)=>{this.emit(eo.TrackSubscriptionFailed,e,i,t)}).on(ec.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(eo.TrackSubscriptionPermissionChanged,e,t,i)}).on(ec.Active,()=>{this.emitWhenConnected(eo.ParticipantActive,i),i.kind===ia.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(let t of this.remoteParticipants.values())for(let i of t.videoTrackPublications.values()){var e;i.isSubscribed&&(e=i)&&!e.isLocal&&i.emitTrackUpdate()}}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=rw.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t4.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&rw.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit
1(eo.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===e_.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===e_.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return ah(this,void 0,void 0,function*(){var t,i,n,a;let r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new t8({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:e4.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new it({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(eo.SignalConnected),this.emit(eo.Connected),this.setAndEmitConnectionState(e_.Connected),r.video){let e=new oq(rW.Kind.Video,new ic({source:t0.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:t$.AUDIO,name:"video-dummy"}),new ov(r.useRealTracks&&(null==(t=window.navigator.mediaDevices)?void 0:t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:sc(160*(null!=(i=s.aspectRatios[0])?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(ec.LocalTrackPublished,e)}if(r.audio){let e=new oq(rW.Kind.Audio,new ic({source:t0.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:t$.AUDIO}),new or(r.useRealTracks&&(null==(n=navigator.mediaDevices)?void 0:n.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:sl(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(ec.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new it({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:ii.ACTIVE,tracks:[],joinedAt:e4.parse(Date.now())}),i=this.getOrCreateParticipant(t.identity,t);if(s.video){let n=sc(160*(null!=(a=s.aspectRatios[e%s.aspectRatios.length])?a:1),160,!1,!0),r=new ic({source:t0.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:t$.AUDIO});i.addSubscribedMediaTrack(n,r.sid,new MediaStream([n]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}if(s.audio){let e=sl(),n=new ic({source:t0.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:t$.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==eo.ActiveSpeakersChanged&&e!==eo.TranscriptionReceived){let t=(function e(t){return t.map(t=>{if(t)return Array.isArray(t)?e(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t})})(i).filter(e=>void 0!==e);(e===eo.TrackSubscribed||e===eo.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}oz.cleanupRegistry="u">typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),(H=eO||(eO={}))[H.IDLE=0]="IDLE",H[H.RUNNING=1]="RUNNING",H[H.SKIPPED=2]="SKIPPED",H[H.SUCCESS=3]="SUCCESS",H[H.FAILED=4]="FAILED";class oQ extends ag.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=eO.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new oz(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return ah(this,void 0,void 0,function*(){if(this.status!==eO.IDLE)throw Error("check is running already");this.setStatus(eO.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise(e=>setTimeout(e,500)),this.status!==eO.SKIPPED&&this.setStatus(this.isSuccess()?eO.SUCCESS:eO.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>"error"===e.level)}connect(e){return ah(this,void 0,void 0,function*(){return this.room.state===e_.Connected||(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions)),this.room})}disconnect(){return ah(this,void 0,void 0,function*(){this.room&&this.room.state!==e_.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(eO.SKIPPED)}switchProtocol(e){return ah(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(eo.Reconnecting,()=>{t=!0}),this.room.once(eo.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(e=>setTimeout(e,1e3)),!t)return;let n=Date.now()+1e4;for(;Date.now()<n;){if(i)return;yield rz(100)}throw Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}
1),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null==(e=this.room)?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function oY(e,t,i){var n;return(t="symbol"==typeof(n=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"))?n:n+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}ag.EventEmitter,new TextEncoder,new TextDecoder;class oX extends Error{constructor(e,t){var i;super(e,t),oY(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null==(i=Error.captureStackTrace)||i.call(Error,this,this.constructor)}}oY(oX,"code","ERR_JOSE_GENERIC");class oZ extends oX{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),oY(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),oY(this,"claim",void 0),oY(this,"reason",void 0),oY(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}}oY(oZ,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class o$ extends oX{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:n,payload:t}}),oY(this,"code","ERR_JWT_EXPIRED"),oY(this,"claim",void 0),oY(this,"reason",void 0),oY(this,"payload",void 0),this.claim=i,this.reason=n,this.payload=t}}oY(o$,"code","ERR_JWT_EXPIRED");class o0 extends oX{constructor(){super(...arguments),oY(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}oY(o0,"code","ERR_JOSE_ALG_NOT_ALLOWED");class o1 extends oX{constructor(){super(...arguments),oY(this,"code","ERR_JOSE_NOT_SUPPORTED")}}oY(o1,"code","ERR_JOSE_NOT_SUPPORTED");class o2 extends oX{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),oY(this,"code","ERR_JWE_DECRYPTION_FAILED")}}oY(o2,"code","ERR_JWE_DECRYPTION_FAILED");class o3 extends oX{constructor(){super(...arguments),oY(this,"code","ERR_JWE_INVALID")}}oY(o3,"code","ERR_JWE_INVALID");class o4 extends oX{constructor(){super(...arguments),oY(this,"code","ERR_JWS_INVALID")}}oY(o4,"code","ERR_JWS_INVALID");class o9 extends oX{constructor(){super(...arguments),oY(this,"code","ERR_JWT_INVALID")}}oY(o9,"code","ERR_JWT_INVALID");class o6 extends oX{constructor(){super(...arguments),oY(this,"code","ERR_JWK_INVALID")}}oY(o6,"code","ERR_JWK_INVALID");class o5 extends oX{constructor(){super(...arguments),oY(this,"code","ERR_JWKS_INVALID")}}oY(o5,"code","ERR_JWKS_INVALID");class o8 extends oX{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),oY(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}
1oY(o8,"code","ERR_JWKS_NO_MATCHING_KEY");class o7 extends oX{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),oY(this,Symbol.asyncIterator,void 0),oY(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}oY(o7,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class ce extends oX{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),oY(this,"code","ERR_JWKS_TIMEOUT")}}oY(ce,"code","ERR_JWKS_TIMEOUT");class ct extends oX{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),oY(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}oY(ct,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED"),(W=eD||(eD={}))[W.Reserved=0]="Reserved",W[W.TooLarge=1]="TooLarge",(G=eM||(eM={}))[G.TooShort=0]="TooShort",G[G.HeaderOverrun=1]="HeaderOverrun",G[G.MissingExtWords=2]="MissingExtWords",G[G.UnsupportedVersion=3]="UnsupportedVersion",G[G.InvalidHandle=4]="InvalidHandle",G[G.MalformedExt=5]="MalformedExt",(K=ex||(ex={}))[K.TooSmallForHeader=0]="TooSmallForHeader",K[K.TooSmallForPayload=1]="TooSmallForPayload";class ci{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),i=new DataView(t),n=this.toBinaryInto(i);if(e!==n)throw Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(n," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}(J=eA||(eA={}))[J.UserTimestamp=2]="UserTimestamp",J[J.E2ee=1]="E2ee";class cn extends ci{}class ca extends cn{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 4+ca.lengthBytes}toBinaryInto(e){let t=0;e.setUint16(t,ca.tag),t+=2;let i=ca.lengthBytes-1;e.setUint16(t,i),t+=2,e.setBigUint64(t,this.timestamp),t+=8;let n=this.toBinaryLengthBytes();if(t!==n)throw Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:ca.tag,lengthBytes:ca.lengthBytes,timestamp:this.timestamp}}}ca.tag=eA.UserTimestamp,ca.lengthBytes=8;class cr extends cn{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 4+cr.lengthBytes}toBinaryInto(e){let t=0;e.setUint16(t,cr.tag),t+=2;let i=cr.lengthBytes-1;e.setUint16(t,i),t+=2,e.setUint8(t,this.keyIndex),t+=1;for(let i=0;i<this.iv.length;i+=1)e.setUint8(t,this.iv[i]),t+=1;let n=this.toBinaryLengthBytes();if(t!==n)throw Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:cr.tag,lengthBytes:cr.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}cr.tag=eA.E2ee,cr.lengthBytes=13,(z=eN||(eN={}))[z.Start=0]="Start",z[z.Inter=1]="Inter",z[z.Final=2]="Final",z[z.Single=3]="Single"}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.