obi-sdk 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -405,7 +405,7 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
405
405
  font-weight: 500;
406
406
  font-size: 14px;
407
407
  }
408
- `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",vs);var ys=Object.defineProperty,bs=Object.getOwnPropertyDescriptor,ks=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?bs(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&ys(t,i,r),r};class Ts extends oe{constructor(){super(),this.apiBaseUrl=En,this.apiKey="",this.position="bottom-right",this.user=null,this.state=Rn.READY,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.closeNavTimeoutRef=null,window.obiWidgetConfig&&(window.obiWidgetConfig.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),window.obiWidgetConfig.position&&(this.position=window.obiWidgetConfig.position),window.obiWidgetConfig.user&&(this.user=window.obiWidgetConfig.user))}connectedCallback(){super.connectedCallback(),window.obiWidgetConfig||(window.obiWidgetConfig={apiKey:this.apiKey||""}),this.apiKey&&(window.obiWidgetConfig.apiKey=this.apiKey),this.setAttribute("position",this.position)}disconnectedCallback(){super.disconnectedCallback(),null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null)}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout((()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null}),300)}handleItemSelect(e,t){"experiences"!==e?Ge([e,t]).with(["pause",!0],(()=>{this.activeSession?.pauseRecording()})).with(["pause",!1],(()=>{this.activeSession?.resumeRecording()})).with(["activate",!1],(()=>{this.activeSession?.disconnect()})).otherwise((()=>{})):this.showCourseModal=!0}async handleSessionStart(e){this.showCourseModal=!1,this.state=Rn.LOADING;try{const{ObiSession:t}=await Promise.resolve().then((()=>up)),i=new t({token:e,apiBaseUrl:this.apiBaseUrl});i.on("stateChanged",(e=>{this.state=e.newState})),i.on("volume",(e=>{this.volume=e})),i.on("error",(e=>{console.error("Session error:",e.error),this.state=Rn.ERROR,this.activeSession=null})),await i.connect(),this.activeSession=i}catch(t){console.error("Failed to connect to session:",t),this.state=Rn.ERROR}}render(){const e=Ge(this.state).with(Rn.LOADING,(()=>q`<obi-dot-loader></obi-dot-loader>`)).with(Rn.RESEARCHING,(()=>q`<obi-searching-loader></obi-searching-loader>`)).with(Ze.union(Rn.USER_SPEAKING,Rn.AGENT_SPEAKING),(()=>q`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`)).with(Rn.PAUSED,(()=>Fn)).otherwise((()=>Fn));return q`
408
+ `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",vs);var ys=Object.defineProperty,bs=Object.getOwnPropertyDescriptor,ks=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?bs(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&ys(t,i,r),r};class Ts extends oe{constructor(){super(),this.apiBaseUrl=En,this.apiKey="",this.position="bottom-right",this.user=null,this.state=Rn.READY,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.closeNavTimeoutRef=null,window.obiWidgetConfig&&(window.obiWidgetConfig.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),window.obiWidgetConfig.position&&(this.position=window.obiWidgetConfig.position),window.obiWidgetConfig.user&&(this.user=window.obiWidgetConfig.user))}connectedCallback(){super.connectedCallback(),window.obiWidgetConfig||(window.obiWidgetConfig={apiKey:this.apiKey||""}),this.apiKey&&(window.obiWidgetConfig.apiKey=this.apiKey),this.setAttribute("position",this.position)}disconnectedCallback(){super.disconnectedCallback(),null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null)}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout((()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null}),300)}handleItemSelect(e,t){"experiences"!==e?Ge([e,t]).with(["pause",!0],(()=>{this.activeSession?.pauseRecording()})).with(["pause",!1],(()=>{this.activeSession?.resumeRecording()})).with(["activate",!1],(()=>{this.activeSession?.disconnect()})).otherwise((()=>{})):this.showCourseModal=!0}async handleSessionStart(e){this.showCourseModal=!1,this.state=Rn.LOADING;try{const{ObiSession:t}=await Promise.resolve().then((()=>mp)),i=new t({token:e,apiBaseUrl:this.apiBaseUrl});i.on("stateChanged",(e=>{this.state=e.newState})),i.on("volume",(e=>{this.volume=e})),i.on("error",(e=>{console.error("Session error:",e.error),this.state=Rn.ERROR,this.activeSession=null})),await i.connect(),this.activeSession=i}catch(t){console.error("Failed to connect to session:",t),this.state=Rn.ERROR}}render(){const e=Ge(this.state).with(Rn.LOADING,(()=>q`<obi-dot-loader></obi-dot-loader>`)).with(Rn.RESEARCHING,(()=>q`<obi-searching-loader></obi-searching-loader>`)).with(Ze.union(Rn.USER_SPEAKING,Rn.AGENT_SPEAKING),(()=>q`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`)).with(Rn.PAUSED,(()=>Fn)).otherwise((()=>Fn));return q`
409
409
  <div
410
410
  class="widget-container ${this.state===Rn.USER_SPEAKING||this.state===Rn.AGENT_SPEAKING?"pulse":""} ${this.state!==Rn.READY||this.navVisible?"rounded":""} ${this.state===Rn.RESEARCHING?"researching":""} ${this.state===Rn.USER_SPEAKING?"user-speaking":""}"
411
411
  @mouseenter=${this.handleMouseEnter}
@@ -527,5 +527,5 @@ var e=function(e){"use strict";const t=globalThis,i=t.ShadowRoot&&(void 0===t.Sh
527
527
  .pulse {
528
528
  animation: pulse-shadow 2s ease-in-out infinite;
529
529
  }
530
- `,ks([ue({type:String})],Ts.prototype,"apiBaseUrl",2),ks([ue({type:String})],Ts.prototype,"apiKey",2),ks([ue({type:String})],Ts.prototype,"position",2),ks([ue({type:Object})],Ts.prototype,"user",2),ks([he()],Ts.prototype,"state",2),ks([he()],Ts.prototype,"showCourseModal",2),ks([he()],Ts.prototype,"isHovering",2),ks([he()],Ts.prototype,"navVisible",2),ks([he()],Ts.prototype,"activeSession",2),ks([he()],Ts.prototype,"volume",2),customElements.get("obi-widget")||customElements.define("obi-widget",Ts);const Cs="https://unpkg.com/obi-sdk";function ws(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var Es=Object.defineProperty,_s=(e,t,i)=>((e,t,i)=>t in e?Es(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Ps{constructor(){_s(this,"_locking"),_s(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function Rs(e,t){if(!e)throw new Error(t)}function xs(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function Is(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function Os(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const As=Symbol("@bufbuild/protobuf/enum-type");function Ns(e,t,i,n){e[As]=Ds(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function Ds(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const a of t){const e=Ms(a);r.push(e),n[a.name]=e,s[a.no]=e}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function Ms(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class Ls{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(n){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(n instanceof Error?n.message:String(n)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Us(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function js(e,t,i){for(let r=0;r<28;r+=7){const n=e>>>r,s=!(n>>>7==0&&0==t),a=255&(s?128|n:n);if(i.push(a),!s)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const Fs=4294967296;function Bs(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const a=Number(e.slice(t,r));s*=i,n=n*i+a,n>=Fs&&(s+=n/Fs|0,n%=Fs)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?qs(n,s):Vs(n,s)}function $s(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(Fs*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,a=2*n;const o=1e7;return s>=o&&(r+=Math.floor(s/o),s%=o),r>=o&&(a+=Math.floor(r/o),r%=o),a.toString()+Ks(r)+Ks(s)}function Vs(e,t){return{lo:0|e,hi:0|t}}function qs(e,t){return t=~t,e?e=1+~e:t+=1,Vs(e,t)}const Ks=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Zs(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 Hs(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let i=5;128&e&&i<10;i++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const zs=function(){const 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 process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new 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))}}const t=e=>Rs(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>Rs(/^[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),Bs(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),Bs(e)),dec:(e,t)=>function(e,t){let i=Vs(e,t);const n=2147483648&i.hi;n&&(i=qs(i.lo,i.hi));const s=$s(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>$s(e,t)}}();var Gs,Ws,Js,Qs,Ys,Xs;function er(e,t,i){if(t===i)return!0;if(e==Gs.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(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 Gs.UINT64:case Gs.FIXED64:case Gs.INT64:case Gs.SFIXED64:case Gs.SINT64:return t==i}return!1}function tr(e,t){switch(e){case Gs.BOOL:return!1;case Gs.UINT64:case Gs.FIXED64:case Gs.INT64:case Gs.SFIXED64:case Gs.SINT64:return 0==t?zs.zero:"0";case Gs.DOUBLE:case Gs.FLOAT:return 0;case Gs.BYTES:return new Uint8Array(0);case Gs.STRING:return"";default:return 0}}function ir(e,t){switch(e){case Gs.BOOL:return!1===t;case Gs.STRING:return""===t;case Gs.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(Ws=Gs||(Gs={}))[Ws.DOUBLE=1]="DOUBLE",Ws[Ws.FLOAT=2]="FLOAT",Ws[Ws.INT64=3]="INT64",Ws[Ws.UINT64=4]="UINT64",Ws[Ws.INT32=5]="INT32",Ws[Ws.FIXED64=6]="FIXED64",Ws[Ws.FIXED32=7]="FIXED32",Ws[Ws.BOOL=8]="BOOL",Ws[Ws.STRING=9]="STRING",Ws[Ws.BYTES=12]="BYTES",Ws[Ws.UINT32=13]="UINT32",Ws[Ws.SFIXED32=15]="SFIXED32",Ws[Ws.SFIXED64=16]="SFIXED64",Ws[Ws.SINT32=17]="SINT32",Ws[Ws.SINT64=18]="SINT64",(Qs=Js||(Js={}))[Qs.BIGINT=0]="BIGINT",Qs[Qs.STRING=1]="STRING",(Xs=Ys||(Ys={}))[Xs.Varint=0]="Varint",Xs[Xs.Bit64=1]="Bit64",Xs[Xs.LengthDelimited=2]="LengthDelimited",Xs[Xs.StartGroup=3]="StartGroup",Xs[Xs.EndGroup=4]="EndGroup",Xs[Xs.Bit32=5]="Bit32";class nr{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 n=0;n<this.chunks.length;n++)e+=this.chunks[n].length;let t=new Uint8Array(e),i=0;for(let n=0;n<this.chunks.length;n++)t.set(this.chunks[n],i),i+=this.chunks[n].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Is(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return xs(e),Zs(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Os(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){Is(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){xs(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return xs(e),Zs(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=zs.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=zs.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=zs.enc(e);return js(t.lo,t.hi,this.buf),this}sint64(e){let t=zs.enc(e),i=t.hi>>31;return js(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=zs.uEnc(e);return js(t.lo,t.hi,this.buf),this}}class sr{constructor(e,t){this.varint64=Us,this.uint32=Hs,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;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case Ys.Varint:for(;128&this.buf[this.pos++];);break;case Ys.Bit64:this.pos+=4;case Ys.Bit32:this.pos+=4;break;case Ys.LengthDelimited:let i=this.uint32();this.pos+=i;break;case Ys.StartGroup:for(;;){const[e,i]=this.tag();if(i===Ys.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return zs.dec(...this.varint64())}uint64(){return zs.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,zs.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 zs.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return zs.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 rr(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const 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 tr(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let ar="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),or=[];for(let hp=0;hp<ar.length;hp++)or[ar[hp].charCodeAt(0)]=hp;or["-".charCodeAt(0)]=ar.indexOf("+"),or["_".charCodeAt(0)]=ar.indexOf("/");const cr={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,a=0;for(let o=0;o<e.length;o++){if(i=or[e.charCodeAt(o)],void 0===i)switch(e[o]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:a=i,r=1;break;case 1:n[s++]=a<<2|(48&i)>>4,a=i,r=2;break;case 2:n[s++]=(15&a)<<4|(60&i)>>2,a=i,r=3;break;case 3:n[s++]=(3&a)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=ar[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=ar[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=ar[s|t>>6],i+=ar[63&t],n=0}return n&&(i+=ar[s],i+="=",1==n&&(i+="=")),i}};function dr(e,t,i){hr(t,e);const n=t.runtime.bin.makeReadOptions(i),s=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,a]=rr(t);for(const o of s)t.runtime.bin.readField(r,n.readerFactory(o.data),t.field,o.wireType,n);return a()}function lr(e,t,i,n){hr(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(ur(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const a=r.writerFactory();let 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,a,r);const c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function ur(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function hr(e,t){Rs(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function pr(e,t){const 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":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!ir(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function mr(e,t){const 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?tr(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function gr(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(Ls.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function fr(e,t){return gr(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}Gs.DOUBLE,Gs.FLOAT,Gs.INT64,Gs.UINT64,Gs.INT32,Gs.UINT32,Gs.BOOL,Gs.STRING,Gs.BYTES;const vr={ignoreUnknownFields:!1},yr={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};const br=Symbol(),kr=Symbol();function Tr(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 Sr(e,t,i,n,s){let r=i.localName;if(i.repeated){if(Rs("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Tr(t)));const o=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Tr(e)));switch(i.kind){case"message":o.push(i.T.fromJson(e,n));break;case"enum":const t=Er(i.T,e,n.ignoreUnknownFields,!0);t!==kr&&o.push(t);break;case"scalar":try{o.push(wr(i.T,e,i.L,!0))}catch(a){let t="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Tr(e));throw a instanceof Error&&a.message.length>0&&(t+=": ".concat(a.message)),new Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Tr(t)));const o=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let c;try{c=Cr(i.K,e)}catch(a){let e="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Tr(t));throw a instanceof Error&&a.message.length>0&&(e+=": ".concat(a.message)),new Error(e)}switch(i.V.kind){case"message":o[c]=i.V.T.fromJson(r,n);break;case"enum":const e=Er(i.V.T,r,n.ignoreUnknownFields,!0);e!==kr&&(o[c]=e);break;case"scalar":try{o[c]=wr(i.V.T,r,Js.BIGINT,!0)}catch(a){let e="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Tr(t));throw a instanceof Error&&a.message.length>0&&(e+=": ".concat(a.message)),new Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const o=i.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let c=e[r];gr(c)?c.fromJson(t,n):(e[r]=c=o.fromJson(t,n),o.fieldWrapper&&!i.oneof&&(e[r]=o.fieldWrapper.unwrapField(c)));break;case"enum":const d=Er(i.T,t,n.ignoreUnknownFields,!1);switch(d){case br:mr(i,e);break;case kr:break;default:e[r]=d}break;case"scalar":try{const n=wr(i.T,t,i.L,!1);n===br?mr(i,e):e[r]=n}catch(a){let e="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Tr(t));throw a instanceof Error&&a.message.length>0&&(e+=": ".concat(a.message)),new Error(e)}}}function Cr(e,t){if(e===Gs.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return wr(e,t,Js.BIGINT,!0).toString()}function wr(e,t,i,n){if(null===t)return n?tr(e,i):br;switch(e){case Gs.DOUBLE:case Gs.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==Gs.FLOAT&&Os(n),n;case Gs.INT32:case Gs.FIXED32:case Gs.SFIXED32:case Gs.SINT32:case Gs.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==Gs.UINT32||e==Gs.FIXED32?Is(r):xs(r),r;case Gs.INT64:case Gs.SFIXED64:case Gs.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=zs.parse(t);return i?a.toString():a;case Gs.FIXED64:case Gs.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=zs.uParse(t);return i?o.toString():o;case Gs.BOOL:if("boolean"!=typeof t)break;return t;case Gs.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(s){throw new Error("invalid UTF8")}return t;case Gs.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return cr.dec(t)}throw new Error}function Er(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:br;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return kr}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Tr(t)))}function _r(e){return!(!e.repeated&&"map"!=e.kind&&(e.oneof||"message"==e.kind||e.opt||e.req))}function Pr(e,t,i){if("map"==e.kind){Rs("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[i,r]of s)n[i.toString()]=xr(e.V.T,r);break;case"message":for(const[e,r]of s)n[e.toString()]=r.toJson(i);break;case"enum":const t=e.V.T;for(const[e,r]of s)n[e.toString()]=Rr(t,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){Rs(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(xr(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(Rr(e.T,t[s],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 xr(e.T,t);case"enum":return Rr(e.T,t,i.enumAsInteger);case"message":return fr(e.T,t).toJson(i)}}function Rr(e,t,i){var n;if(Rs("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function xr(e,t){switch(e){case Gs.INT32:case Gs.SFIXED32:case Gs.SINT32:case Gs.FIXED32:case Gs.UINT32:return Rs("number"==typeof t),t;case Gs.FLOAT:case Gs.DOUBLE:return Rs("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case Gs.STRING:return Rs("string"==typeof t),t;case Gs.BOOL:return Rs("boolean"==typeof t),t;case Gs.UINT64:case Gs.FIXED64:case Gs.INT64:case Gs.SFIXED64:case Gs.SINT64:return Rs("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case Gs.BYTES:return Rs(t instanceof Uint8Array),cr.enc(t)}}const Ir=Symbol("@bufbuild/protobuf/unknown-fields"),Or={readUnknownFields:!0,readerFactory:e=>new sr(e)},Ar={writeUnknownFields:!0,writerFactory:()=>new nr};function Nr(e,t,i,n,s){let{repeated:r,localName:a}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=a&&delete e.value,e.case=a,a="value"),i.kind){case"scalar":case"enum":const o="enum"==i.kind?Gs.INT32:i.T;let c=Lr;if("scalar"==i.kind&&i.L>0&&(c=Mr),r){let i=e[a];if(n==Ys.LengthDelimited&&o!=Gs.STRING&&o!=Gs.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,o))}else i.push(c(t,o))}else e[a]=c(t,o);break;case"message":const d=i.T;r?e[a].push(Dr(t,new d,s,i)):gr(e[a])?Dr(t,e[a],s,i):(e[a]=Dr(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[a]=d.fieldWrapper.unwrapField(e[a])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,a;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=Lr(t,e.K);break;case 2:switch(e.V.kind){case"scalar":a=Lr(t,e.V.T);break;case"enum":a=t.int32();break;case"message":a=Dr(t,new e.V.T,i,void 0)}}}if(void 0===r&&(r=tr(e.K,Js.BIGINT)),"string"!=typeof r&&"number"!=typeof r&&(r=r.toString()),void 0===a)switch(e.V.kind){case"scalar":a=tr(e.V.T,Js.BIGINT);break;case"enum":a=e.V.T.values[0].no;break;case"message":a=new e.V.T}return[r,a]}(i,t,s);e[a][l]=u}}function Dr(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function Mr(e,t){const i=Lr(e,t);return"bigint"==typeof i?i.toString():i}function Lr(e,t){switch(t){case Gs.STRING:return e.string();case Gs.BOOL:return e.bool();case Gs.DOUBLE:return e.double();case Gs.FLOAT:return e.float();case Gs.INT32:return e.int32();case Gs.INT64:return e.int64();case Gs.UINT64:return e.uint64();case Gs.FIXED64:return e.fixed64();case Gs.BYTES:return e.bytes();case Gs.FIXED32:return e.fixed32();case Gs.SFIXED32:return e.sfixed32();case Gs.SFIXED64:return e.sfixed64();case Gs.SINT64:return e.sint64();case Gs.UINT32:return e.uint32();case Gs.SINT32:return e.sint32()}}function Ur(e,t,i,n){Rs(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?Gs.INT32:e.T;if(s)if(Rs(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,Ys.LengthDelimited).fork();let[,s]=$r(t);for(let r=0;r<n.length;r++)e[s](n[r]);e.join()}(i,r,e.no,t);else for(const n of t)Br(i,r,e.no,n);else Br(i,r,e.no,t);break;case"message":if(s){Rs(Array.isArray(t));for(const s of t)Fr(i,n,e,s)}else Fr(i,n,e,t);break;case"map":Rs("object"==typeof t&&null!=t);for(const[s,a]of Object.entries(t))jr(i,n,e,s,a)}}function jr(e,t,i,n,s){e.tag(i.no,Ys.LengthDelimited),e.fork();let r=n;switch(i.K){case Gs.INT32:case Gs.FIXED32:case Gs.UINT32:case Gs.SFIXED32:case Gs.SINT32:r=Number.parseInt(n);break;case Gs.BOOL:Rs("true"==n||"false"==n),r="true"==n}switch(Br(e,i.K,1,r),i.V.kind){case"scalar":Br(e,i.V.T,2,s);break;case"enum":Br(e,Gs.INT32,2,s);break;case"message":Rs(void 0!==s),e.tag(2,Ys.LengthDelimited).bytes(s.toBinary(t))}e.join()}function Fr(e,t,i,n){const s=fr(i.T,n);i.delimited?e.tag(i.no,Ys.StartGroup).raw(s.toBinary(t)).tag(i.no,Ys.EndGroup):e.tag(i.no,Ys.LengthDelimited).bytes(s.toBinary(t))}function Br(e,t,i,n){Rs(void 0!==n);let[s,r]=$r(t);e.tag(i,s)[r](n)}function $r(e){let t=Ys.Varint;switch(e){case Gs.BYTES:case Gs.STRING:t=Ys.LengthDelimited;break;case Gs.DOUBLE:case Gs.FIXED64:case Gs.SFIXED64:t=Ys.Bit64;break;case Gs.FIXED32:case Gs.SFIXED32:case Gs.FLOAT:t=Ys.Bit32}return[t,Gs[e].toLowerCase()]}function Vr(e){if(void 0===e)return e;if(gr(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function qr(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Kr{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const 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){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Zr(e,t){const i=zr(e);return t?i:Yr(Qr(i))}const Hr=zr;function zr(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){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(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const Gr=new Set(["constructor","toString","toJSON","valueOf"]),Wr=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Jr=e=>"".concat(e,"$"),Qr=e=>Wr.has(e)?Jr(e):e,Yr=e=>Gr.has(e)?Jr(e):e;class Xr{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=Zr(e,!1)}addField(e){Rs(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]}}const ea=(ta=e=>new Kr(e,(e=>function(e){var t,i,n,s,r,a;const o=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Zr(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Hr(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:Js.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(r=d.req)&&void 0!==r&&r,e.opt=null!==(a=d.opt)&&void 0!==a&&a,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=Gs.BYTES&&d.T!=Gs.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Xr(t)),e.oneof=c,c.addField(e)}o.push(e)}return o}(e))),ia=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=tr(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},vr),e):vr},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},yr),e):yr},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(Tr(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[a,o]of Object.entries(t)){const t=e.fields.findJsonName(a);if(t){if(t.oneof){if(null===o&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(a,'"'));s.set(t.oneof,a)}Sr(n,o,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&a.startsWith("[")&&a.endsWith("]")){const s=r.findExtension(a.substring(1,a.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=rr(s);Sr(e,o,s.field,i,s),lr(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!pr(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!_r(s))continue}const i=Pr(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const a=r.findExtensionFor(i.typeName,s.no);if(a&&ur(e,a)){const i=dr(e,a,t),s=Pr(a.field,i,t);void 0!==s&&(n[a.field.jsonName]=s)}}}catch(r){const e=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw new Error(e+(t.length>0?": ".concat(t):""))}return n},readScalar:(e,t,i)=>wr(e,t,null!=i?i:Js.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||ir(e,t)?xr(e,t):void 0},debug:Tr},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},Or),e):Or},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},Ar),e):Ar},listUnknownFields(e){var t;return null!==(t=e[Ir])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Ir]},writeUnknownFields(e,t){const i=e[Ir];if(i)for(const n of i)t.tag(n.no,n.wireType).raw(n.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[Ir])||(s[Ir]=[]),s[Ir].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),a=s?t.len:t.pos+i;let o,c;for(;t.pos<a&&([o,c]=t.tag(),!0!==s||c!=Ys.EndGroup);){const i=r.fields.find(o);if(i)Nr(e,t,i,c,n);else{const i=t.skip(c,o);n.readUnknownFields&&this.onUnknownField(e,o,c,i)}}if(s&&(c!=Ys.EndGroup||o!==i))throw new Error("invalid end group tag")},readField:Nr,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(pr(s,e))Ur(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&Ur(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:Ns,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let a=r[i].value;t&&"message"==t.kind&&!gr(a,t.T)?a=new t.T(a):t&&"scalar"===t.kind&&t.T===Gs.BYTES&&(a=qr(a)),s[i]={case:e,value:a};break;case"scalar":case"enum":let o=r[i];n.T===Gs.BYTES&&(o=n.repeated?o.map(qr):qr(o)),s[i]=o;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===Gs.BYTES)for(const[t,n]of Object.entries(r[i]))s[i][t]=qr(n);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((e=>gr(e,c)?e:new c(e)));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=qr(e):s[i]=e:s[i]=gr(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>er(e.T,t,s[i])));case"enum":return n.every(((e,t)=>er(Gs.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(n,s);case"enum":return er(Gs.INT32,n,s);case"scalar":return er(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const t=e.findField(n.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(n.value,s.value);case"enum":return er(Gs.INT32,n.value,s.value);case"scalar":return er(t.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const i=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return i.every((e=>t.equals(n[e],s[e])));case"enum":return i.every((e=>er(Gs.INT32,n[e],s[e])));case"scalar":const r=e.V.T;return i.every((e=>er(r,n[e],s[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const s of t.fields.byMember()){const t=e[s.localName];let i;if(s.repeated)i=t.map(Vr);else if("map"==s.kind){i=n[s.localName];for(const[e,n]of Object.entries(t))i[e]=Vr(n)}else i="oneof"==s.kind?s.findField(t.case)?{case:t.case,value:Vr(t.value)}:{case:void 0}:Vr(t);n[s.localName]=i}for(const s of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return i}}),{newFieldList:ta,initFields:ia}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),a={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(a.prototype,new Ls),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new a).fromBinary(e,t),fromJson:(e,t)=>(new a).fromJson(e,t),fromJsonString:(e,t)=>(new a).fromJsonString(e,t),equals:(t,i)=>e.util.equals(a,t,i)}),a}(this,e,t,i)},makeEnum:function(e,t,i){const n={};for(const s of t){const e=Ms(s);n[e.localName]=e.no,n[e.no]=e.localName}return Ns(n,e,t),n},makeEnumType:Ds,getEnumType:function(e){const t=e[As];return Rs(t,"missing enum type on enum object"),t},makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var ta,ia;class na extends Ls{constructor(e){super(),this.seconds=zs.zero,this.nanos=0,ea.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(ea.json.debug(e)));const 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 new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const 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 new 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 new 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=zs.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new 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 new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const 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 na.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new na({seconds:zs.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new na).fromBinary(e,t)}static fromJson(e,t){return(new na).fromJson(e,t)}static fromJsonString(e,t){return(new na).fromJsonString(e,t)}static equals(e,t){return ea.util.equals(na,e,t)}}na.runtime=ea,na.typeName="google.protobuf.Timestamp",na.fields=ea.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const sa=ea.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:na},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:ra,repeated:!0},{no:5,name:"events",kind:"message",T:oa,repeated:!0}])),ra=ea.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:aa,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),aa=ea.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:na},{no:3,name:"value",kind:"scalar",T:2}])),oa=ea.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:na},{no:7,name:"normalized_end_timestamp",kind:"message",T:na,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),ca=ea.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),da=ea.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),la=ea.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"}]),ua=ea.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ha=ea.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),pa=ea.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),ma=ea.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"}]),ga=ea.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"}]),fa=ea.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),va=ea.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"}]),ya=ea.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:ba,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:Ja}])),ba=ea.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),ka=ea.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:ea.getEnumType(la),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}])),Ta=ea.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:ea.getEnumType(Sa)},{no:4,name:"tracks",kind:"message",T:Pa,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:ka},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:ea.getEnumType(Ca)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:ea.getEnumType(ma)},{no:18,name:"kind_details",kind:"enum",T:ea.getEnumType(wa),repeated:!0}])),Sa=ea.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ca=ea.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),wa=ea.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Ea=ea.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),_a=ea.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:Ra,repeated:!0}])),Pa=ea.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:ea.getEnumType(da)},{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:ea.getEnumType(la)},{no:10,name:"layers",kind:"message",T:Ra,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:_a,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:ea.getEnumType(Ea)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Ja},{no:19,name:"audio_features",kind:"enum",T:ea.getEnumType(va),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:ea.getEnumType(ca)}])),Ra=ea.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:ea.getEnumType(ua)},{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}])),xa=ea.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:ea.getEnumType(Ia)},{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:Na,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Oa,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Da,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Ma,oneof:"value"},{no:8,name:"metrics",kind:"message",T:sa,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Ua,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:ja,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Fa,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ba,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:eo,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:to,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:io,oneof:"value"}])),Ia=ea.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Oa=ea.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Aa,repeated:!0}])),Aa=ea.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}])),Na=ea.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}])),Da=ea.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Ma=ea.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:La,repeated:!0}])),La=ea.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}])),Ua=ea.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}])),ja=ea.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}])),Fa=ea.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Ba=ea.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:$a,oneof:"value"}])),$a=ea.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}])),Va=ea.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),qa=ea.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:ea.getEnumType(Ka)},{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}])),Ka=ea.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Za=ea.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:ea.getEnumType(Ha)},{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}])),Ha=ea.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"}]),za=ea.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Ga},{no:2,name:"screen",kind:"message",T:Ga},{no:3,name:"resume_connection",kind:"enum",T:ea.getEnumType(pa)},{no:4,name:"disabled_codecs",kind:"message",T:Wa},{no:5,name:"force_relay",kind:"enum",T:ea.getEnumType(pa)}])),Ga=ea.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:ea.getEnumType(pa)}])),Wa=ea.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:ba,repeated:!0},{no:2,name:"publish",kind:"message",T:ba,repeated:!0}])),Ja=ea.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Qa=ea.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Ya=ea.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:ea.getEnumType(Qa)},{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"}),Xa=ea.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),eo=ea.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:ea.getEnumType(Ea)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Ya,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Xa,oneof:"content_header"}]),{localName:"DataStream_Header"}),to=ea.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"}),io=ea.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"}),no=ea.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),so=ea.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),ro=ea.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),ao=ea.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:vo,oneof:"message"},{no:2,name:"answer",kind:"message",T:vo,oneof:"message"},{no:3,name:"trickle",kind:"message",T:uo,oneof:"message"},{no:4,name:"add_track",kind:"message",T:lo,oneof:"message"},{no:5,name:"mute",kind:"message",T:ho,oneof:"message"},{no:6,name:"subscription",kind:"message",T:bo,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ko,oneof:"message"},{no:8,name:"leave",kind:"message",T:Co,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Eo,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:jo,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Bo,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Vo,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:_o,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:qo,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:To,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:So,oneof:"message"}])),oo=ea.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:po,oneof:"message"},{no:2,name:"answer",kind:"message",T:vo,oneof:"message"},{no:3,name:"offer",kind:"message",T:vo,oneof:"message"},{no:4,name:"trickle",kind:"message",T:uo,oneof:"message"},{no:5,name:"update",kind:"message",T:yo,oneof:"message"},{no:6,name:"track_published",kind:"message",T:go,oneof:"message"},{no:8,name:"leave",kind:"message",T:Co,oneof:"message"},{no:9,name:"mute",kind:"message",T:ho,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Ro,oneof:"message"},{no:11,name:"room_update",kind:"message",T:xo,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Oo,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:No,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Lo,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Fo,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:fo,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:mo,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Ko,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:zo,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Go,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Jo,oneof:"message"}])),co=ea.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),lo=ea.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:ea.getEnumType(da)},{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:ea.getEnumType(la)},{no:9,name:"layers",kind:"message",T:Ra,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:co,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:ea.getEnumType(Ea)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:ea.getEnumType(ca)}])),uo=ea.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:ea.getEnumType(no)},{no:3,name:"final",kind:"scalar",T:8}])),ho=ea.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),po=ea.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:ya},{no:2,name:"participant",kind:"message",T:Ta},{no:3,name:"other_participants",kind:"message",T:Ta,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Po,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:za},{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:qa},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ba,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),mo=ea.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Po,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:za}])),go=ea.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Pa}])),fo=ea.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),vo=ea.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}])),yo=ea.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:Ta,repeated:!0}])),bo=ea.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:Va,repeated:!0}])),ko=ea.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:ea.getEnumType(ua)},{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}])),To=ea.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:ea.getEnumType(va),repeated:!0}])),So=ea.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}])),Co=ea.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:ea.getEnumType(ma)},{no:3,name:"action",kind:"enum",T:ea.getEnumType(wo)},{no:4,name:"regions",kind:"message",T:Zo}])),wo=ea.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Eo=ea.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Ra,repeated:!0}])),_o=ea.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}])),Po=ea.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}])),Ro=ea.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Aa,repeated:!0}])),xo=ea.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:ya}])),Io=ea.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:ea.getEnumType(ha)},{no:3,name:"score",kind:"scalar",T:2}])),Oo=ea.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Io,repeated:!0}])),Ao=ea.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:ea.getEnumType(so)}])),No=ea.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Ao,repeated:!0}])),Do=ea.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:ea.getEnumType(ua)},{no:2,name:"enabled",kind:"scalar",T:8}])),Mo=ea.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Do,repeated:!0}])),Lo=ea.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Do,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Mo,repeated:!0}])),Uo=ea.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}])),jo=ea.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Uo,repeated:!0}])),Fo=ea.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}])),Bo=ea.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:vo},{no:2,name:"subscription",kind:"message",T:bo},{no:3,name:"publish_tracks",kind:"message",T:go,repeated:!0},{no:4,name:"data_channels",kind:"message",T:$o,repeated:!0},{no:5,name:"offer",kind:"message",T:vo},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}])),$o=ea.makeMessageType("livekit.DataChannelInfo",(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:ea.getEnumType(no)}])),Vo=ea.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:ea.getEnumType(ro),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"}])),qo=ea.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Ko=ea.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Zo=ea.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Ho,repeated:!0}])),Ho=ea.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}])),zo=ea.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:ea.getEnumType(fa)}])),Go=ea.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:ea.getEnumType(Wo)},{no:3,name:"message",kind:"scalar",T:9}])),Wo=ea.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Jo=ea.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));function Qo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Yo,Xo,ec,tc,ic,nc,sc,rc,ac={exports:{}},oc=(Yo||(Yo=1,ec=ac.exports,tc=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"],s={},r=null;function a(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(n){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(),s=0;s<n.length;s++){var r=n[s];this[r]=s<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 d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?o:void 0!==console[n]?a(console,n):void 0!==console.log?a(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var a,o,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(r){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(r){}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 new 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||l,u.getLevel=function(){return null!=d?d:null!=o?o:a},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(s){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(s){}}}(d),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(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&&(a=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},a=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[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 s},r.default=r,r},(Xo=ac).exports?Xo.exports=tc():ec.log=tc()),ac.exports);(nc=ic||(ic={}))[nc.trace=0]="trace",nc[nc.debug=1]="debug",nc[nc.info=2]="info",nc[nc.warn=3]="warn",nc[nc.error=4]="error",nc[nc.silent=5]="silent",(rc=sc||(sc={})).Default="livekit",rc.Room="livekit-room",rc.Participant="livekit-participant",rc.Track="livekit-track",rc.Publication="livekit-track-publication",rc.Engine="livekit-engine",rc.Signal="livekit-signal",rc.PCManager="livekit-pc-manager",rc.PCTransport="livekit-pc-transport",rc.E2EE="lk-e2ee";let cc=oc.getLogger("livekit");function dc(e){const t=oc.getLogger(e);return t.setDefaultLevel(cc.getLevel()),t}Object.values(sc).map((e=>oc.getLogger(e))),cc.setDefaultLevel(ic.info);const lc=oc.getLogger("lk-e2ee"),uc=7e3,hc=[0,300,1200,2700,4800,uc,uc,uc,uc,uc];function pc(e,t,i,n){return new(i||(i=Promise))((function(s,r){function a(e){try{c(n.next(e))}catch(t){r(t)}}function o(e){try{c(n.throw(e))}catch(t){r(t)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}c((n=n.apply(e,t||[])).next())}))}function mc(e){if(!Symbol.asyncIterator)throw new 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 new 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,s){!function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)}(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var gc,fc={exports:{}},vc=function(){if(gc)return fc.exports;gc=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 s(){s.init.call(this)}fc.exports=s,fc.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,r,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,s)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,r,c,d;if(a(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),(s=o(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new 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,d=l,console&&console.warn&&console.warn(d)}return e}function d(){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 l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.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=new 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)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(r){n.once&&e.removeEventListener(t,s),i(r)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),s.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},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return a(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,r,o;if(a(t),void 0===(n=this._events))return this;if(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(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){o=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.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 s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);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},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},fc.exports}();let yc=!0,bc=!0;function kc(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function Tc(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const 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),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const 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 Sc(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(yc=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Cc(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(bc=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function wc(){if("object"==typeof window){if(yc)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ec(e,t){bc&&console.warn(e+" is deprecated, please use "+t+" instead.")}function _c(e){return"[object Object]"===Object.prototype.toString.call(e)}function Pc(e){return _c(e)?Object.keys(e).reduce((function(t,i){const n=_c(e[i]),s=n?Pc(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})}),{}):e}function Rc(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Rc(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Rc(e,e.get(t),i)}))})))}function xc(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const 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&&Rc(e,i,s)}))})),s}const Ic=wc;function Oc(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=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[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const 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});const a=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||a)){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 a=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&i.length&&t.includes("back")&&(a=i[i.length-1]),a&&(e.video.deviceId=r.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=n(e.video),Ic("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return Ic("chrome: "+JSON.stringify(e)),s(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){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(r(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(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 Ac(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Nc(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){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});const 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};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),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};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Tc(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Dc(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const 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()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const 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))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const 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)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const 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 Mc(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>xc(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Tc(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>xc(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Lc(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const 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};const 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")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const 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)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Uc(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Lc(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const 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]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.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||{},s.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");const 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||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const 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){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const 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)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:r(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){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");let t;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 jc(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function Fc(e,t){Tc(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Bc=Object.freeze({__proto__:null,fixNegotiationNeeded:Fc,shimAddTrackRemoveTrack:Uc,shimAddTrackRemoveTrackWithNative:Lc,shimGetSendersWithDtmf:Dc,shimGetUserMedia:Oc,shimMediaStream:Ac,shimOnTrack:Nc,shimPeerConnection:jc,shimSenderReceiverGetStats:Mc});function $c(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Ec("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const 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&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Vc(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 qc(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){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const 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(){const[e,s,r]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(n){if("TypeError"!==n.name)throw n;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(s,r)}}function Kc(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const 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 Zc(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Tc(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Hc(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ec("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function zc(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Gc(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{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 Wc(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Jc(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const 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 Qc(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const 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 Yc=Object.freeze({__proto__:null,shimAddTransceiver:Gc,shimCreateAnswer:Qc,shimCreateOffer:Jc,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){const 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:Wc,shimGetUserMedia:$c,shimOnTrack:Vc,shimPeerConnection:qc,shimRTCDataChannel:zc,shimReceiverGetStats:Zc,shimRemoveStream:Hc,shimSenderGetStats:Kc});function Xc(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)){const 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=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];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=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function ed(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);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const 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);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function td(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let o=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,o=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=o,o=function(e,t,i){const n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=o}function id(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(nd(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function nd(e){return e&&void 0!==e.video?Object.assign({},e,{video:Pc(e.video)}):e}function sd(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(Ec("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),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 rd(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 ad(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const 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);const 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 od(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var cd,dd=Object.freeze({__proto__:null,shimAudioContext:od,shimCallbacksAPI:td,shimConstraints:nd,shimCreateOfferLegacy:ad,shimGetUserMedia:id,shimLocalStreamsAPI:Xc,shimRTCIceServerUrls:sd,shimRemoteStreamsAPI:ed,shimTrackEventTransceiver:rd}),ld={exports:{}},ud=(cd||(cd=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[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 n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const 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);const 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(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const 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(" ")}},t.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"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let s=0;s<n.length;s++)i=n[s].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const 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},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.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},t.parseSsrcMedia=function(e){const 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},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.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},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const 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}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.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},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],a=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(a){const n=t.parseRtpMap(a),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",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((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),o=a.length>0&&a[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===o&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:o,codecPayloadType:parseInt(e.parameters.apt,10)};o&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:o,mechanism:r?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&o&&i.push({ssrc:o});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},t.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},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.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("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"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]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(ld)),ld.exports),hd=Qo(ud),pd=ws({__proto__:null,default:hd},[ud]);function md(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const 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){const i=new t(e),n=hd.parseCandidate(e.candidate);for(const 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,Tc(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function gd(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Tc(e,"icecandidate",(e=>{if(e.candidate){const t=hd.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function fd(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}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{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(function(e){if(!e||!e.sdp)return!1;const t=hd.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=hd.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=hd.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function vd(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},Tc(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function yd(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const 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}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function bd(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const 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 kd(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const 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 Td(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const 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},!e.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 Sd=Object.freeze({__proto__:null,removeExtmapAllowMixed:bd,shimAddIceCandidateNullOrEmpty:kd,shimConnectionState:yd,shimMaxMessageSize:fd,shimParameterlessSetLocalDescription:Td,shimRTCIceCandidate:md,shimRTCIceCandidateRelayProtocol:gd,shimSendThrowTypeError:vd});!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};const i=wc,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=kc(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=kc(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=kc(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:n,commonShim:Sd,extractVersion:kc,disableLog:Sc,disableWarnings:Cc,sdp:pd};switch(n.browser){case"chrome":if(!Bc||!jc||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=Bc,kd(e,n),Td(e),Oc(e,n),Ac(e),jc(e,n),Nc(e),Uc(e,n),Dc(e),Mc(e),Fc(e,n),md(e),gd(e),yd(e),fd(e,n),vd(e),bd(e,n);break;case"firefox":if(!Yc||!qc||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=Yc,kd(e,n),Td(e),$c(e,n),qc(e,n),Vc(e),Hc(e),Kc(e),Zc(e),zc(e),Gc(e),Wc(e),Jc(e),Qc(e),md(e),yd(e),fd(e,n),vd(e);break;case"safari":if(!dd||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=dd,kd(e,n),Td(e),sd(e),ad(e),td(e),Xc(e),ed(e),rd(e),id(e),od(e),md(e),gd(e),fd(e,n),vd(e),bd(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const Cd="lk_e2ee";var wd,Ed,_d,Pd,Rd,xd,Id,Od,Ad,Nd,Dd,Md,Ld,Ud,jd,Fd,Bd,$d,Vd,qd;function Kd(){return void 0!==window.RTCRtpScriptTransform}(Ed=wd||(wd={})).SetKey="setKey",Ed.RatchetRequest="ratchetRequest",Ed.KeyRatcheted="keyRatcheted",(_d||(_d={})).KeyRatcheted="keyRatcheted",(Rd=Pd||(Pd={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Rd.EncryptionError="encryptionError",(xd||(xd={})).Error="cryptorError",vc.EventEmitter;class Zd extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}(Od=Id||(Id={}))[Od.NotAllowed=0]="NotAllowed",Od[Od.ServerUnreachable=1]="ServerUnreachable",Od[Od.InternalError=2]="InternalError",Od[Od.Cancelled=3]="Cancelled",Od[Od.LeaveRequest=4]="LeaveRequest";class Hd extends Zd{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=Id[t]}}class zd extends Zd{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Gd extends Zd{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Wd extends Zd{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Jd extends Zd{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Qd extends Zd{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Yd extends Zd{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Xd extends Zd{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:Wo[t]}}(Nd=Ad||(Ad={})).PermissionDenied="PermissionDenied",Nd.NotFound="NotFound",Nd.DeviceInUse="DeviceInUse",Nd.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(Ad||(Ad={})),(Md=Dd||(Dd={}))[Md.InvalidKey=0]="InvalidKey",Md[Md.MissingKey=1]="MissingKey",Md[Md.InternalError=2]="InternalError",(Ud=Ld||(Ld={})).Connected="connected",Ud.Reconnecting="reconnecting",Ud.SignalReconnecting="signalReconnecting",Ud.Reconnected="reconnected",Ud.Disconnected="disconnected",Ud.ConnectionStateChanged="connectionStateChanged",Ud.MediaDevicesChanged="mediaDevicesChanged",Ud.ParticipantConnected="participantConnected",Ud.ParticipantDisconnected="participantDisconnected",Ud.TrackPublished="trackPublished",Ud.TrackSubscribed="trackSubscribed",Ud.TrackSubscriptionFailed="trackSubscriptionFailed",Ud.TrackUnpublished="trackUnpublished",Ud.TrackUnsubscribed="trackUnsubscribed",Ud.TrackMuted="trackMuted",Ud.TrackUnmuted="trackUnmuted",Ud.LocalTrackPublished="localTrackPublished",Ud.LocalTrackUnpublished="localTrackUnpublished",Ud.LocalAudioSilenceDetected="localAudioSilenceDetected",Ud.ActiveSpeakersChanged="activeSpeakersChanged",Ud.ParticipantMetadataChanged="participantMetadataChanged",Ud.ParticipantNameChanged="participantNameChanged",Ud.ParticipantAttributesChanged="participantAttributesChanged",Ud.RoomMetadataChanged="roomMetadataChanged",Ud.DataReceived="dataReceived",Ud.SipDTMFReceived="sipDTMFReceived",Ud.TranscriptionReceived="transcriptionReceived",Ud.ConnectionQualityChanged="connectionQualityChanged",Ud.TrackStreamStateChanged="trackStreamStateChanged",Ud.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Ud.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Ud.AudioPlaybackStatusChanged="audioPlaybackChanged",Ud.VideoPlaybackStatusChanged="videoPlaybackChanged",Ud.MediaDevicesError="mediaDevicesError",Ud.ParticipantPermissionsChanged="participantPermissionsChanged",Ud.SignalConnected="signalConnected",Ud.RecordingStatusChanged="recordingStatusChanged",Ud.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Ud.EncryptionError="encryptionError",Ud.DCBufferStatusChanged="dcBufferStatusChanged",Ud.ActiveDeviceChanged="activeDeviceChanged",Ud.ChatMessage="chatMessage",Ud.LocalTrackSubscribed="localTrackSubscribed",Ud.MetricsReceived="metricsReceived",(Fd=jd||(jd={})).TrackPublished="trackPublished",Fd.TrackSubscribed="trackSubscribed",Fd.TrackSubscriptionFailed="trackSubscriptionFailed",Fd.TrackUnpublished="trackUnpublished",Fd.TrackUnsubscribed="trackUnsubscribed",Fd.TrackMuted="trackMuted",Fd.TrackUnmuted="trackUnmuted",Fd.LocalTrackPublished="localTrackPublished",Fd.LocalTrackUnpublished="localTrackUnpublished",Fd.ParticipantMetadataChanged="participantMetadataChanged",Fd.ParticipantNameChanged="participantNameChanged",Fd.DataReceived="dataReceived",Fd.SipDTMFReceived="sipDTMFReceived",Fd.TranscriptionReceived="transcriptionReceived",Fd.IsSpeakingChanged="isSpeakingChanged",Fd.ConnectionQualityChanged="connectionQualityChanged",Fd.TrackStreamStateChanged="trackStreamStateChanged",Fd.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Fd.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Fd.MediaDevicesError="mediaDevicesError",Fd.AudioStreamAcquired="audioStreamAcquired",Fd.ParticipantPermissionsChanged="participantPermissionsChanged",Fd.PCTrackAdded="pcTrackAdded",Fd.AttributesChanged="attributesChanged",Fd.LocalTrackSubscribed="localTrackSubscribed",Fd.ChatMessage="chatMessage",($d=Bd||(Bd={})).TransportsCreated="transportsCreated",$d.Connected="connected",$d.Disconnected="disconnected",$d.Resuming="resuming",$d.Resumed="resumed",$d.Restarting="restarting",$d.Restarted="restarted",$d.SignalResumed="signalResumed",$d.SignalRestarted="signalRestarted",$d.Closing="closing",$d.MediaTrackAdded="mediaTrackAdded",$d.ActiveSpeakersUpdate="activeSpeakersUpdate",$d.DataPacketReceived="dataPacketReceived",$d.RTPVideoMapUpdate="rtpVideoMapUpdate",$d.DCBufferStatusChanged="dcBufferStatusChanged",$d.ParticipantUpdate="participantUpdate",$d.RoomUpdate="roomUpdate",$d.SpeakersChanged="speakersChanged",$d.StreamStateChanged="streamStateChanged",$d.ConnectionQualityUpdate="connectionQualityUpdate",$d.SubscriptionError="subscriptionError",$d.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",$d.RemoteMute="remoteMute",$d.SubscribedQualityUpdate="subscribedQualityUpdate",$d.LocalTrackUnpublished="localTrackUnpublished",$d.LocalTrackSubscribed="localTrackSubscribed",$d.Offline="offline",$d.SignalRequestResponse="signalRequestResponse",$d.SignalConnected="signalConnected",(qd=Vd||(Vd={})).Message="message",qd.Muted="muted",qd.Unmuted="unmuted",qd.Restarted="restarted",qd.Ended="ended",qd.Subscribed="subscribed",qd.Unsubscribed="unsubscribed",qd.UpdateSettings="updateSettings",qd.UpdateSubscription="updateSubscription",qd.AudioPlaybackStarted="audioPlaybackStarted",qd.AudioPlaybackFailed="audioPlaybackFailed",qd.AudioSilenceDetected="audioSilenceDetected",qd.VisibilityChanged="visibilityChanged",qd.VideoDimensionsChanged="videoDimensionsChanged",qd.VideoPlaybackStarted="videoPlaybackStarted",qd.VideoPlaybackFailed="videoPlaybackFailed",qd.ElementAttached="elementAttached",qd.ElementDetached="elementDetached",qd.UpstreamPaused="upstreamPaused",qd.UpstreamResumed="upstreamResumed",qd.SubscriptionPermissionChanged="subscriptionPermissionChanged",qd.SubscriptionStatusChanged="subscriptionStatusChanged",qd.SubscriptionFailed="subscriptionFailed",qd.TrackProcessorUpdate="trackProcessorUpdate",qd.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",qd.TranscriptionReceived="transcriptionReceived",qd.TimeSyncUpdate="timeSyncUpdate";const el=/version\/(\d+(\.?_?\d+)+)/i;let tl;function il(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===tl||t){const e=nl.find((e=>{let{test:t}=e;return t.test(i)}));tl=null==e?void 0:e.describe(i)}return tl}const nl=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:sl(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:rl(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:sl(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:rl(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:sl(el,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:rl(e)})}];function sl(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function rl(e){return e.includes("mac os")?sl(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class al{}al.setTimeout=function(){return setTimeout(...arguments)},al.setInterval=function(){return setInterval(...arguments)},al.clearTimeout=function(){return clearTimeout(...arguments)},al.clearInterval=function(){return clearInterval(...arguments)};const ol=[];var cl,dl;(dl=cl||(cl={}))[dl.LOW=0]="LOW",dl[dl.MEDIUM=1]="MEDIUM",dl[dl.HIGH=2]="HIGH";class ll extends vc.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=ll.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=cc,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=dc(null!==(n=i.loggerName)&&void 0!==n?n:sc.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=ll.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),vu(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===ll.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===ll.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(ol.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&ol.splice(ol.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),ul(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(n?Vd.AudioPlaybackStarted:Vd.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(n?Vd.AudioPlaybackFailed:Vd.VideoPlaybackFailed,t):"AbortError"===t.name?cc.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):cc.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(Vd.ElementAttached,e),e}detach(e){try{if(e){hl(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Vd.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{hl(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Vd.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=dc(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ol.forEach((e=>{e.parentElement||(t=!1)})),t&&ol.push(e)}}handleAppVisibilityChanged(){return pc(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==ll.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){Nl()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Nl()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ul(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),Ol()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Ol()||Il())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function hl(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t;var i;let n;var s;let r;var a;(i=t=e.Kind||(e.Kind={})).Audio="audio",i.Video="video",i.Unknown="unknown",(s=n=e.Source||(e.Source={})).Camera="camera",s.Microphone="microphone",s.ScreenShare="screen_share",s.ScreenShareAudio="screen_share_audio",s.Unknown="unknown",(a=r=e.StreamState||(e.StreamState={})).Active="active",a.Paused="paused",a.Unknown="unknown",e.kindToProto=function(e){switch(e){case t.Audio:return da.AUDIO;case t.Video:return da.VIDEO;default:return da.DATA}},e.kindFromProto=function(e){switch(e){case da.AUDIO:return t.Audio;case da.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return la.CAMERA;case n.Microphone:return la.MICROPHONE;case n.ScreenShare:return la.SCREEN_SHARE;case n.ScreenShareAudio:return la.SCREEN_SHARE_AUDIO;default:return la.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case la.CAMERA:return n.Camera;case la.MICROPHONE:return n.Microphone;case la.SCREEN_SHARE:return n.ScreenShare;case la.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case so.ACTIVE:return r.Active;case so.PAUSED:return r.Paused;default:return r.Unknown}}}(ll||(ll={}));class pl{constructor(e,t,i,n,s){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)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const ml=["vp8","h264"],gl=["vp8","h264","vp9","av1"];function fl(e){return!!ml.find((t=>t===e))}var vl,yl,bl,kl;(yl=vl||(vl={}))[yl.PREFER_REGRESSION=0]="PREFER_REGRESSION",yl[yl.SIMULCAST=1]="SIMULCAST",yl[yl.REGRESSION=2]="REGRESSION",(kl=bl||(bl={})).telephone={maxBitrate:12e3},kl.speech={maxBitrate:24e3},kl.music={maxBitrate:48e3},kl.musicStereo={maxBitrate:64e3},kl.musicHighQuality={maxBitrate:96e3},kl.musicHighQualityStereo={maxBitrate:128e3};const Tl={h90:new pl(160,90,9e4,20),h180:new pl(320,180,16e4,20),h216:new pl(384,216,18e4,20),h360:new pl(640,360,45e4,20),h540:new pl(960,540,8e5,25),h720:new pl(1280,720,17e5,30),h1080:new pl(1920,1080,3e6,30),h1440:new pl(2560,1440,5e6,30),h2160:new pl(3840,2160,8e6,30)},Sl={h120:new pl(160,120,7e4,20),h180:new pl(240,180,125e3,20),h240:new pl(320,240,14e4,20),h360:new pl(480,360,33e4,20),h480:new pl(640,480,5e5,20),h540:new pl(720,540,6e5,25),h720:new pl(960,720,13e5,30),h1080:new pl(1440,1080,23e5,30),h1440:new pl(1920,1440,38e5,30)},Cl={h360fps3:new pl(640,360,2e5,3,"medium"),h360fps15:new pl(640,360,4e5,15,"medium"),h720fps5:new pl(1280,720,8e5,5,"medium"),h720fps15:new pl(1280,720,15e5,15,"medium"),h720fps30:new pl(1280,720,2e6,30,"medium"),h1080fps15:new pl(1920,1080,25e5,15,"medium"),h1080fps30:new pl(1920,1080,5e6,30,"medium"),original:new pl(0,0,7e6,30,"medium")},wl="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function El(e){return pc(this,void 0,void 0,(function*(){return new Promise((t=>al.setTimeout(t,e)))}))}function _l(){return"addTransceiver"in RTCPeerConnection.prototype}function Pl(){return"addTrack"in RTCPeerConnection.prototype}function Rl(e){return"av1"===e||"vp9"===e}function xl(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function Il(){var e;return"Firefox"===(null===(e=il())||void 0===e?void 0:e.name)}function Ol(){var e;return"Safari"===(null===(e=il())||void 0===e?void 0:e.name)}function Al(){var e,t;return!!Nl()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function Nl(){return"undefined"!=typeof document}function Dl(){return"ReactNative"==navigator.product}function Ml(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Ll(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ul(){if(!Dl())return;let e=Ll();return e?e.platform:void 0}function jl(){if(Nl())return window.devicePixelRatio;if(Dl()){let e=Ll();if(e)return e.devicePixelRatio}return 1}function Fl(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let r=0;r<s;++r){const e=parseInt(i[r],10),t=parseInt(n[r],10);if(e>t)return 1;if(e<t)return-1;if(r===s-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function Bl(e){for(const t of e)t.target.handleResize(t)}function $l(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Vl=null;const ql=()=>(Vl||(Vl=new ResizeObserver(Bl)),Vl);let Kl=null;const Zl=()=>(Kl||(Kl=new IntersectionObserver($l,{root:null,rootMargin:"0px"})),Kl);function Hl(){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];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=i,o}let zl;function Gl(){if(!zl){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[zl]=n.stream.getAudioTracks(),!zl)throw Error("Could not get empty media stream audio track");zl.enabled=!1}return zl.clone()}class Wl{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>pc(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}function Jl(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Ql(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function Yl(e){switch(e.reason){case Id.LeaveRequest:return e.context;case Id.Cancelled:return ma.CLIENT_INITIATED;case Id.NotAllowed:return ma.USER_REJECTED;case Id.ServerUnreachable:return ma.JOIN_FAILURE;default:return ma.UNKNOWN_REASON}}function Xl(e){return void 0!==e?Number(e):void 0}function eu(e){return void 0!==e?BigInt(e):void 0}function tu(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function iu(e){return!!e&&e.kind==ll.Kind.Audio}function nu(e){return!!e&&e.kind==ll.Kind.Video}function su(e){return tu(e)&&nu(e)}function ru(e){return tu(e)&&iu(e)}function au(e){return!!e&&!e.isLocal}function ou(e){return!!e&&!e.isLocal}function cu(e){return au(e)&&nu(e)}function du(e,t,i){var n,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=yu(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=o?o:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(lu(h.audio,t),null!==(n=(r=h.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(lu(h.video,i),null!==(s=(a=h.video).deviceId)&&void 0!==s||(a.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function lu(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function uu(e){var t,i,n,s;const r={};if(e.video)if("object"==typeof e.video){const i={},s=i,a=e.video;Object.keys(a).forEach((e=>{"resolution"===e?lu(s,a.resolution):s[e]=a[e]})),r.video=i,null!==(t=(n=r.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else r.video=!!e.video&&{deviceId:{ideal:"default"}};else r.video=!1;return e.audio?"object"==typeof e.audio?(r.audio=e.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function hu(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>pc(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(n){console.warn("Error trying to auto-resume audio context",n)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}));window.document.body.addEventListener("click",e)}return i}}function pu(e){return"audioinput"===e?ll.Source.Microphone:"videoinput"===e?ll.Source.Camera:ll.Source.Unknown}function mu(e){return e===ll.Source.Microphone?"audioinput":e===ll.Source.Camera?"videoinput":void 0}function gu(e){return e.split("/")[1].toLowerCase()}function fu(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new go({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function vu(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?vu(e.track):{})}}function yu(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}class bu extends vc.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":cc.error(s.error.message),this.emit(Pd.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(Pd.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(Pd.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(wd.KeyRatcheted,s.material,s.keyIndex)}},this.onWorkerError=e=>{cc.error("e2ee worker encountered an error:",{error:e.error}),this.emit(Pd.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||Kd()))throw new zd("tried to setup end-to-end encryption on an unsupported browser");if(cc.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:lc.getLevel()}};this.worker&&(cc.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){cc.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):cc.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(Bd.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(e,t){e.on(Ld.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==Ea.NONE,t.identity))),e.on(Ld.ConnectionStateChanged,(t=>{t===Uh.Connected&&e.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==Ea.NONE,e.identity)}))}))})).on(Ld.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(Ld.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(Ld.SignalConnected,(()=>{if(!this.room)throw new 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(jd.LocalTrackPublished,(e=>pc(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),t.on(wd.SetKey,(e=>this.postKey(e))).on(wd.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}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?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const 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");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?gu(i.mimeType):void 0)}}setupE2EESender(e,t){tu(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||cc.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return pc(this,void 0,void 0,(function*(){if(this.worker){if(Kd()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Cd in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const a={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(a,[r,s])}e[Cd]=!0}}))}handleSender(e,t,i){var n;if(!(Cd in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?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(Kd()){cc.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{cc.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[n.readable,n.writable])}e[Cd]=!0}}}const ku="default";class Tu{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Tu),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return pc(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=Tu.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){cc.debug("awaiting getUserMedia promise");try{e?yield Tu.userMediaPromiseMap.get(e):yield Promise.all(Tu.userMediaPromiseMap.values())}catch(r){cc.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!Ol()||!t.hasDeviceInUse(e))&&(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n})))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return pc(this,void 0,void 0,(function*(){if(t!==ku)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===ku));if(!s)return void cc.warn("could not reliably determine default device");const r=n.find((e=>e.deviceId!==ku&&e.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;cc.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Tu.userMediaPromiseMap.has(e):Tu.userMediaPromiseMap.size>0}}var Su,Cu;Tu.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Tu.userMediaPromiseMap=new Map,(Cu=Su||(Su={}))[Cu.WAITING=0]="WAITING",Cu[Cu.RUNNING=1]="RUNNING",Cu[Cu.COMPLETED=2]="COMPLETED";class wu{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ps,this.nextTaskIndex=0}run(e){return pc(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Su.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Su.RUNNING,yield e()}finally{t.status=Su.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return pc(this,void 0,void 0,(function*(){return this.run((()=>pc(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function Eu(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}const _u=["syncState","trickle","offer","answer","simulate","leave"];var Pu,Ru;(Ru=Pu||(Pu={}))[Ru.CONNECTING=0]="CONNECTING",Ru[Ru.CONNECTED=1]="CONNECTED",Ru[Ru.RECONNECTING=2]="RECONNECTING",Ru[Ru.DISCONNECTING=3]="DISCONNECTING",Ru[Ru.DISCONNECTED=4]="DISCONNECTED";class xu{get currentState(){return this.state}get isDisconnected(){return this.state===Pu.DISCONNECTING||this.state===Pu.DISCONNECTED}get isEstablishingConnection(){return this.state===Pu.CONNECTING||this.state===Pu.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Pu.DISCONNECTED,this.log=cc,this._requestId=0,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.log=dc(null!==(i=t.loggerName)&&void 0!==i?i:sc.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new wu,this.queuedRequests=[],this.closingLock=new Ps,this.connectionLock=new Ps,this.state=Pu.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return pc(this,void 0,void 0,(function*(){return this.state=Pu.CONNECTING,this.options=i,yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return pc(this,void 0,void 0,(function*(){if(this.options)return this.state=Pu.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}));this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)}))}connect(e,t,i,n){this.connectOptions=i;const s=function(e,t,i){var n;const s=new URLSearchParams;return s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid)),s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",Dl()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel),t.os&&s.set("os",t.os),t.osVersion&&s.set("os_version",t.osVersion),t.browser&&s.set("browser",t.browser),t.browserVersion&&s.set("browser_version",t.browserVersion),i.adaptiveStream&&s.set("adaptive_stream","1"),i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString()),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type),s}(t,function(){var e;const t=new Za({sdk:Ha.JS,protocol:15,version:"2.11.4"});return Dl()&&(t.os=null!==(e=Ul())&&void 0!==e?e:""),t}(),i),r=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{i.searchParams.set(t,e)})),Eu(i,"rtc")}(e,s),a=Eu(new URL(Ql(r)),"validate");return new Promise(((e,t)=>pc(this,void 0,void 0,(function*(){const s=yield this.connectionLock.lock();try{const s=()=>pc(this,void 0,void 0,(function*(){this.close(),clearTimeout(o),t(new Hd("room connection has been cancelled (signal)",Id.Cancelled))})),o=setTimeout((()=>{this.close(),t(new Hd("room connection has timed out (signal)",Id.ServerUnreachable))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&s(),null==n||n.addEventListener("abort",s);const c=new URL(r);c.searchParams.has("access_token")&&c.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(c),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(o)},this.ws.onerror=e=>pc(this,void 0,void 0,(function*(){if(this.state===Pu.CONNECTED)this.handleWSError(e);else{this.state=Pu.DISCONNECTED,clearTimeout(o);try{const i=yield fetch(a);if(i.status.toFixed(0).startsWith("4")){const e=yield i.text();t(new Hd(e,Id.NotAllowed,i.status))}else t(new Hd("Encountered unknown websocket error during connection: ".concat(e.toString()),Id.InternalError,i.status))}catch(i){t(new Hd(i instanceof Error?i.message:"server was not reachable",Id.ServerUnreachable))}}})),this.ws.onmessage=r=>pc(this,void 0,void 0,(function*(){var a,o,c;let d;if("string"==typeof r.data){const e=JSON.parse(r.data);d=oo.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(r.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof r.data),this.logContext);d=oo.fromBinary(new Uint8Array(r.data))}if(this.state!==Pu.CONNECTED){let r=!1;if("join"===(null===(a=d.message)||void 0===a?void 0:a.case)?(this.state=Pu.CONNECTED,null==n||n.removeEventListener("abort",s),this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.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})),this.startPingInterval()),e(d.message.value)):this.state===Pu.RECONNECTING&&"leave"!==d.message.case?(this.state=Pu.CONNECTED,null==n||n.removeEventListener("abort",s),this.startPingInterval(),"reconnect"===(null===(o=d.message)||void 0===o?void 0:o.case)?e(d.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),r=!0)):this.isEstablishingConnection&&"leave"===d.message.case?t(new Hd("Received leave request while trying to (re)connect",Id.LeaveRequest,void 0,d.message.value.reason)):i.reconnect||t(new Hd("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"),Id.InternalError)),!r)return}this.signalLatency&&(yield El(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new Hd("Websocket got closed during a (re)connection attempt",Id.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{s()}}))))}close(){return pc(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Pu.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,El(250)])),e.ws=void 0}}finally{t&&(e.state=Pu.DISCONNECTED),i()}}()}))}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Ou(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Ou(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new uo({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new ho({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return pc(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new _o({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}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 Eo({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new jo({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:zs.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new qo({timestamp:zs.parse(Date.now()),rtt:zs.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new To({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Co({reason:ma.CLIENT_INITIATED,action:wo.DISCONNECT})})}sendRequest(e){return pc(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=_u.indexOf(e.case)>=0;return cc.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===Pu.RECONNECTING)return void t.queuedRequests.push((()=>pc(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield El(t.signalLatency)),!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new ao({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(r){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:r}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=Iu(n.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.case){const e=Iu(n.value);this.onOffer&&this.onOffer(e)}else if("trickle"===n.case){const 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)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?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(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return pc(this,void 0,void 0,(function*(){if(this.state===Pu.DISCONNECTED)return;const t=this.onClose;yield this.close(),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=al.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&&al.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=al.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&&al.clearInterval(this.pingInterval)}}function Iu(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function Ou(e){return new vo({sdp:e.sdp,type:e.type})}var Au,Nu,Du,Mu,Lu,Uu={},ju={},Fu={exports:{}};function Bu(){if(Au)return Fu.exports;Au=1;var e=Fu.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",t+=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","maxMessageSize"],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:new 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:new 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",t+=null!=e.mediaClockValue?"=%s":"",(t+=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")}))})),Fu.exports}function $u(){if(Mu)return Du;Mu=1;var e=Bu(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,(function(e){if(i>=s)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 s=[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 a=t.names[r];t.name?s.push(n[t.name][a]):s.push(n[t.names[r]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Du=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var a=i.outerOrder||s,o=i.innerOrder||r,c=[];return a.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"}}var Vu=function(){if(Lu)return Uu;Lu=1;var e=(Nu||(Nu=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=Bu(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),a=r[r.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(s))return i(c,a,s)}})),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(ju)),ju),t=$u(),i=Bu();return Uu.grammar=i,Uu.write=t,Uu.parse=e.parse,Uu.parseParams=e.parseParams,Uu.parseFmtpConfig=e.parseFmtpConfig,Uu.parsePayloads=e.parsePayloads,Uu.parseRemoteCandidates=e.parseRemoteCandidates,Uu.parseImageAttributes=e.parseImageAttributes,Uu.parseSimulcastStreamList=e.parseSimulcastStreamList,Uu}();function qu(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var a=null!=(n=i.isImmediate)&&n,o=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise((function(s,u){var h=a&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!a){var t=e.apply(n,i);o&&o(t),l.forEach((function(e){return(0,e.resolve)(t)})),l=[]}}),function(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return o&&o(p),s(p)}l.push({resolve:s,reject:u})}))};return u.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},u}const Ku="negotiationStarted",Zu="negotiationComplete",Hu="rtpVideoPayloadTypes";class zu extends vc.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=cc,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=qu((e=>pc(this,void 0,void 0,(function*(){this.emit(Ku);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(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=dc(null!==(i=t.loggerName)&&void 0!==i?i:sc.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return pc(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){return pc(this,void 0,void 0,(function*(){var t;let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=Vu.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===r&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const n=Vu.parse(null!==(t=e.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),i=Vu.write(n)}yield this.setMungedSDP(e,i,!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(Zu),e.sdp)&&Vu.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Hu,e.rtp)}))}))}createAndSendOffer(e){return pc(this,void 0,void 0,(function*(){var t;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){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}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);const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const n=Vu.parse(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{Wu(e),"audio"===e.type?Gu(e,[],[]):"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)return!0;if(Rl(t.codec)&&this.ensureVideoDDExtensionForSVC(e,n),"av1"!==t.codec)return!0;const s=Math.round(.7*t.maxbr);for(const n of e.fmtp)if(n.payload===i){n.config.includes("x-google-start-bitrate")||(n.config+=";x-google-start-bitrate=".concat(s));break}return!0}))})),yield this.setMungedSDP(i,Vu.write(n)),this.onOffer(i)}))}createAndSetAnswer(){return pc(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=Vu.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Wu(e),"audio"===e.type&&Gu(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Vu.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Jd("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 Jd("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return pc(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const 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;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return pc(this,void 0,void 0,(function*(){if(t){const s=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(n){let t="unknown error";n instanceof Error?t=n.message:"string"==typeof n&&(t=n);const s={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Qd(t)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===wl)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:wl})}}}function Gu(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Wu(e){if(e.connection){const 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)}}const Ju="vp8",Qu={audioPreset:bl.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Cl.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Ju,backupCodec:!0},Yu={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Xu={deviceId:{ideal:"default"},resolution:Tl.h720.resolution},eh={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:hc}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1},th={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ih,nh;(nh=ih||(ih={}))[nh.NEW=0]="NEW",nh[nh.CONNECTING=1]="CONNECTING",nh[nh.CONNECTED=2]="CONNECTED",nh[nh.FAILED=3]="FAILED",nh[nh.CLOSING=4]="CLOSING",nh[nh.CLOSED=5]="CLOSED";class sh{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=th.peerConnectionTimeout,this.log=cc,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=ih.CONNECTED:i.some((e=>"failed"===e))?this.state=ih.FAILED:i.some((e=>"connecting"===e))?this.state=ih.CONNECTING:i.every((e=>"closed"===e))?this.state=ih.CLOSED:i.some((e=>"closed"===e))?this.state=ih.CLOSING:i.every((e=>"new"===e))&&(this.state=ih.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(ih[t]," to ").concat(ih[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=dc(null!==(n=i.loggerName)&&void 0!==n?n:sc.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new zu(e,i),this.subscriber=new zu(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,no.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,no.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=e=>{var t;null===(t=this.onPublisherOffer)||void 0===t||t.call(this,e)},this.state=ih.NEW,this.connectionLock=new Ps,this.remoteOfferLock=new Ps}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return pc(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return pc(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return pc(this,void 0,void 0,(function*(){t===no.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e){return pc(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return pc(this,void 0,void 0,(function*(){var i;const 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?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return pc(this,void 0,void 0,(function*(){return new Promise(((t,i)=>pc(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(Ku,(()=>{e.signal.aborted||this.publisher.once(Zu,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===no.PUBLISHER||e===no.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return pc(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,s)=>pc(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),al.clearTimeout(r),s(new Hd("room connection has been cancelled",Id.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const r=al.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),s(new Hd("could not establish pc connection",Id.InternalError))}),n);for(;this.state!==ih.CONNECTED;)if(yield El(50),null==t?void 0:t.signal.aborted)return void s(new Hd("room connection has been cancelled",Id.Cancelled));al.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}class rh extends Error{constructor(e,t,i){super(t),this.code=e,this.message=oh(t,rh.MAX_MESSAGE_BYTES),this.data=i?oh(i,rh.MAX_DATA_BYTES):void 0}static fromProto(e){return new rh(e.code,e.message,e.data)}toProto(){return new $a({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new rh(rh.ErrorCode[e],rh.ErrorMessage[e],t)}}function ah(e){return(new TextEncoder).encode(e).length}function oh(e,t){if(ah(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(e.slice(0,r)).length<=t?i=r:n=r-1}return e.slice(0,i)}rh.MAX_MESSAGE_BYTES=256,rh.MAX_DATA_BYTES=15360,rh.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},rh.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"};const ch=2e3;function dh(e,t){if(!t)return 0;let i,n;return"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:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class lh extends ll{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),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=qu((()=>pc(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>pc(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(Vd.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new Ps,this.pauseUpstreamLock=new Ps,this.processorLock=new Ps,this.restartLock=new Ps,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==ll.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}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?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return pc(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{hl(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){const t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(ul(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(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=>{ul(null!=n?n:e,t)})))}))}waitForDimensions(){return pc(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===ll.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=il())||void 0===i?void 0:i.os)&&(yield El(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield El(50)}throw new Gd("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return pc(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Jl(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Jl(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return pc(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===ll.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===ll.Kind.Audio?"audioinput":"videoinput";return t?Tu.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return pc(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return pc(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return pc(this,void 0,void 0,(function*(){if(!this.sender)throw new Gd("unable to replace an unpublished track");let i,n;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.stopProcessor()),this}))}restart(e){return pc(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===ll.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||{deviceId:t},this.attachedElements.forEach((e=>{hl(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return 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(Vd.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?Vd.Muted:Vd.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return pc(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Al()&&(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)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return pc(this,void 0,void 0,(function*(){var e;const 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(Vd.UpstreamPaused,this);const t=il();if("Safari"===(null==t?void 0:t.name)&&Fl(t.version,"12.0")<0)throw new zd("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}}))}resumeUpstream(){return pc(this,void 0,void 0,(function*(){var e;const 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(Vd.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}}))}getRTCStatsReport(){return pc(this,void 0,void 0,(function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()}))}setProcessor(e){return pc(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),r={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(r),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(ul(t._mediaStreamTrack,s),s.muted=!0,s.play().catch((e=>t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e})))),t.processor=e,t.processorElement=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(hl(t._mediaStreamTrack,e),ul(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(Vd.TrackProcessorUpdate,t.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return pc(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)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Vd.TrackProcessorUpdate))}()}))}}class uh extends lh{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,s=arguments.length>4?arguments[4]:void 0;super(e,ll.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>pc(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(t){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}e&&this.prevStats&&(this._currentBitrate=dh(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Vd.AudioTrackFeatureUpdate,this,va.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Vd.AudioTrackFeatureUpdate,this,va.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return pc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===ll.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(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return pc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Jl(this._constraints.deviceId);return this.source!==ll.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 pc(this,void 0,void 0,(function*(){let t;if(e){const i=uu({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return pc(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){Nl()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ch)))}setProcessor(e){return pc(this,void 0,void 0,(function*(){var t;const i=yield this.processorLock.lock();try{if(!Dl()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const 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?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(Vd.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return pc(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;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 pc(this,void 0,void 0,(function*(){const e=yield function(e){return pc(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=hu();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield El(t),n.getByteTimeDomainData(r);const a=r.some((e=>128!==e&&0!==e));return i.close(),!a}return!1}()}))}(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(Vd.AudioSilenceDetected)),e}))}}const hh=Object.values(Tl),ph=Object.values(Sl),mh=Object.values(Cl),gh=[Tl.h180,Tl.h360],fh=[Sl.h180,Sl.h360],vh=["q","h","f"];function yh(e,t,i,n){var s,r;let a=null==n?void 0:n.videoEncoding;e&&(a=null==n?void 0:n.screenShareEncoding);const o=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!a&&!o&&!c||!t||!i)return[{}];a||(a=function(e,t,i,n){const s=function(e,t,i){if(e)return mh;const n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?hh:ph}(e,t,i);let{encoding:r}=s[0];const a=Math.max(t,i);for(let o=0;o<s.length;o+=1){const e=s[o];if(r=e.encoding,e.width>=a)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),cc.debug("using video encoding",a));const l=a.maxFramerate,u=new pl(t,i,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Rl(d)){const e=new Sh(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=il();if(Ol()||Dl()||"Chrome"===(null==i?void 0:i.name)&&Fl(null==i?void 0:i.version,"113")<0){const i="h"==e.suffix?2:3;for(let n=0;n<e.spatial;n+=1)t.push({rid:vh[2-n],maxBitrate:a.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate});t[0].scalabilityMode=c}else t.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),cc.debug("using svc encoding",{encodings:t}),t}if(!o)return[a];let h,p=[];if(p=e?null!==(s=Th(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:bh(e,u):null!==(r=Th(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:bh(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return kh(t,i,[e,h,u],l);if(n>=480)return kh(t,i,[e,u],l)}return kh(t,i,[u])}function bh(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map((e=>{var t,n;return new pl(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)}));var i;const{width:n,height:s}=t,r=n>s?n/s:s/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?gh:fh}function kh(e,t,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=vh.length)return;const a=Math.min(e,t),o={rid:vh[r],scaleResolutionDownBy:Math.max(1,a/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);const d=Il()||0===r;i.encoding.priority&&d&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),s.push(o)})),Dl()&&"ios"===Ul()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,cc.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),cc.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return s}function Th(e){if(e)return e.sort(((e,t)=>{const{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 Sh{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new 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)&&void 0!==e?e:"")}}class Ch extends lh{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,ll.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>pc(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(i){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:i}))}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=dh(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Ps}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Nl())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ch))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return pc(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var a,o=!0,c=mc(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){s=a.value,o=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(d){i={error:d}}finally{try{o||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return pc(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var a,o=!0,c=mc(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){s=a.value,o=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{o||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return pc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==ll.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return pc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==ll.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return pc(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={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)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(e){const t=[];for(let i=cl.LOW;i<=cl.HIGH;i+=1)t.push(new Do({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return pc(this,void 0,void 0,(function*(){var t,i,n,s,r;let a;if(e){const t=uu({video:e});"boolean"!=typeof t.video&&(a=t.video)}yield this.restart(a);try{for(var o,c=!0,d=mc(this.simulcastCodecs.values());!(t=(o=yield d.next()).done);c=!0){s=o.value,c=!1;const e=s;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(l){i={error:l}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return pc(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,a,o,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=mc(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){o=l.value,u=!1;const e=o;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(p){r={error:p}}finally{try{u||s||!(a=h.return)||(yield a.call(h))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(e){return pc(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},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);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return pc(this,void 0,void 0,(function*(){var t,i,n,s,r,a,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(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=mc(e);!(s=(n=yield i.next()).done);t=!0){o=n.value,t=!1;const e=o;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield wh(t.sender,t.encodings,e.qualities,this.senderLock,this.log,this.logContext));else for(const i of e.qualities)if(i.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(d){r={error:d}}finally{try{t||s||!(a=i.return)||(yield a.call(i))}finally{if(r)throw r.error}}return c}))}setPublishingLayers(e){return pc(this,void 0,void 0,(function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),this.sender&&this.encodings&&(yield wh(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return pc(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Al()&&this.isInBackground&&this.source===ll.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function wh(e,t,i,n,s,r){return pc(this,void 0,void 0,(function*(){const a=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:t}));let o=!1;const c=il();if("Chrome"===(null==c?void 0:c.name)&&Fl(null==c?void 0:c.version,"133")>0&&a[0].scalabilityMode){const e=a[0],n=new Sh(e.scalabilityMode);let s=ua.OFF;if(i.forEach((e=>{e.enabled&&(s===ua.OFF||e.quality>s)&&(s=e.quality)})),s===ua.OFF)e.active&&(e.active=!1,o=!0);else if(!e.active||n.spatial!==s+1){o=!0,e.active=!0;const i=new Sh(t[0].scalabilityMode);n.spatial=s+1,n.suffix=i.suffix,1===n.spatial&&(n.suffix=void 0),e.scalabilityMode=n.toString(),e.scaleResolutionDownBy=Math.pow(2,2-s),t[0].maxBitrate&&(e.maxBitrate=t[0].maxBitrate/(e.scaleResolutionDownBy*e.scaleResolutionDownBy))}}else a.forEach(((e,n)=>{var a;let c=null!==(a=e.rid)&&void 0!==a?a:"";""===c&&(c="q");const d=Eh(c),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(o=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),Il()&&(l.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)))}));o&&(n.encodings=a,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}}))}function Eh(e){switch(e){case"f":default:return cl.HIGH;case"h":return cl.MEDIUM;case"q":return cl.LOW}}function _h(e,t,i,n){if(!i)return[new Ra({quality:cl.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new Sh(n),r=[],a="h"==s.suffix?1.5:2,o="h"==s.suffix?2:3;for(let c=0;c<s.spatial;c+=1)r.push(new Ra({quality:Math.min(cl.HIGH,s.spatial-1)-c,width:Math.ceil(e/Math.pow(a,c)),height:Math.ceil(t/Math.pow(a,c)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(o,c)):0,ssrc:0}));return r}return i.map((i=>{var n,s,r;const a=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let o=Eh(null!==(s=i.rid)&&void 0!==s?s:"");return new Ra({quality:o,width:Math.ceil(e/a),height:Math.ceil(t/a),bitrate:null!==(r=i.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const Ph="_lossy",Rh="_reliable",xh="leave-reconnect";var Ih,Oh,Ah,Nh,Dh,Mh,Lh,Uh,jh,Fh,Bh;(Oh=Ih||(Ih={}))[Oh.New=0]="New",Oh[Oh.Connected=1]="Connected",Oh[Oh.Disconnected=2]="Disconnected",Oh[Oh.Reconnecting=3]="Reconnecting",Oh[Oh.Closed=4]="Closed";class $h extends vc.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=th.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ih.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=cc,this.handleDataChannel=e=>pc(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===Rh)t.reliableDCSub=i;else{if(i.label!==Ph)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=>pc(this,void 0,void 0,(function*(){var t,i;const n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=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}));n=yield e.data.arrayBuffer()}const s=xa.fromBinary(new Uint8Array(n));"speaker"===(null===(t=s.value)||void 0===t?void 0:t.case)?this.emit(Bd.ActiveSpeakersUpdate,s.value.value.speakers):("user"===(null===(i=s.value)||void 0===i?void 0:i.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(s,s.value.value),this.emit(Bd.DataPacketReceived,s))}finally{n()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{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=>{const t=0===e.currentTarget.maxRetransmits?Ia.LOSSY:Ia.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());const i=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});null!==n?(e===xh&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=al.setTimeout((()=>this.attemptReconnect(t).finally((()=>this.reconnectTimeout=void 0))),n)):(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(Bd.Disconnected),this.close()})(i)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===Ih.Connected&&e();const i=()=>{this.off(Bd.Disconnected,n),e()},n=()=>{this.off(Bd.Restarted,i),t()};this.once(Bd.Restarted,i),this.once(Bd.Disconnected,n)})),this.updateAndEmitDCBufferStatus=e=>{const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Bd.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Pu.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ga.RR_SIGNAL_DISCONNECTED))},this.log=dc(null!==(t=e.loggerName)&&void 0!==t?t:sc.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new xu(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Ps,this.dataProcessLock=new Ps,this.dcBufferStatus=new Map([[Ia.LOSSY,!0],[Ia.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(Bd.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(Bd.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(Bd.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Bd.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Bd.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Bd.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Bd.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Bd.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,r,a,o;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:null===(o=null===(a=this.latestJoinResponse)||void 0===a?void 0:a.participant)||void 0===o?void 0:o.sid}}join(e,t,i,n){return pc(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout((()=>{this.emit(Bd.SignalConnected)}),10),s}catch(s){if(s instanceof Hd&&s.reason===Id.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw s}}))}close(){return pc(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(Bd.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}}))}cleanupPeerConnections(){return pc(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const 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}))}cleanupClient(){return pc(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Gd("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new Hd("publication of local track timed out, no response from server",Id.InternalError))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return pc(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return pc(this,void 0,void 0,(function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==ih.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const n=this.makeRTCConfiguration(e);var s;this.pcManager=new sh(n,e.subscriberPrimary,this.loggerOptions),this.emit(Bd.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=e=>{this.client.sendOffer(e)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>pc(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===ih.CONNECTED){const t=this.pcState===Ih.New;this.pcState=Ih.Connected,t&&this.emit(Bd.Connected,e)}else t===ih.FAILED&&this.pcState===Ih.Connected&&(this.pcState=Ih.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?ga.RR_SUBSCRIBER_FAILED:ga.RR_PUBLISHER_FAILED));const s=this.client.isDisconnected||this.client.currentState===Pu.RECONNECTING,r=[ih.FAILED,ih.CLOSING,ih.CLOSED].includes(t);s&&r&&!this._isClosed&&this.emit(Bd.Offline)})),this.pcManager.onTrack=e=>{this.emit(Bd.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(s=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=e=>pc(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))})),this.client.onTrickle=(e,t)=>{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=>pc(this,void 0,void 0,(function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(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?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}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Bd.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Bd.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Bd.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Bd.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ga.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(e.regions)),e.action){case wo.DISCONNECT:this.emit(Bd.Disconnected,null==e?void 0:e.reason),this.close();break;case wo.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(xh);break;case wo.RESUME:this.handleDisconnect(xh)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const 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===pa.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(Ph,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Rh,{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)}createSender(e,t,i){return pc(this,void 0,void 0,(function*(){if(_l())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Pl())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Jd("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return pc(this,void 0,void 0,(function*(){if(_l())return this.createSimulcastTransceiverSender(e,t,i,n);if(Pl())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Jd("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return pc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Jd("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),nu(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return pc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Jd("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(e){return pc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Jd("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(e){return pc(this,void 0,void 0,(function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)cc.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==pa.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:ih.NEW)!==ih.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let e=!0;s instanceof Jd?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),e=!1):s instanceof Vh||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",ga.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(Bd.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return pc(this,void 0,void 0,(function*(){var t,i,n;try{if(!this.url||!this.token)throw new Jd("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Bd.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 Vh;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(s){if(s instanceof Hd&&s.reason===Id.NotAllowed)throw new Jd("could not reconnect, token might be expired");throw new Vh}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Bd.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Pu.CONNECTED)throw new Vh("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(Bd.Restarted)}catch(r){const e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),r}}))}resumeConnection(e){return pc(this,void 0,void 0,(function*(){var t;if(!this.url||!this.token)throw new Jd("could not reconnect, url or token not saved");if(!this.pcManager)throw new Jd("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Bd.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(n){let e="";if(n instanceof Error&&(e=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof Hd&&n.reason===Id.NotAllowed)throw new Jd("could not reconnect, token might be expired");if(n instanceof Hd&&n.reason===Id.LeaveRequest)throw n;throw new Vh(e)}if(this.emit(Bd.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Pu.CONNECTED)throw new Vh("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(Bd.Resumed)}))}waitForPCInitialConnection(e,t){return pc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Jd("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return pc(this,void 0,void 0,(function*(){this.pcState=Ih.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield El(2e3),!this.pcManager)throw new Jd("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ih.Connected}catch(e){throw this.pcState=Ih.Disconnected,new Hd("could not establish PC connection, ".concat(e.message),Id.InternalError)}}))}publishRpcResponse(e,t,i,n){return pc(this,void 0,void 0,(function*(){const s=new xa({destinationIdentities:[e],kind:Ia.RELIABLE,value:{case:"rpcResponse",value:new Ba({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,Ia.RELIABLE)}))}publishRpcAck(e,t){return pc(this,void 0,void 0,(function*(){const i=new xa({destinationIdentities:[e],kind:Ia.RELIABLE,value:{case:"rpcAck",value:new Fa({requestId:t})}});yield this.sendDataPacket(i,Ia.RELIABLE)}))}sendDataPacket(e,t){return pc(this,void 0,void 0,(function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const n=this.dataChannelForKind(t);n&&n.send(i),this.updateAndEmitDCBufferStatus(t)}))}waitForBufferStatusLow(e){return new Promise(((t,i)=>pc(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i("Engine closed");for(this.once(Bd.Closing,n);!this.dcBufferStatus.get(e);)yield El(10);this.off(Bd.Closing,n),t()}}))))}ensureDataTransportConnected(e){return pc(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 Jd("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw new Hd("".concat(r," connection not set"),Id.InternalError);let a=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),a=!0),a||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(a=!0),a&&t.negotiate();const o=t.dataChannelForKind(e,i);if("open"===(null==o?void 0:o.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield El(50)}throw new Hd("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()),Id.InternalError)}()}))}ensurePublisherConnected(e){return pc(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===ih.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return pc(this,void 0,void 0,(function*(){return new Promise(((e,t)=>pc(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new Qd("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(Bd.Closing,n),this.pcManager.publisher.once(Hu,(e=>{const t=new Map;e.forEach((e=>{const i=e.codec.toLowerCase();var n;n=i,gl.includes(n)&&t.set(e.payload,i)})),this.emit(Bd.RTPVideoMapUpdate,t)}));try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Qd&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ga.RR_UNKNOWN),t(s)}finally{this.off(Bd.Closing,n)}}))))}))}dataChannelForKind(e,t){if(t){if(e===Ia.LOSSY)return this.lossyDCSub;if(e===Ia.RELIABLE)return this.reliableDCSub}else{if(e===Ia.LOSSY)return this.lossyDC;if(e===Ia.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),r=this.pcManager.subscriber.getRemoteDescription(),a=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,o=new Array,c=new Array;e.forEach((e=>{e.isDesired!==a&&o.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new Bo({answer:s?Ou({sdp:s.sdp,type:s.type}):void 0,offer:r?Ou({sdp:r.sdp,type:r.type}):void 0,subscription:new bo({trackSids:o,subscribe:!a,participantTracks:[]}),publishTracks:fu(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new $o({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(Ia.LOSSY),no.PUBLISHER),t(this.dataChannelForKind(Ia.RELIABLE),no.PUBLISHER),t(this.dataChannelForKind(Ia.LOSSY,!0),no.SUBSCRIBER),t(this.dataChannelForKind(Ia.RELIABLE,!0),no.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&al.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Nl()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Nl()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Vh extends Error{}class qh{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Ml(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return pc(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),cc.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return pc(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new Hd("Could not fetch region settings: ".concat(t.statusText),401===t.status?Id.NotAllowed:Id.InternalError,t.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class Kh{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class Zh extends Kh{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>pc(this,void 0,void 0,(function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch(t){return{done:!0,value:void 0}}})),return(){return pc(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return pc(this,void 0,void 0,(function*(){var e,t,i,n;let s=new Set;try{for(var r,a=!0,o=mc(this);!(e=(r=yield o.next()).done);a=!0){n=r.value,a=!1;const e=n;s.add(e)}}catch(c){t={error:c}}finally{try{a||e||!(i=o.return)||(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(s)}))}}class Hh extends Kh{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Xl(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>pc(this,void 0,void 0,(function*(){try{const{done:i,value:n}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:t.decode(n.content)})}catch(i){return{done:!0,value:void 0}}})),return(){return pc(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return pc(this,void 0,void 0,(function*(){var e,t,i,n;let s="";try{for(var r,a=!0,o=mc(this);!(e=(r=yield o.next()).done);a=!0)n=r.value,a=!1,s+=n}catch(c){t={error:c}}finally{try{a||e||!(i=o.return)||(yield i.call(o))}finally{if(t)throw t.error}}return s}))}}class zh{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 pc(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class Gh extends zh{}class Wh extends zh{}class Jh extends ll{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Vd.Muted:Vd.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const 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(Vd.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return pc(this,void 0,void 0,(function*(){var e;if(null===(e=this.receiver)||void 0===e?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;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()),ch)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame((()=>e()));const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(Vd.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class Qh extends Jh{constructor(e,t,i,n,s,r){super(e,t,ll.Kind.Audio,i,r),this.monitorReceiver=()=>pc(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=dh(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Dl()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Dl())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return pc(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(xl(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&xl(e)&&e.setSinkId(this.sinkId),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(Vd.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(Vd.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return pc(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;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 Yh extends Jh{constructor(e,t,i,n,s){super(e,t,ll.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>pc(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=dh(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=qu((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?hl(this._mediaStreamTrack,t):ul(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new Xh(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);const t=this.elementInfos.filter((t=>t===e));for(const i of t)i.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);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return pc(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return pc(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),n=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),r=this.elementInfos.some((e=>e.visible))&&!n||s;this.lastVisible!==r&&(!r&&Date.now()-i<100?al.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=r,this.emit(Vd.VisibilityChanged,r,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const r of this.elementInfos){const e=r.width()*s,t=r.height()*s;e+t>i+n&&(i=e,n=t)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Vd.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?jl():t||(jl()>2?2:1)}}class Xh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=ep(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ep(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=ep(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:tp(e),this.isPiP=Nl()&&ep(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=tp(this.element),this.isPiP=ep(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Zl().observe(this.element),ql().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=Zl())||void 0===e||e.unobserve(this.element),null===(t=ql())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function ep(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&tp(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function tp(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const r=e.offsetWidth,a=e.offsetHeight,{hidden:o}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+a>i.pageYOffset&&s+r>i.pageXOffset&&!o&&"none"!==c}class ip extends vc.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=Ea.NONE,this.log=cc,this.handleMuted=()=>{this.emit(Vd.Muted)},this.handleUnmuted=()=>{this.emit(Vd.Unmuted)},this.log=dc(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:sc.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=ll.Source.Unknown}setTrack(e){this.track&&(this.track.off(Vd.Muted,this.handleMuted),this.track.off(Vd.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Vd.Muted,this.handleMuted),e.on(Vd.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),vu(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==Ea.NONE}get audioTrack(){if(iu(this.track))return this.track}get videoTrack(){if(nu(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=ll.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===ll.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}))}}(Nh=(Ah=ip||(ip={})).SubscriptionStatus||(Ah.SubscriptionStatus={})).Desired="desired",Nh.Subscribed="subscribed",Nh.Unsubscribed="unsubscribed",(Dh=Ah.PermissionStatus||(Ah.PermissionStatus={})).Allowed="allowed",Dh.NotAllowed="not_allowed";class np extends ip{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Vd.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(Vd.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(Vd.Ended,this.handleTrackEnded)}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 pc(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return pc(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return pc(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return pc(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(iu(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(va.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(va.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(va.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(va.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(va.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(va.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function sp(e,t){return pc(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=yu(e);let a=r.audio,o=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),e.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const e=r.audio.deviceId;r.audio.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:e}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const e=r.video.deviceId;r.video.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:e}})}(!0===r.audio||"object"==typeof r.audio&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),(!0===r.video||"object"==typeof r.video&&!r.video.deviceId)&&(r.video={deviceId:"default"});const c=du(r,Yu,Xu),d=uu(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(Tu.userMediaPromiseMap.set("audioinput",l),l.catch((()=>Tu.userMediaPromiseMap.delete("audioinput")))),r.video&&(Tu.userMediaPromiseMap.set("videoinput",l),l.catch((()=>Tu.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>pc(this,void 0,void 0,(function*(){const r="audio"===i.kind;let a,o=r?c.audio:c.video;"boolean"!=typeof o&&o||(o={});const l=r?d.audio:d.video;"boolean"!=typeof l&&(a=l);const u=i.getSettings().deviceId;(null==a?void 0:a.deviceId)&&Jl(a.deviceId)!==u?a.deviceId=u:a||(a={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new uh(e,t,!1,void 0,i);case"video":return new Ch(e,t,!1,i);default:throw new Gd("unsupported track type: ".concat(e.kind))}}(i,a,t);return h.kind===ll.Kind.Video?h.source=ll.Source.Camera:h.kind===ll.Kind.Audio&&(h.source=ll.Source.Microphone),h.mediaStream=e,iu(h)&&n?yield h.setProcessor(n):nu(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(u){if(!i)throw u;return sp(Object.assign(Object.assign({},e),{audio:a,video:o}),t)}}))}(Lh=Mh||(Mh={})).Excellent="excellent",Lh.Good="good",Lh.Poor="poor",Lh.Lost="lost",Lh.Unknown="unknown";class rp extends vc.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?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?void 0:e.agent)||this.kind===Ca.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,r){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:Ca.STANDARD;var o;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Mh.Unknown,this.log=cc,this.log=dc(null!==(o=null==r?void 0:r.loggerName)&&void 0!==o?o:sc.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=a,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(ll.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(ll.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(ll.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){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.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),0))}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(jd.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(jd.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(jd.AttributesChanged,t)}setPermissions(e){var t,i,n,s,r,a;const o=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(r=this.permissions)||void 0===r?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?void 0:i.canPublishSources[t])}))||e.canSubscribeMetrics!==(null===(a=this.permissions)||void 0===a?void 0:a.canSubscribeMetrics);return this.permissions=e,c&&this.emit(jd.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(jd.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case ha.EXCELLENT:return Mh.Excellent;case ha.GOOD:return Mh.Good;case ha.POOR:return Mh.Poor;case ha.LOST:return Mh.Lost;default:return Mh.Unknown}}(e),t!==this._connectionQuality&&this.emit(jd.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>iu(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(e){e.on(Vd.Muted,(()=>{this.emit(jd.TrackMuted,e)})),e.on(Vd.Unmuted,(()=>{this.emit(jd.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case ll.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case ll.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class ap extends rp{constructor(e,t,i,n,s){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=Ea.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Wl)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==Wo.OK&&s.reject(new Xd(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=rh.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.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 new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Uo({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&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),vu(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),vu(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),vu(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const 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.handleSubscribedQualityUpdate=e=>pc(this,void 0,void 0,(function*(){var t,i,n,s,r,a;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const o=this.videoTrackPublications.get(e.trackSid);if(o)if(e.subscribedCodecs.length>0){if(!o.videoTrack)return;const r=yield o.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=mc(r);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;fl(e)&&(this.log.debug("publish ".concat(e," for ").concat(o.videoTrack.sid),Object.assign(Object.assign({},this.logContext),vu(o))),yield this.publishAdditionalCodecForTrack(o.videoTrack,e,o.options))}}catch(u){i={error:u}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(a=o.videoTrack)||void 0===a?void 0:a.setPublishingLayers(e.subscribedQualities));else this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))})),this.handleLocalTrackUnpublished=e=>{const 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=>pc(this,void 0,void 0,(function*(){if(e.source===ll.Source.ScreenShare||e.source===ll.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),vu(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(ru(e)||su(e))try{if(Nl())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===ll.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),vu(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(t){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),vu(e))),ru(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),vu(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=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Ea.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(Bd.RemoteMute,((e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())})),this.engine.on(Bd.Connected,this.handleReconnected).on(Bd.SignalRestarted,this.handleReconnected).on(Bd.SignalResumed,this.handleReconnected).on(Bd.Restarting,this.handleReconnecting).on(Bd.Resuming,this.handleReconnecting).on(Bd.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Bd.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Bd.Disconnected,this.handleDisconnected).on(Bd.SignalRequestResponse,this.handleSignalRequestResponse).on(Bd.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return pc(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return pc(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return pc(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return pc(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,r)=>pc(t,void 0,void 0,(function*(){var t,a;try{let o=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(a=null!=n?n:this.name)&&void 0!==a?a:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),o=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!o;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield El(50)}r(new Xd("Request to update local metadata timed out","TimeoutError"))}catch(o){o instanceof Error&&r(o)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(ll.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(ll.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(ll.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(jd.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return pc(this,void 0,void 0,(function*(){this.encryptionType=e?Ea.GCM:Ea.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(e,t,i,n){return pc(this,void 0,void 0,(function*(){var s,r;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)){const 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 ll.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case ll.Source.Microphone:t=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case ll.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Gd(e)}}catch(o){throw null==t||t.forEach((e=>{e.stop()})),o instanceof Error&&this.emit(jd.MediaDevicesError,o),this.pendingPublishing.delete(e),o}try{const e=[];for(const s of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),vu(s))),e.push(this.publishTrack(s,n));const i=yield Promise.all(e);[a]=i}catch(o){throw null==t||t.forEach((e=>{e.stop()})),o}finally{this.pendingPublishing.delete(e)}}else if(!(null==a?void 0:a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===ll.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const e=this.getTrackPublication(ll.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a}))}enableCameraAndMicrophone(){return pc(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(ll.Source.Camera)&&!this.pendingPublishing.has(ll.Source.Microphone)){this.pendingPublishing.add(ll.Source.Camera),this.pendingPublishing.add(ll.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(ll.Source.Camera),this.pendingPublishing.delete(ll.Source.Microphone)}}}))}createTracks(e){return pc(this,void 0,void 0,(function*(){var t,i;null!=e||(e={});const n=du(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield sp(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map((e=>(iu(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=ll.Source.Microphone,this.emit(jd.AudioStreamAcquired)),nu(e)&&(this.cameraError=void 0,e.source=ll.Source.Camera),e)))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}}))}createScreenTracks(e){return pc(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new zd("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=il();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")}()||(e.resolution=Cl.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=Ol()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new Gd("no video track found");const s=new Ch(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=ll.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(jd.AudioStreamAcquired);const e=new uh(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=ll.Source.ScreenShareAudio,r.push(e)}return r}))}publishTrack(e,t){return pc(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return pc(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,a,o;let c,d;if(ru(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),tu(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case ll.Source.Microphone:t="audioinput";break;case ll.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new uh(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new Ch(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Gd("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&&(d=t)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),vu(d))),d;const l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(r=null==t?void 0:t.forceStereo)&&void 0!==r?r:l;u&&(t||(t={}),void 0===t.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),vu(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(a=t.dtx)&&void 0!==a||(t.dtx=!1),null!==(o=t.red)&&void 0!==o||(t.red=!1));const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){const e=il(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Fl(t,e.osVersion)>=0)||"Safari"===e.name&&Fl(t,e.version)>=0}()&&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)),h.simulcast=!1),h.source&&(e.source=h.source);const p=new Promise(((t,n)=>pc(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==Pu.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:vu(e)}));const i=()=>pc(this,void 0,void 0,(function*(){try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}));setTimeout((()=>{this.engine.off(Bd.SignalConnected,i),n(new Yd("publishing rejected as engine not connected within timeout",408))}),15e3),this.engine.once(Bd.SignalConnected,i),this.engine.on(Bd.Closing,(()=>{this.engine.off(Bd.SignalConnected,i),n(new Yd("publishing rejected as engine closed",499))}))}else try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}catch(i){n(i)}}))));i.pendingPublishPromises.set(e,p);try{return yield p}catch(m){throw m}finally{i.pendingPublishPromises.delete(e)}}()}))}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),vu(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map((e=>function(e){switch(e){case la.CAMERA:return ll.Source.Camera;case la.MICROPHONE:return ll.Source.Microphone;case la.SCREEN_SHARE:return ll.Source.ScreenShare;case la.SCREEN_SHARE_AUDIO:return ll.Source.ScreenShareAudio;default:return ll.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),vu(e))),!1)}publish(e,t,i){return pc(this,void 0,void 0,(function*(){var n,s,r,a,o,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new Yd("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((t=>tu(e)&&t.source===e.source))&&e.source!==ll.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),vu(e))),t.stopMicTrackOnMute&&iu(e)&&(e.stopOnMute=!0),e.source===ll.Source.ScreenShare&&Il()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Ol())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Il())return!1;if(Ol()){const e=il();if((null==e?void 0:e.version)&&Fl(e.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=Ju),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>t.videoCodec===gu(e.mime)))||(t.videoCodec=gu(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(Vd.Muted,this.onTrackMuted),e.on(Vd.Unmuted,this.onTrackUnmuted),e.on(Vd.Ended,this.handleTrackEnded),e.on(Vd.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Vd.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Vd.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=new lo({cid:e.mediaStreamTrack.id,name:t.name,type:ll.kindToProto(e.kind),muted:e.isMuted,source:ll.sourceToProto(e.source),disableDtx:!(null===(n=t.dtx)||void 0===n||n),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy});let g;if(e.kind===ll.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(b){const t=null!==(a=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==a?a:Tl.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),vu(e)),{dims:i}))}m.width=i.width,m.height=i.height,su(e)&&(Rl(p)&&(e.source===ll.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),vu(e))))),t.scalabilityMode=null!==(o=t.scalabilityMode)&&void 0!==o?o:"L3T3_KEY"),m.simulcastCodecs=[new co({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:Ju}),t.backupCodec&&p!==t.backupCodec.codec&&m.encryption===Ea.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new co({codec:t.backupCodec.codec,cid:""})))),g=yh(e.source===ll.Source.ScreenShare,m.width,m.height,t),m.layers=_h(m.width,m.height,g,Rl(t.videoCodec))}else e.kind===ll.Kind.Audio&&(g=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Jd("cannot publish track when not connected");const f=()=>pc(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new Jd("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,g),su(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===ll.Source.ScreenShare||e.constraints.height&&Jl(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),g)if(Il()&&e.kind===ll.Kind.Audio){let t;for(const 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===(n=g[0])||void 0===n?void 0:n.maxBitrate)?g[0].maxBitrate/1e3:0})}else e.codec&&Rl(e.codec)&&(null===(s=g[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:m.cid,codec:e.codec,maxbr:g[0].maxBitrate/1e3});yield this.engine.negotiate()}));let v;if(this.enabledPublishVideoCodecs.length>0)v=(yield Promise.all([this.engine.addTrack(m),f()]))[0];else{let i;if(v=yield this.engine.addTrack(m),v.codecs.forEach((e=>{void 0===i&&(i=e.mimeType)})),i&&e.kind===ll.Kind.Video){const n=gu(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),vu(e)),{codec:n})),t.videoCodec=n,g=yh(e.source===ll.Source.ScreenShare,m.width,m.height,t))}yield f()}const y=new np(e.kind,v,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return y.options=t,e.sid=v.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:g,trackInfo:v})),su(e)?e.startMonitor(this.engine.client):ru(e)&&e.startMonitor(),this.addTrackPublication(y),this.emit(jd.LocalTrackPublished,y),y}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return pc(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==Ea.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new Gd("track is not published");if(!su(e))throw new Gd("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),a=function(e,t,i){var n,s,r,a;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&cc.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const o=e.mediaStreamTrack.getSettings(),c=null!==(n=o.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=o.height)&&void 0!==r?r:null===(a=e.dimensions)||void 0===a?void 0:a.height;return e.source===ll.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),yh(e.source===ll.Source.ScreenShare,c,d,i)}(e,t,r);if(!a)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),vu(e)));const o=e.addSimulcastTrack(t,a);if(!o)return;const c=new lo({cid:o.mediaStreamTrack.id,type:ll.kindToProto(e.kind),muted:e.isMuted,source:ll.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=_h(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new Jd("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>pc(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,o,r,a),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:d}))}))}unpublishTrack(e,t){return pc(this,void 0,void 0,(function*(){var i,n;if(tu(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),vu(e))),yield t)}const s=this.getPublicationForTrack(e),r=s?vu(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(e=s.track).off(Vd.Muted,this.onTrackMuted),e.off(Vd.Unmuted,this.onTrackUnmuted),e.off(Vd.Ended,this.handleTrackEnded),e.off(Vd.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Vd.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Vd.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let a=!1;const o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ih.FAILED&&o)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",a=!0);if(this.engine.removeTrack(o)&&(a=!0),su(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(a=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:c}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case ll.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case ll.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(jd.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return pc(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return pc(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 Promise(((n,s)=>pc(t,void 0,void 0,(function*(){try{const 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=>pc(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===ll.Source.ScreenShare||t.source===ll.Source.ScreenShareAudio||!ru(t)&&!su(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(t){s(t)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return pc(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?Ia.RELIABLE:Ia.LOSSY,s=i.destinationIdentities,r=i.topic,a=new xa({kind:n,value:{case:"user",value:new Na({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r})}});yield t.engine.sendDataPacket(a,n)}()}))}publishDtmf(e,t){return pc(this,void 0,void 0,(function*(){const i=new xa({kind:Ia.RELIABLE,value:{case:"sipDtmf",value:new Da({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Ia.RELIABLE)}))}sendChatMessage(e,t){return pc(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new xa({value:{case:"chatMessage",value:new Ua(Object.assign(Object.assign({},i),{timestamp:zs.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,Ia.RELIABLE),this.emit(jd.ChatMessage,i),i}))}editChatMessage(e,t){return pc(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new xa({value:{case:"chatMessage",value:new Ua(Object.assign(Object.assign({},i),{timestamp:zs.parse(i.timestamp),editTimestamp:zs.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,Ia.RELIABLE),this.emit(jd.ChatMessage,i),i}))}sendText(e,t){return pc(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,r=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),a=new Array(r?r.length+1:1).fill(0),o=(e,i)=>{var n;a[i]=e;const s=a.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,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)=>pc(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 pc(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},r=new eo({streamId:n,mimeType:s.mimeType,topic:s.topic,timestamp:eu(s.timestamp),totalLength:eu(null==e?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Ya({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?Qa.UPDATE:Qa.CREATE})}}),a=null==e?void 0:e.destinationIdentities,o=new xa({destinationIdentities:a,value:{case:"streamHeader",value:r}});yield this.engine.sendDataPacket(o,Ia.RELIABLE);let c=0;const d=this,l=new WritableStream({write(e){return pc(this,void 0,void 0,(function*(){for(const t of function(e){const t=[];let i=(new TextEncoder).encode(e);for(;i.length>15e3;){let e=15e3;for(;e>0;){const t=i[e];if(void 0!==t&&128!=(192&t))break;e--}t.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&t.push(i),t}(e)){yield d.engine.waitForBufferStatusLow(Ia.RELIABLE);const e=new to({content:t,streamId:n,chunkIndex:eu(c)}),i=new xa({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield d.engine.sendDataPacket(i,Ia.RELIABLE),c+=1}}))},close(){return pc(this,void 0,void 0,(function*(){const e=new io({streamId:n}),t=new xa({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield d.engine.sendDataPacket(t,Ia.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let u=()=>pc(this,void 0,void 0,(function*(){yield h.close()}));d.engine.once(Bd.Closing,u);const h=new Gh(l,s,(()=>this.engine.off(Bd.Closing,u)));return h}))}sendFile(e,t){return pc(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return pc(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=t.stream().getReader();for(;;){const{done:e,value:t}=yield r.read();if(e)break;yield s.write(t)}return yield s.close(),s.info}))}streamBytes(e){return pc(this,void 0,void 0,(function*(){var t,i,n,s,r;const a=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),o=null==e?void 0:e.destinationIdentities,c={id:a,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown"},d=new eo({totalLength:eu(null!==(r=c.size)&&void 0!==r?r:0),mimeType:c.mimeType,streamId:a,topic:c.topic,timestamp:eu(Date.now()),contentHeader:{case:"byteHeader",value:new Xa({name:c.name})}}),l=new xa({destinationIdentities:o,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(l,Ia.RELIABLE);let u=0;const h=new Ps,p=this.engine,m=this.log,g=new WritableStream({write(e){return pc(this,void 0,void 0,(function*(){const t=yield h.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3);yield p.waitForBufferStatusLow(Ia.RELIABLE);const n=new xa({destinationIdentities:o,value:{case:"streamChunk",value:new to({content:t,streamId:a,chunkIndex:eu(u)})}});yield p.sendDataPacket(n,Ia.RELIABLE),u+=1,i+=t.byteLength}}finally{t()}}))},close(){return pc(this,void 0,void 0,(function*(){const e=new io({streamId:a}),t=new xa({destinationIdentities:o,value:{case:"streamTrailer",value:e}});yield p.sendDataPacket(t,Ia.RELIABLE)}))},abort(e){m.error("Sink error:",e)}});return new Wh(g,c)}))}performRpc(e){return pc(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:r=1e4}=e;return function*(){return new Promise(((e,a)=>pc(t,void 0,void 0,(function*(){var t,o,c,d;if(ah(s)>15360)return void a(rh.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(o=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===o?void 0:o.version)&&Fl(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void a(rh.builtIn("UNSUPPORTED_SERVER"));const l=crypto.randomUUID();yield this.publishRpcRequest(i,l,n,s,r-2e3);const u=setTimeout((()=>{this.pendingAcks.delete(l),a(rh.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(h)}),2e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:i});const h=setTimeout((()=>{this.pendingResponses.delete(l),a(rh.builtIn("RESPONSE_TIMEOUT"))}),r);this.pendingResponses.set(l,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(l)&&(console.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?a(i):e(null!=t?t:"")},participantIdentity:i})}))))}()}))}registerRpcMethod(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){const 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){const 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,s){return pc(this,void 0,void 0,(function*(){const r=new xa({destinationIdentities:[e],kind:Ia.RELIABLE,value:{case:"rpcRequest",value:new ja({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,Ia.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,rh.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return e.sid===this.sid&&!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),vu(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(ru(n)||su(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return pc(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[i]=t;return i.source===e}));if(t)return t[1];yield El(20)}}))}}class op extends ip{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=cl.HIGH,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Vd.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new bo({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Va({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Vd.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?ip.SubscriptionStatus.Unsubscribed:super.isSubscribed?ip.SubscriptionStatus.Subscribed:ip.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ip.PermissionStatus.Allowed:ip.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(cu(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&cu(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(Vd.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Vd.VisibilityChanged,this.handleVisibilityChange),n.off(Vd.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Vd.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Vd.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Vd.VisibilityChanged,this.handleVisibilityChange),e.on(Vd.Ended,this.handleEnded),this.emit(Vd.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Vd.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Vd.Muted:Vd.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Vd.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Vd.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===ll.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return cu(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ko({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=cl.HIGH,this.emit(Vd.UpdateSettings,e)}}class cp extends rp{static fromParticipantInfo(e,t,i){return new cp(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,s,r,a){super(t,i||"",n,s,r,a,arguments.length>7&&void 0!==arguments[7]?arguments[7]:Ca.STANDARD),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(Vd.UpdateSettings,(t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),vu(e))),this.signalClient.sendUpdateTrackSettings(t)})),e.on(Vd.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(Vd.SubscriptionPermissionChanged,(t=>{this.emit(jd.TrackSubscriptionPermissionChanged,e,t)})),e.on(Vd.SubscriptionStatusChanged,(t=>{this.emit(jd.TrackSubscriptionStatusChanged,e,t)})),e.on(Vd.Subscribed,(t=>{this.emit(jd.TrackSubscribed,t,e)})),e.on(Vd.Unsubscribed,(t=>{this.emit(jd.TrackUnsubscribed,t,e)})),e.on(Vd.SubscriptionFailed,(t=>{this.emit(jd.TrackSubscriptionFailed,e.trackSid,t)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ll.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ll.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,r){let a,o=this.getTrackPublicationBySid(t);return o||t.startsWith("TR")||this.trackPublications.forEach((t=>{o||e.kind!==t.kind.toString()||(o=t)})),o?"ended"===e.readyState?(this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),vu(o))),void this.emit(jd.TrackSubscriptionFailed,t)):(a="video"===e.kind?new Yh(e,t,n,s):new Qh(e,t,n,this.audioContext,this.audioOutput),a.source=o.source,a.isMuted=o.isMuted,a.setMediaStream(i),a.start(),o.setTrack(a),this.volumeMap.has(o.source)&&au(a)&&iu(a)&&a.setVolume(this.volumeMap.get(o.source)),o):0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(jd.TrackSubscriptionFailed,t)):(void 0===r&&(r=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,r-1)}),150))}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach((e=>{var n,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const t=ll.kindFromProto(e.type);if(!t)return;r=new op(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(e),i.set(e.sid,r);const a=Array.from(this.trackPublications.values()).find((e=>e.source===(null==r?void 0:r.source)));a&&r.source!==ll.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:vu(a),newTrack:vu(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),vu(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(jd.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case ll.Kind.Audio:this.audioTrackPublications.delete(e);break;case ll.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(jd.TrackUnpublished,i)}setAudioOutput(e){return pc(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;iu(i.track)&&au(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new 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)}}(jh=Uh||(Uh={})).Disconnected="disconnected",jh.Connecting="connecting",jh.Connected="connected",jh.Reconnecting="reconnecting",jh.SignalReconnecting="signalReconnecting";class dp extends vc.EventEmitter{constructor(e){var t,i,n,s;if(super(),t=this,this.state=Uh.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=cc,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(e,t,i)=>pc(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!_l()&&!Pl())throw Dl()?Error("WebRTC isn't detected, have you called registerGlobals?"):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.");const s=yield this.disconnectLock.lock();if(this.state===Uh.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(Uh.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ml(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new qh(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const r=(n,a,o)=>pc(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{yield this.attemptConnection(null!=o?o:e,t,i,l),this.abortController=void 0,n()}catch(u){if(this.regionUrlProvider&&u instanceof Hd&&u.reason!==Id.Cancelled&&u.reason!==Id.NotAllowed){let e=null;try{e=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(h){if(h instanceof Hd&&(401===h.status||h.reason===Id.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void a(h)}e&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(u.message,". Retrying with another region: ").concat(e),this.logContext),this.recreateEngine(),yield r(n,a,e)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Yl(u)),a(u))}else{let e=ma.UNKNOWN_REASON;u instanceof Hd&&(e=Yl(u)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),a(u)}}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Wl(((e,t)=>{r(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,r)=>pc(this,void 0,void 0,(function*(){var a,o,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(a=d.room)||void 0===a?void 0:a.name,roomSid:null===(o=d.room)||void 0===o?void 0:o.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Wd("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(i){this.log.error(i instanceof Error?i.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:i}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>pc(this,void 0,void 0,(function*(){var s,r;this.state===Uh.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},th),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(Ld.SignalConnected)}catch(a){yield this.engine.close(),this.recreateEngine();const e=new Hd("could not establish signal connection",Id.ServerUnreachable);throw a instanceof Error&&(e.message="".concat(e.message,": ").concat(a.message)),a instanceof Hd&&(e.reason=a.reason,e.status=a.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:a})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Hd("Connection attempt aborted",Id.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(o){throw yield this.engine.close(),this.recreateEngine(),o}Nl()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Nl()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Uh.Connected),this.emit(Ld.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return pc(t,[...i],void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s,r;const a=yield e.disconnectLock.lock();try{if(e.state===Uh.Disconnected)return void e.log.debug("already disconnected",e.logContext);e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===Uh.Connecting||e.state===Uh.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null===(i=e.abortController)||void 0===i||i.abort(),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new Hd("Client initiated disconnect",Id.Cancelled)),e.connectFuture=void 0),(null===(r=e.engine)||void 0===r?void 0:r.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,ma.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()}))},this.onPageLeave=()=>pc(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>pc(this,void 0,void 0,(function*(){const e=[],t=il();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=Gl();e.enabled=!0;const 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(Ld.Disconnected,(()=>{null==i||i.remove(),i=null}))}e.push(i)}this.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(i){throw this.handleAudioPlaybackFailed(i),i}})),this.startVideo=()=>pc(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||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=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Uh.Reconnecting)&&this.emit(Ld.Reconnecting)},this.handleSignalRestarted=e=>pc(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(t){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:t}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(i){return}this.setAndEmitConnectionState(Uh.Connected),this.emit(Ld.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))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===Sa.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=e=>{const 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{const 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.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emitWhenConnected(Ld.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{const 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))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(Ld.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=ll.streamStateFromProto(e.state);n!==i.track.streamState&&(i.track.streamState=n,t.emit(jd.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Ld.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case)this.handleStreamHeader(e.value.value,e.participantIdentity);else if("streamChunk"===e.value.case)this.handleStreamChunk(e.value.value);else if("streamTrailer"===e.value.case)this.handleStreamTrailer(e.value.value);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(Ld.DataReceived,t.payload,e,i,t.topic),null==e||e.emit(jd.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(Ld.SipDTMFReceived,t,e),null==e||e.emit(jd.SipDTMFReceived,t)},this.bufferedSegments=new Map,this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:r,endTime:a,final:o}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return o?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(a.toString()),final:o,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(t,this.transcriptionReceivedTimes);null==n||n.emit(Vd.TranscriptionReceived,s),null==i||i.emit(jd.TranscriptionReceived,s,n),this.emit(Ld.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(Ld.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(Ld.MetricsReceived,e,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Ld.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(Ld.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Ld.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Ld.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>pc(this,void 0,void 0,(function*(){var e,t,i;const n=Tu.getInstance().previousDevices,s=yield Tu.getInstance().getDevices(void 0,!1),r=il();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let o of s){const e=n.find((e=>e.deviceId===o.deviceId));e&&""!==e.label&&e.kind===o.kind&&e.label!==o.label&&"default"===this.getActiveDevice(o.kind)&&this.emit(Ld.ActiveDeviceChanged,o.kind,o.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let o of a){const r=pu(o),a=this.localParticipant.getTrackPublication(r);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter((e=>e.kind===o)),d=this.getActiveDevice(o);d===(null===(t=n.filter((e=>e.kind===o))[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(o,c[0].deviceId):"audioinput"===o&&!Ol()||"videoinput"===o||c.length>0&&!c.find((e=>e.deviceId===this.getActiveDevice(o)))&&(yield this.switchActiveDevice(o,c[0].deviceId))}this.emit(Ld.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Ld.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(Ld.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=e=>{this.emit(Ld.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Ld.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Ld.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Ld.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Ld.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>pc(this,void 0,void 0,(function*(){var t,i,n,s,r,a;null===(t=e.track)||void 0===t||t.on(Vd.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(Vd.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(Ld.LocalTrackPublished,e,this.localParticipant),ru(e.track)&&(yield e.track.checkForSilence())&&this.emit(Ld.LocalAudioSilenceDetected,e);const o=yield null===(a=e.track)||void 0===a?void 0:a.getDeviceId(!1),c=mu(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit(Ld.ActiveDeviceChanged,c,o))})),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(Vd.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(Vd.Restarted,this.onLocalTrackRestarted),this.emit(Ld.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>pc(this,void 0,void 0,(function*(){const t=yield e.getDeviceId(!1),i=mu(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(Ld.ActiveDeviceChanged,i,t))})),this.onLocalConnectionQualityChanged=e=>{this.emit(Ld.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=e=>{this.emit(Ld.MediaDevicesError,e)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Ld.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Ld.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},eh),e),this.log=dc(null!==(i=this.options.loggerName)&&void 0!==i?i:sc.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Yu),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Xu),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Qu),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Ps,this.localParticipant=new ap("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Jl(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Jl(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Jl(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE(),Nl()){const e=new AbortController;null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),dp.cleanupRegistry&&dp.cleanupRegistry.register(this,(()=>{e.abort()}))}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(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)}handleIncomingRpcRequest(e,t,i,n,s,r){return pc(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==r)return void(yield this.engine.publishRpcResponse(e,t,null,rh.builtIn("UNSUPPORTED_VERSION")));const a=this.rpcHandlers.get(i);if(!a)return void(yield this.engine.publishRpcResponse(e,t,null,rh.builtIn("UNSUPPORTED_METHOD")));let o=null,c=null;try{const r=yield a({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});ah(r)>15360?(o=rh.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=r}catch(d){d instanceof rh?o=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),o=rh.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,o)}))}setE2EEEnabled(e){return pc(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new bu(this.options.e2ee),this.e2eeManager.on(Pd.ParticipantEncryptionStatusChanged,((e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(Ld.ParticipantEncryptionStatusChanged,e,t)})),this.e2eeManager.on(Pd.EncryptionError,(e=>this.emit(Ld.EncryptionError,e))),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?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?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return pc(this,void 0,void 0,(function*(){return this.state===Uh.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(Bd.RoomUpdate,i),e(t.sid))};this.engine.on(Bd.RoomUpdate,i),this.once(Ld.Disconnected,(()=>{this.engine.off(Bd.RoomUpdate,i),t("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new $h(this.options),this.engine.on(Bd.ParticipantUpdate,this.handleParticipantUpdates).on(Bd.RoomUpdate,this.handleRoomUpdate).on(Bd.SpeakersChanged,this.handleSpeakersChanged).on(Bd.StreamStateChanged,this.handleStreamStateUpdate).on(Bd.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Bd.SubscriptionError,this.handleSubscriptionError).on(Bd.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Bd.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Bd.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(Bd.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Bd.DataPacketReceived,this.handleDataPacket).on(Bd.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Uh.SignalReconnecting)&&this.emit(Ld.SignalReconnecting)})).on(Bd.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Uh.Connected)&&this.emit(Ld.Reconnected)})).on(Bd.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Uh.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(Bd.Restarting,this.handleRestarting).on(Bd.SignalRestarted,this.handleSignalRestarted).on(Bd.Offline,(()=>{this.setAndEmitConnectionState(Uh.Reconnecting)&&this.emit(Ld.Reconnecting)})).on(Bd.DCBufferStatusChanged,((e,t)=>{this.emit(Ld.DCBufferStatusChanged,e,t)})).on(Bd.LocalTrackSubscribed,(e=>{const t=this.localParticipant.getTrackPublications().find((t=>{let{trackSid:i}=t;return i===e}));t?(this.localParticipant.emit(jd.LocalTrackSubscribed,t),this.emitWhenConnected(Ld.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Tu.getInstance().getDevices(e,t)}prepareConnection(e,t){return pc(this,void 0,void 0,(function*(){if(this.state===Uh.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ml(new URL(e))&&t){this.regionUrlProvider=new qh(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Uh.Disconnected&&(this.regionUrl=i,yield fetch(Ql(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ql(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return pc(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Vo({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Vo({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Vo({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Vo({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=()=>pc(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Vo({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>pc(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Vo({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 Vo({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>pc(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Co({reason:ma.CLIENT_INITIATED,action:wo.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Vo({scenario:{case:"subscriberBandwidth",value:eu(t)}});break;case"leave-full-reconnect":i=new Vo({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 pc(this,arguments,void 0,(function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,a,o,c,d,l,u;let h=!0,p=!1;const m=n?{exact:t}:t;if("audioinput"===e){p=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===ll.Source.Microphone));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.audioCaptureDefaults.deviceId=t,g}}else if("videoinput"===e){p=0===i.localParticipant.videoTrackPublications.size;const t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===ll.Source.Camera));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.videoCaptureDefaults.deviceId=t,g}}else if("audiooutput"===e){if(!xl()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");i.options.webAudioMix&&(t=null!==(a=yield Tu.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==a?a:""),null!==(o=(u=i.options).audioOutput)&&void 0!==o||(u.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(g){throw i.options.audioOutput.deviceId=n,g}}return(p||"audiooutput"===e)&&(i.localParticipant.activeDeviceMap.set(e,"audiooutput"===e&&(null===(l=i.options.audioOutput)||void 0===l?void 0:l.deviceId)||t),i.emit(Ld.ActiveDeviceChanged,e,t)),h}()}))}setupLocalParticipantEvents(){this.localParticipant.on(jd.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(jd.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(jd.AttributesChanged,this.onLocalAttributesChanged).on(jd.TrackMuted,this.onLocalTrackMuted).on(jd.TrackUnmuted,this.onLocalTrackUnmuted).on(jd.LocalTrackPublished,this.onLocalTrackPublished).on(jd.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(jd.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(jd.MediaDevicesError,this.onMediaDevicesError).on(jd.AudioStreamAcquired,this.startAudio).on(jd.ChatMessage,this.onLocalChatMessageSent).on(jd.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===Uh.Connecting||this.state===Uh.Reconnecting){const n=()=>{this.onTrackAdded(e,t,i),s()},s=()=>{this.off(Ld.Reconnected,n),this.off(Ld.Connected,n),this.off(Ld.Disconnected,s)};return this.once(Ld.Reconnected,n),this.once(Ld.Connected,n),void this.once(Ld.Disconnected,s)}if(this.state===Uh.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);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let r=n[1],a=e.id;if(r&&r.startsWith("TR")&&(a=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const o=Array.from(this.remoteParticipants.values()).find((e=>e.sid===s));if(!o)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),o.addSubscribedMediaTrack(e,a,t,i,c)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Uh.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((t=>{var i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(jd.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(jd.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(jd.AttributesChanged,this.onLocalAttributesChanged).off(jd.TrackMuted,this.onLocalTrackMuted).off(jd.TrackUnmuted,this.onLocalTrackUnmuted).off(jd.LocalTrackPublished,this.onLocalTrackPublished).off(jd.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(jd.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(jd.MediaDevicesError,this.onMediaDevicesError).off(jd.AudioStreamAcquired,this.startAudio).off(jd.ChatMessage,this.onLocalChatMessageSent).off(jd.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),Nl()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Uh.Disconnected),this.emit(Ld.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit(Ld.ParticipantDisconnected,t),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return pc(this,void 0,void 0,(function*(){var i;if("byteHeader"===e.contentHeader.case){const n=this.byteStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const r={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Xl(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:t=>{s=t,this.byteStreamControllers.set(e.streamId,{info:r,controller:s,startTime:Date.now()})}});n(new Zh(r,a,Xl(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){const i=this.textStreamHandlers.get(e.topic);if(!i)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let n;const 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},r=new ReadableStream({start:t=>{n=t,this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now()})}});i(new Hh(s,r,Xl(e.totalLength)),{identity:t})}}))}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return pc(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=hu())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),El(200)])}catch(n){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:n}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Ld.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var i;let n;return n=t?cp.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new cp(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?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)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Ld.ParticipantConnected,i),i.on(jd.TrackPublished,(e=>{this.emitWhenConnected(Ld.TrackPublished,e,i)})).on(jd.TrackSubscribed,((e,t)=>{e.kind===ll.Kind.Audio?(e.on(Vd.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Vd.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===ll.Kind.Video&&(e.on(Vd.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Vd.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Ld.TrackSubscribed,e,t,i)})).on(jd.TrackUnpublished,(e=>{this.emit(Ld.TrackUnpublished,e,i)})).on(jd.TrackUnsubscribed,((e,t)=>{this.emit(Ld.TrackUnsubscribed,e,t,i)})).on(jd.TrackMuted,(e=>{this.emitWhenConnected(Ld.TrackMuted,e,i)})).on(jd.TrackUnmuted,(e=>{this.emitWhenConnected(Ld.TrackUnmuted,e,i)})).on(jd.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(Ld.ParticipantMetadataChanged,e,i)})).on(jd.ParticipantNameChanged,(e=>{this.emitWhenConnected(Ld.ParticipantNameChanged,e,i)})).on(jd.AttributesChanged,(e=>{this.emitWhenConnected(Ld.ParticipantAttributesChanged,e,i)})).on(jd.ConnectionQualityChanged,(e=>{this.emitWhenConnected(Ld.ConnectionQualityChanged,e,i)})).on(jd.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(Ld.ParticipantPermissionsChanged,e,i)})).on(jd.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(Ld.TrackSubscriptionStatusChanged,e,t,i)})).on(jd.TrackSubscriptionFailed,((e,t)=>{this.emit(Ld.TrackSubscriptionFailed,e,i,t)})).on(jd.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(Ld.TrackSubscriptionPermissionChanged,e,t,i)})),t&&i.updateInfo(t),i}sendSyncState(){const 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(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&ou(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=al.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,ma.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&al.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Ld.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=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===Uh.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Uh.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return pc(this,void 0,void 0,(function*(){var t,i;const n=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 ya({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:zs.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Ta({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Ld.SignalConnected),this.emit(Ld.Connected),this.setAndEmitConnectionState(Uh.Connected),n.video){const e=new np(ll.Kind.Video,new Pa({source:la.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:da.AUDIO,name:"video-dummy"}),new Ch(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Hl(160*(null!==(t=s.aspectRatios[0])&&void 0!==t?t: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(jd.LocalTrackPublished,e)}if(n.audio){const e=new np(ll.Kind.Audio,new Pa({source:la.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:da.AUDIO}),new uh(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Gl(),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(jd.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new Ta({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Sa.ACTIVE,tracks:[],joinedAt:zs.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=Hl(160*(null!==(i=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),a=new Pa({source:la.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:da.AUDIO});n.addSubscribedMediaTrack(r,a.sid,new MediaStream([r]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(s.audio){const e=Gl(),i=new Pa({source:la.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:da.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==Ld.ActiveSpeakersChanged&&e!==Ld.TranscriptionReceived){const t=lp(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function lp(e){return e.map((e=>{if(e)return Array.isArray(e)?lp(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}dp.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()})),(Bh=Fh||(Fh={}))[Bh.IDLE=0]="IDLE",Bh[Bh.RUNNING=1]="RUNNING",Bh[Bh.SKIPPED=2]="SKIPPED",Bh[Bh.SUCCESS=3]="SUCCESS",Bh[Bh.FAILED=4]="FAILED",vc.EventEmitter,vc.EventEmitter;const up=Object.freeze(Object.defineProperty({__proto__:null,ObiSession:class{constructor(e={}){this.currentState=Rn.READY,this.assistantAudioContext=null,this.userAudioContext=null,this.emitter=Ss(),this.apiBaseUrl=e.apiBaseUrl||"/api",this.token=e.token}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async connect(e={}){if(this.token=e.token??this.token??new URLSearchParams(window.location.search).get("token")??void 0,!this.token)return console.error("No token found"),void this.emitter.emit("error",{session:this,error:new Error("No session token provided")});await this.requestMicrophone();try{this.room=new dp({adaptiveStream:!0,dynacast:!0}),this.room.on(Ld.LocalTrackUnpublished,(e=>{console.log("Local track unpublished",e.source),e.source===ll.Source.ScreenShare&&(this.screenStream=void 0)})),this.room.on(Ld.Disconnected,(()=>{console.log("LiveKit room disconnected"),this.disconnect()})),this.room.on(Ld.ParticipantDisconnected,(()=>{this.disconnect()})),this.room.on(Ld.TrackSubscribed,((e,t,i)=>{if("audio"===e.kind&&e.attach(),e.source===ll.Source.Microphone&&i.identity.includes("agent-")){const t=e.mediaStream;if(!t)return void console.error("No media stream available for assistant track");const i=new AudioContext,n=i.createAnalyser();i.createMediaStreamSource(t).connect(n),n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,s,"ASSISTANT"),this.assistantAudioContext=i}})),this.room.on(Ld.ParticipantAttributesChanged,(e=>{if(!e["lk.agent.state"])return;if(this.currentState===Rn.RESEARCHING||this.currentState===Rn.PAUSED)return;const t=Ge(e["lk.agent.state"]).with("listening",(()=>Rn.USER_SPEAKING)).with("speaking",(()=>Rn.AGENT_SPEAKING)).with("thinking",(()=>Rn.AGENT_SPEAKING)).otherwise((()=>{}));t&&this.setState(t)})),this.room.on(Ld.DataReceived,(async e=>{try{const t=JSON.parse((new TextDecoder).decode(e));Ge(t.status||t.request).with("using_tool",(()=>{const e=this.currentState;this.currentState=Rn.RESEARCHING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:e})})).with("using_tool_ended",(()=>{const e=this.currentState;this.currentState=Rn.AGENT_SPEAKING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:e})})).with("share_screen",(()=>{this.shareScreen()})).with("prompt_user",(()=>{this.promptContinue()})).with("capture_page_html",(()=>{this.emitter.emit("capturePageHTML",{session:this})})).otherwise((()=>{console.warn("Unknown data received:",t)}))}catch(t){console.error("Error parsing data:",t)}}));const e=`${this.apiBaseUrl}/join-token?token=${this.token}`,t=await fetch(e).then((e=>e.json()));if(await this.room.connect(t.url,t.token),this.microphoneStream){const e=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(e,{name:"microphone",source:ll.Source.Microphone})}}catch(t){throw console.error("Failed to connect to LiveKit:",t),this.disconnect(),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))}),t}}disconnect(){this.room&&this.room.disconnect(!0),this.screenStream?.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach((e=>e.stop())),this.setState(Rn.READY)}setState(e){if(e===this.currentState)return;const t=this.currentState;this.currentState=e,this.emitter.emit("stateChanged",{session:this,newState:e,oldState:t})}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const i=t.createAnalyser(),n=t.createMediaStreamSource(e),s=t.createGain();s.gain.value=1.5,n.connect(s),s.connect(i),i.fftSize=2048;const r=new Uint8Array(i.frequencyBinCount);this.analyzeAudio(i,r,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){this.emitter.emit("preScreenShare",{session:this});try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream)return void console.warn("Failed to share screen");await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",{session:this,error:e instanceof Error?e:new Error(String(e))})}}pauseRecording(){this.room&&(this.setState(Rn.PAUSED),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleMuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!1))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!1)),this.screenStream?.track?.mute(),this.userAudioContext&&this.userAudioContext.resume(),this.assistantAudioContext&&this.assistantAudioContext.resume())}resumeRecording(){this.room&&(this.setState(Rn.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleUnmuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!0))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!0)),this.screenStream?.track?.unmute())}async promptContinue(){await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,i){e.getByteFrequencyData(t);const n=t.reduce(((e,t)=>e+t),0)/t.length,s=Math.max(.01,Math.min(1,n/128));"USER"===i&&this.currentState===Rn.USER_SPEAKING?this.emitter.emit("volume",{speaker:"USER",spectrum:Array.from(t),volume:s}):"ASSISTANT"===i&&this.currentState===Rn.AGENT_SPEAKING&&this.emitter.emit("volume",{speaker:"ASSISTANT",spectrum:Array.from(t),volume:s}),setTimeout((()=>this.analyzeAudio(e,t,i)),50)}async sendHTML(e){if(this.room)try{const t={type:"page_content",html:e,timestamp:(new Date).toISOString()},i=JSON.stringify(t),n=(new TextEncoder).encode(i);await this.room.localParticipant.publishData(n,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))})}else console.log("Cannot send HTML: Not connected to LiveKit room")}}},Symbol.toStringTag,{value:"Module"}));return e.EventType=Pn,e.ObiAssistant=class{static init(e){customElements.get("obi-widget")||customElements.define("obi-widget",Ts);const t=document.createElement("obi-widget");return e.apiKey&&(t.apiKey=e.apiKey),e.position&&(t.position=e.position),e.user&&(t.user=e.user),window.obiWidgetConfig=e,document.body.appendChild(t),console.log("Obi Widget initialized and mounted"),t}},e.ObiSDK=class{constructor(e={}){this.state=Rn.READY,this.emitter=Ss(),this.voiceEnabled=!1,this.screenCaptureEnabled=!1,this.config=_n.parse(e),this.config.debug&&console.log("ObiSDK initialized with config:",this.config)}async init(){try{this.config.enableVoice&&await this.initVoice(),this.config.enableScreenCapture&&await this.initScreenCapture(),this.setState(Rn.READY),this.emitter.emit(Pn.READY),this.config.debug&&console.log("ObiSDK ready")}catch(e){const t={code:"init_failed",message:"Failed to initialize SDK",details:e};this.handleError(t)}}async initVoice(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getUserMedia)throw new Error("Voice recording not supported in this browser");try{await window.navigator.mediaDevices.getUserMedia({audio:!0}),this.voiceEnabled=!0,this.config.debug&&console.log("Voice capabilities initialized")}catch(e){throw new Error(`Microphone access denied: ${e}`)}}async initScreenCapture(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getDisplayMedia)throw new Error("Screen capture not supported in this browser");this.screenCaptureEnabled=!0,this.config.debug&&console.log("Screen capture capabilities initialized")}setState(e){this.state=e,this.emitter.emit(Pn.STATE_CHANGE,e)}handleError(e){this.setState(Rn.ERROR),this.emitter.emit(Pn.ERROR,e),this.config.debug&&console.error("ObiSDK error:",e)}async startVoiceRecording(){if(this.voiceEnabled)try{this.setState(Rn.AGENT_SPEAKING),this.emitter.emit(Pn.VOICE_START),this.config.debug&&console.log("Voice recording started")}catch(e){this.handleError({code:"voice_start_failed",message:"Failed to start voice recording",details:e})}else this.handleError({code:"voice_disabled",message:"Voice recording is not enabled or available"})}async stopVoiceRecording(){if(this.state===Rn.READY)return{transcript:void 0};try{const e={transcript:"Sample transcript"};return this.setState(Rn.READY),this.emitter.emit(Pn.VOICE_STOP,e),this.config.debug&&console.log("Voice recording stopped:",e),e}catch(e){return this.handleError({code:"voice_stop_failed",message:"Failed to stop voice recording",details:e}),{transcript:void 0}}}async startScreenCapture(){if(this.screenCaptureEnabled)try{this.setState(Rn.AGENT_SPEAKING),this.emitter.emit(Pn.SCREEN_CAPTURE_START),this.config.debug&&console.log("Screen capture started")}catch(e){this.handleError({code:"screen_capture_start_failed",message:"Failed to start screen capture",details:e})}else this.handleError({code:"screen_capture_disabled",message:"Screen capture is not enabled or available"})}async stopScreenCapture(){if(this.state===Rn.READY)return{screenshot:void 0};try{const e={screenshot:"data:image/png;base64,..."};return this.setState(Rn.READY),this.emitter.emit(Pn.SCREEN_CAPTURE_STOP,e),this.config.debug&&console.log("Screen capture stopped"),e}catch(e){return this.handleError({code:"screen_capture_stop_failed",message:"Failed to stop screen capture",details:e}),{screenshot:void 0}}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getState(){return this.state}dispose(){this.emitter.all.clear(),this.config.debug&&console.log("ObiSDK disposed")}},e.ObiWidget=Ts,e.SDKState=Rn,e.initObi=async e=>{const{ObiAssistant:t}=await(async()=>{return e=await new Promise((e=>{try{const t=new XMLHttpRequest;t.open("GET","https://registry.npmjs.org/obi-sdk/latest"),t.onload=()=>{if(200===t.status)try{const i=JSON.parse(t.responseText);e(i.version)}catch(i){e(null)}else e(null)},t.onerror=()=>e(null),t.send()}catch(t){e(null)}})),new Promise(((t,i)=>{if(window.ObiAssistant)return void t({ObiAssistant:window.ObiAssistant,ObiSDK:window.ObiSDK,createSession:window.ObiSDK?.createSession});const n=document.createElement("script"),s=e||"latest";n.src=`${Cs}@${s}/dist/obi-sdk.standalone.iife.js`,n.type="text/javascript",n.async=!0,n.onload=()=>{t({ObiAssistant:window.ObiAssistant,ObiSDK:window.ObiSDK,createSession:window.ObiSDK?.createSession})},n.onerror=()=>{"latest"!==s?(console.warn("Failed to load specific version, falling back to latest"),n.src=`${Cs}@latest/dist/obi-sdk.standalone.iife.js`,n.onload=()=>{t({ObiAssistant:window.ObiAssistant,ObiSDK:window.ObiSDK,createSession:window.ObiSDK?.createSession})}):i(new Error("Failed to load Obi SDK from CDN"))},document.head.appendChild(n)}));var e})();if(!t)throw new Error("Obi SDK loaded but ObiAssistant not found");return t.init(e)},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
530
+ `,ks([ue({type:String})],Ts.prototype,"apiBaseUrl",2),ks([ue({type:String})],Ts.prototype,"apiKey",2),ks([ue({type:String})],Ts.prototype,"position",2),ks([ue({type:Object})],Ts.prototype,"user",2),ks([he()],Ts.prototype,"state",2),ks([he()],Ts.prototype,"showCourseModal",2),ks([he()],Ts.prototype,"isHovering",2),ks([he()],Ts.prototype,"navVisible",2),ks([he()],Ts.prototype,"activeSession",2),ks([he()],Ts.prototype,"volume",2),customElements.get("obi-widget")||customElements.define("obi-widget",Ts);const Cs="https://unpkg.com/obi-sdk",ws=window;function Es(e,t,i){ws.__obiSDKLoading=!0;const n=document.createElement("script");n.type="text/javascript",n.async=!0;const s=e||"latest";n.src=`${Cs}@${s}/dist/obi-sdk.standalone.iife.js`,n.onload=t,n.onerror=()=>{"latest"!==s?(console.warn("Failed to load specific version, falling back to latest"),n.src=`${Cs}@latest/dist/obi-sdk.standalone.iife.js`,n.onload=t):(ws.__obiSDKLoading=!1,i(new Error("Failed to load Obi SDK from CDN")))},document.head.appendChild(n)}function _s(e){const t=document,i=t.querySelector("obi-widget");if(i)return console.log("Obi Widget already exists on the page"),i;if(!customElements.get("obi-widget"))throw new Error("Obi Widget component not registered - SDK may not have loaded properly");const n=t.createElement("obi-widget");return e.apiKey&&n.setAttribute("api-key",e.apiKey),e.position&&n.setAttribute("position",e.position),e.user&&n.setAttribute("user",JSON.stringify(e.user)),t.body.appendChild(n),console.log("Obi Widget added to page"),n}function Ps(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}ws.__obiSDKLoading=ws.__obiSDKLoading||!1;var Rs=Object.defineProperty,xs=(e,t,i)=>((e,t,i)=>t in e?Rs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Is{constructor(){xs(this,"_locking"),xs(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function Os(e,t){if(!e)throw new Error(t)}function As(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function Ns(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function Ds(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const Ms=Symbol("@bufbuild/protobuf/enum-type");function Ls(e,t,i,n){e[Ms]=Us(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function Us(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const a of t){const e=js(a);r.push(e),n[a.name]=e,s[a.no]=e}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function js(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class Fs{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(n){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(n instanceof Error?n.message:String(n)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Bs(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function $s(e,t,i){for(let r=0;r<28;r+=7){const n=e>>>r,s=!(n>>>7==0&&0==t),a=255&(s?128|n:n);if(i.push(a),!s)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const Vs=4294967296;function qs(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const a=Number(e.slice(t,r));s*=i,n=n*i+a,n>=Vs&&(s+=n/Vs|0,n%=Vs)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?Hs(n,s):Zs(n,s)}function Ks(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(Vs*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,a=2*n;const o=1e7;return s>=o&&(r+=Math.floor(s/o),s%=o),r>=o&&(a+=Math.floor(r/o),r%=o),a.toString()+zs(r)+zs(s)}function Zs(e,t){return{lo:0|e,hi:0|t}}function Hs(e,t){return t=~t,e?e=1+~e:t+=1,Zs(e,t)}const zs=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Gs(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 Ws(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let i=5;128&e&&i<10;i++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const Js=function(){const 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 process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new 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))}}const t=e=>Os(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>Os(/^[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),qs(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),qs(e)),dec:(e,t)=>function(e,t){let i=Zs(e,t);const n=2147483648&i.hi;n&&(i=Hs(i.lo,i.hi));const s=Ks(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>Ks(e,t)}}();var Qs,Ys,Xs,er,tr,ir;function nr(e,t,i){if(t===i)return!0;if(e==Qs.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(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 Qs.UINT64:case Qs.FIXED64:case Qs.INT64:case Qs.SFIXED64:case Qs.SINT64:return t==i}return!1}function sr(e,t){switch(e){case Qs.BOOL:return!1;case Qs.UINT64:case Qs.FIXED64:case Qs.INT64:case Qs.SFIXED64:case Qs.SINT64:return 0==t?Js.zero:"0";case Qs.DOUBLE:case Qs.FLOAT:return 0;case Qs.BYTES:return new Uint8Array(0);case Qs.STRING:return"";default:return 0}}function rr(e,t){switch(e){case Qs.BOOL:return!1===t;case Qs.STRING:return""===t;case Qs.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(Ys=Qs||(Qs={}))[Ys.DOUBLE=1]="DOUBLE",Ys[Ys.FLOAT=2]="FLOAT",Ys[Ys.INT64=3]="INT64",Ys[Ys.UINT64=4]="UINT64",Ys[Ys.INT32=5]="INT32",Ys[Ys.FIXED64=6]="FIXED64",Ys[Ys.FIXED32=7]="FIXED32",Ys[Ys.BOOL=8]="BOOL",Ys[Ys.STRING=9]="STRING",Ys[Ys.BYTES=12]="BYTES",Ys[Ys.UINT32=13]="UINT32",Ys[Ys.SFIXED32=15]="SFIXED32",Ys[Ys.SFIXED64=16]="SFIXED64",Ys[Ys.SINT32=17]="SINT32",Ys[Ys.SINT64=18]="SINT64",(er=Xs||(Xs={}))[er.BIGINT=0]="BIGINT",er[er.STRING=1]="STRING",(ir=tr||(tr={}))[ir.Varint=0]="Varint",ir[ir.Bit64=1]="Bit64",ir[ir.LengthDelimited=2]="LengthDelimited",ir[ir.StartGroup=3]="StartGroup",ir[ir.EndGroup=4]="EndGroup",ir[ir.Bit32=5]="Bit32";class ar{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 n=0;n<this.chunks.length;n++)e+=this.chunks[n].length;let t=new Uint8Array(e),i=0;for(let n=0;n<this.chunks.length;n++)t.set(this.chunks[n],i),i+=this.chunks[n].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ns(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return As(e),Gs(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Ds(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){Ns(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){As(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return As(e),Gs(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=Js.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=Js.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=Js.enc(e);return $s(t.lo,t.hi,this.buf),this}sint64(e){let t=Js.enc(e),i=t.hi>>31;return $s(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=Js.uEnc(e);return $s(t.lo,t.hi,this.buf),this}}class or{constructor(e,t){this.varint64=Bs,this.uint32=Ws,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;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case tr.Varint:for(;128&this.buf[this.pos++];);break;case tr.Bit64:this.pos+=4;case tr.Bit32:this.pos+=4;break;case tr.LengthDelimited:let i=this.uint32();this.pos+=i;break;case tr.StartGroup:for(;;){const[e,i]=this.tag();if(i===tr.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return Js.dec(...this.varint64())}uint64(){return Js.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,Js.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 Js.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Js.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 cr(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const 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 sr(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let dr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),lr=[];for(let gp=0;gp<dr.length;gp++)lr[dr[gp].charCodeAt(0)]=gp;lr["-".charCodeAt(0)]=dr.indexOf("+"),lr["_".charCodeAt(0)]=dr.indexOf("/");const ur={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,a=0;for(let o=0;o<e.length;o++){if(i=lr[e.charCodeAt(o)],void 0===i)switch(e[o]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:a=i,r=1;break;case 1:n[s++]=a<<2|(48&i)>>4,a=i,r=2;break;case 2:n[s++]=(15&a)<<4|(60&i)>>2,a=i,r=3;break;case 3:n[s++]=(3&a)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=dr[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=dr[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=dr[s|t>>6],i+=dr[63&t],n=0}return n&&(i+=dr[s],i+="=",1==n&&(i+="=")),i}};function hr(e,t,i){gr(t,e);const n=t.runtime.bin.makeReadOptions(i),s=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,a]=cr(t);for(const o of s)t.runtime.bin.readField(r,n.readerFactory(o.data),t.field,o.wireType,n);return a()}function pr(e,t,i,n){gr(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(mr(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const a=r.writerFactory();let 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,a,r);const c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function mr(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function gr(e,t){Os(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function fr(e,t){const 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":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!rr(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function vr(e,t){const 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?sr(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function yr(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(Fs.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function br(e,t){return yr(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}Qs.DOUBLE,Qs.FLOAT,Qs.INT64,Qs.UINT64,Qs.INT32,Qs.UINT32,Qs.BOOL,Qs.STRING,Qs.BYTES;const kr={ignoreUnknownFields:!1},Tr={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};const Sr=Symbol(),Cr=Symbol();function wr(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 Er(e,t,i,n,s){let r=i.localName;if(i.repeated){if(Os("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(wr(t)));const o=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(wr(e)));switch(i.kind){case"message":o.push(i.T.fromJson(e,n));break;case"enum":const t=Rr(i.T,e,n.ignoreUnknownFields,!0);t!==Cr&&o.push(t);break;case"scalar":try{o.push(Pr(i.T,e,i.L,!0))}catch(a){let t="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(wr(e));throw a instanceof Error&&a.message.length>0&&(t+=": ".concat(a.message)),new Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(wr(t)));const o=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let c;try{c=_r(i.K,e)}catch(a){let e="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(wr(t));throw a instanceof Error&&a.message.length>0&&(e+=": ".concat(a.message)),new Error(e)}switch(i.V.kind){case"message":o[c]=i.V.T.fromJson(r,n);break;case"enum":const e=Rr(i.V.T,r,n.ignoreUnknownFields,!0);e!==Cr&&(o[c]=e);break;case"scalar":try{o[c]=Pr(i.V.T,r,Xs.BIGINT,!0)}catch(a){let e="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(wr(t));throw a instanceof Error&&a.message.length>0&&(e+=": ".concat(a.message)),new Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const o=i.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let c=e[r];yr(c)?c.fromJson(t,n):(e[r]=c=o.fromJson(t,n),o.fieldWrapper&&!i.oneof&&(e[r]=o.fieldWrapper.unwrapField(c)));break;case"enum":const d=Rr(i.T,t,n.ignoreUnknownFields,!1);switch(d){case Sr:vr(i,e);break;case Cr:break;default:e[r]=d}break;case"scalar":try{const n=Pr(i.T,t,i.L,!1);n===Sr?vr(i,e):e[r]=n}catch(a){let e="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(wr(t));throw a instanceof Error&&a.message.length>0&&(e+=": ".concat(a.message)),new Error(e)}}}function _r(e,t){if(e===Qs.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return Pr(e,t,Xs.BIGINT,!0).toString()}function Pr(e,t,i,n){if(null===t)return n?sr(e,i):Sr;switch(e){case Qs.DOUBLE:case Qs.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==Qs.FLOAT&&Ds(n),n;case Qs.INT32:case Qs.FIXED32:case Qs.SFIXED32:case Qs.SINT32:case Qs.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==Qs.UINT32||e==Qs.FIXED32?Ns(r):As(r),r;case Qs.INT64:case Qs.SFIXED64:case Qs.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=Js.parse(t);return i?a.toString():a;case Qs.FIXED64:case Qs.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=Js.uParse(t);return i?o.toString():o;case Qs.BOOL:if("boolean"!=typeof t)break;return t;case Qs.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(s){throw new Error("invalid UTF8")}return t;case Qs.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ur.dec(t)}throw new Error}function Rr(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:Sr;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return Cr}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(wr(t)))}function xr(e){return!(!e.repeated&&"map"!=e.kind&&(e.oneof||"message"==e.kind||e.opt||e.req))}function Ir(e,t,i){if("map"==e.kind){Os("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[i,r]of s)n[i.toString()]=Ar(e.V.T,r);break;case"message":for(const[e,r]of s)n[e.toString()]=r.toJson(i);break;case"enum":const t=e.V.T;for(const[e,r]of s)n[e.toString()]=Or(t,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){Os(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(Ar(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(Or(e.T,t[s],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 Ar(e.T,t);case"enum":return Or(e.T,t,i.enumAsInteger);case"message":return br(e.T,t).toJson(i)}}function Or(e,t,i){var n;if(Os("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function Ar(e,t){switch(e){case Qs.INT32:case Qs.SFIXED32:case Qs.SINT32:case Qs.FIXED32:case Qs.UINT32:return Os("number"==typeof t),t;case Qs.FLOAT:case Qs.DOUBLE:return Os("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case Qs.STRING:return Os("string"==typeof t),t;case Qs.BOOL:return Os("boolean"==typeof t),t;case Qs.UINT64:case Qs.FIXED64:case Qs.INT64:case Qs.SFIXED64:case Qs.SINT64:return Os("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case Qs.BYTES:return Os(t instanceof Uint8Array),ur.enc(t)}}const Nr=Symbol("@bufbuild/protobuf/unknown-fields"),Dr={readUnknownFields:!0,readerFactory:e=>new or(e)},Mr={writeUnknownFields:!0,writerFactory:()=>new ar};function Lr(e,t,i,n,s){let{repeated:r,localName:a}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=a&&delete e.value,e.case=a,a="value"),i.kind){case"scalar":case"enum":const o="enum"==i.kind?Qs.INT32:i.T;let c=Fr;if("scalar"==i.kind&&i.L>0&&(c=jr),r){let i=e[a];if(n==tr.LengthDelimited&&o!=Qs.STRING&&o!=Qs.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,o))}else i.push(c(t,o))}else e[a]=c(t,o);break;case"message":const d=i.T;r?e[a].push(Ur(t,new d,s,i)):yr(e[a])?Ur(t,e[a],s,i):(e[a]=Ur(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[a]=d.fieldWrapper.unwrapField(e[a])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,a;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=Fr(t,e.K);break;case 2:switch(e.V.kind){case"scalar":a=Fr(t,e.V.T);break;case"enum":a=t.int32();break;case"message":a=Ur(t,new e.V.T,i,void 0)}}}if(void 0===r&&(r=sr(e.K,Xs.BIGINT)),"string"!=typeof r&&"number"!=typeof r&&(r=r.toString()),void 0===a)switch(e.V.kind){case"scalar":a=sr(e.V.T,Xs.BIGINT);break;case"enum":a=e.V.T.values[0].no;break;case"message":a=new e.V.T}return[r,a]}(i,t,s);e[a][l]=u}}function Ur(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function jr(e,t){const i=Fr(e,t);return"bigint"==typeof i?i.toString():i}function Fr(e,t){switch(t){case Qs.STRING:return e.string();case Qs.BOOL:return e.bool();case Qs.DOUBLE:return e.double();case Qs.FLOAT:return e.float();case Qs.INT32:return e.int32();case Qs.INT64:return e.int64();case Qs.UINT64:return e.uint64();case Qs.FIXED64:return e.fixed64();case Qs.BYTES:return e.bytes();case Qs.FIXED32:return e.fixed32();case Qs.SFIXED32:return e.sfixed32();case Qs.SFIXED64:return e.sfixed64();case Qs.SINT64:return e.sint64();case Qs.UINT32:return e.uint32();case Qs.SINT32:return e.sint32()}}function Br(e,t,i,n){Os(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?Qs.INT32:e.T;if(s)if(Os(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,tr.LengthDelimited).fork();let[,s]=Kr(t);for(let r=0;r<n.length;r++)e[s](n[r]);e.join()}(i,r,e.no,t);else for(const n of t)qr(i,r,e.no,n);else qr(i,r,e.no,t);break;case"message":if(s){Os(Array.isArray(t));for(const s of t)Vr(i,n,e,s)}else Vr(i,n,e,t);break;case"map":Os("object"==typeof t&&null!=t);for(const[s,a]of Object.entries(t))$r(i,n,e,s,a)}}function $r(e,t,i,n,s){e.tag(i.no,tr.LengthDelimited),e.fork();let r=n;switch(i.K){case Qs.INT32:case Qs.FIXED32:case Qs.UINT32:case Qs.SFIXED32:case Qs.SINT32:r=Number.parseInt(n);break;case Qs.BOOL:Os("true"==n||"false"==n),r="true"==n}switch(qr(e,i.K,1,r),i.V.kind){case"scalar":qr(e,i.V.T,2,s);break;case"enum":qr(e,Qs.INT32,2,s);break;case"message":Os(void 0!==s),e.tag(2,tr.LengthDelimited).bytes(s.toBinary(t))}e.join()}function Vr(e,t,i,n){const s=br(i.T,n);i.delimited?e.tag(i.no,tr.StartGroup).raw(s.toBinary(t)).tag(i.no,tr.EndGroup):e.tag(i.no,tr.LengthDelimited).bytes(s.toBinary(t))}function qr(e,t,i,n){Os(void 0!==n);let[s,r]=Kr(t);e.tag(i,s)[r](n)}function Kr(e){let t=tr.Varint;switch(e){case Qs.BYTES:case Qs.STRING:t=tr.LengthDelimited;break;case Qs.DOUBLE:case Qs.FIXED64:case Qs.SFIXED64:t=tr.Bit64;break;case Qs.FIXED32:case Qs.SFIXED32:case Qs.FLOAT:t=tr.Bit32}return[t,Qs[e].toLowerCase()]}function Zr(e){if(void 0===e)return e;if(yr(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Hr(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class zr{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const 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){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Gr(e,t){const i=Jr(e);return t?i:ta(ea(i))}const Wr=Jr;function Jr(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){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(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const Qr=new Set(["constructor","toString","toJSON","valueOf"]),Yr=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Xr=e=>"".concat(e,"$"),ea=e=>Yr.has(e)?Xr(e):e,ta=e=>Qr.has(e)?Xr(e):e;class ia{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=Gr(e,!1)}addField(e){Os(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]}}const na=(sa=e=>new zr(e,(e=>function(e){var t,i,n,s,r,a;const o=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Gr(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Wr(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:Xs.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(r=d.req)&&void 0!==r&&r,e.opt=null!==(a=d.opt)&&void 0!==a&&a,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=Qs.BYTES&&d.T!=Qs.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new ia(t)),e.oneof=c,c.addField(e)}o.push(e)}return o}(e))),ra=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=sr(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},kr),e):kr},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},Tr),e):Tr},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(wr(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[a,o]of Object.entries(t)){const t=e.fields.findJsonName(a);if(t){if(t.oneof){if(null===o&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(a,'"'));s.set(t.oneof,a)}Er(n,o,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&a.startsWith("[")&&a.endsWith("]")){const s=r.findExtension(a.substring(1,a.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=cr(s);Er(e,o,s.field,i,s),pr(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!fr(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!xr(s))continue}const i=Ir(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const a=r.findExtensionFor(i.typeName,s.no);if(a&&mr(e,a)){const i=hr(e,a,t),s=Ir(a.field,i,t);void 0!==s&&(n[a.field.jsonName]=s)}}}catch(r){const e=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw new Error(e+(t.length>0?": ".concat(t):""))}return n},readScalar:(e,t,i)=>Pr(e,t,null!=i?i:Xs.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||rr(e,t)?Ar(e,t):void 0},debug:wr},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},Dr),e):Dr},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},Mr),e):Mr},listUnknownFields(e){var t;return null!==(t=e[Nr])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Nr]},writeUnknownFields(e,t){const i=e[Nr];if(i)for(const n of i)t.tag(n.no,n.wireType).raw(n.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[Nr])||(s[Nr]=[]),s[Nr].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),a=s?t.len:t.pos+i;let o,c;for(;t.pos<a&&([o,c]=t.tag(),!0!==s||c!=tr.EndGroup);){const i=r.fields.find(o);if(i)Lr(e,t,i,c,n);else{const i=t.skip(c,o);n.readUnknownFields&&this.onUnknownField(e,o,c,i)}}if(s&&(c!=tr.EndGroup||o!==i))throw new Error("invalid end group tag")},readField:Lr,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(fr(s,e))Br(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&Br(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:Ls,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let a=r[i].value;t&&"message"==t.kind&&!yr(a,t.T)?a=new t.T(a):t&&"scalar"===t.kind&&t.T===Qs.BYTES&&(a=Hr(a)),s[i]={case:e,value:a};break;case"scalar":case"enum":let o=r[i];n.T===Qs.BYTES&&(o=n.repeated?o.map(Hr):Hr(o)),s[i]=o;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===Qs.BYTES)for(const[t,n]of Object.entries(r[i]))s[i][t]=Hr(n);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((e=>yr(e,c)?e:new c(e)));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=Hr(e):s[i]=e:s[i]=yr(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>nr(e.T,t,s[i])));case"enum":return n.every(((e,t)=>nr(Qs.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(n,s);case"enum":return nr(Qs.INT32,n,s);case"scalar":return nr(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const t=e.findField(n.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(n.value,s.value);case"enum":return nr(Qs.INT32,n.value,s.value);case"scalar":return nr(t.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const i=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return i.every((e=>t.equals(n[e],s[e])));case"enum":return i.every((e=>nr(Qs.INT32,n[e],s[e])));case"scalar":const r=e.V.T;return i.every((e=>nr(r,n[e],s[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const s of t.fields.byMember()){const t=e[s.localName];let i;if(s.repeated)i=t.map(Zr);else if("map"==s.kind){i=n[s.localName];for(const[e,n]of Object.entries(t))i[e]=Zr(n)}else i="oneof"==s.kind?s.findField(t.case)?{case:t.case,value:Zr(t.value)}:{case:void 0}:Zr(t);n[s.localName]=i}for(const s of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return i}}),{newFieldList:sa,initFields:ra}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),a={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(a.prototype,new Fs),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new a).fromBinary(e,t),fromJson:(e,t)=>(new a).fromJson(e,t),fromJsonString:(e,t)=>(new a).fromJsonString(e,t),equals:(t,i)=>e.util.equals(a,t,i)}),a}(this,e,t,i)},makeEnum:function(e,t,i){const n={};for(const s of t){const e=js(s);n[e.localName]=e.no,n[e.no]=e.localName}return Ls(n,e,t),n},makeEnumType:Us,getEnumType:function(e){const t=e[Ms];return Os(t,"missing enum type on enum object"),t},makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var sa,ra;class aa extends Fs{constructor(e){super(),this.seconds=Js.zero,this.nanos=0,na.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(na.json.debug(e)));const 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 new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const 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 new 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 new 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=Js.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new 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 new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const 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 aa.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new aa({seconds:Js.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new aa).fromBinary(e,t)}static fromJson(e,t){return(new aa).fromJson(e,t)}static fromJsonString(e,t){return(new aa).fromJsonString(e,t)}static equals(e,t){return na.util.equals(aa,e,t)}}aa.runtime=na,aa.typeName="google.protobuf.Timestamp",aa.fields=na.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const oa=na.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:aa},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:ca,repeated:!0},{no:5,name:"events",kind:"message",T:la,repeated:!0}])),ca=na.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:da,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),da=na.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:aa},{no:3,name:"value",kind:"scalar",T:2}])),la=na.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:aa},{no:7,name:"normalized_end_timestamp",kind:"message",T:aa,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),ua=na.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),ha=na.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),pa=na.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"}]),ma=na.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ga=na.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),fa=na.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),va=na.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"}]),ya=na.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"}]),ba=na.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ka=na.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"}]),Ta=na.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:Sa,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:Xa}])),Sa=na.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),Ca=na.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:na.getEnumType(pa),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}])),wa=na.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:na.getEnumType(Ea)},{no:4,name:"tracks",kind:"message",T:Ia,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:Ca},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:na.getEnumType(_a)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:na.getEnumType(va)},{no:18,name:"kind_details",kind:"enum",T:na.getEnumType(Pa),repeated:!0}])),Ea=na.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),_a=na.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Pa=na.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Ra=na.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),xa=na.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:Oa,repeated:!0}])),Ia=na.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:na.getEnumType(ha)},{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:na.getEnumType(pa)},{no:10,name:"layers",kind:"message",T:Oa,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:xa,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:na.getEnumType(Ra)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Xa},{no:19,name:"audio_features",kind:"enum",T:na.getEnumType(ka),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:na.getEnumType(ua)}])),Oa=na.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:na.getEnumType(ma)},{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}])),Aa=na.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:na.getEnumType(Na)},{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:La,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Da,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Ua,oneof:"value"},{no:7,name:"transcription",kind:"message",T:ja,oneof:"value"},{no:8,name:"metrics",kind:"message",T:oa,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Ba,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:$a,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Va,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:qa,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:no,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:so,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:ro,oneof:"value"}])),Na=na.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Da=na.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Ma,repeated:!0}])),Ma=na.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}])),La=na.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}])),Ua=na.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),ja=na.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:Fa,repeated:!0}])),Fa=na.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}])),Ba=na.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}])),$a=na.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}])),Va=na.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),qa=na.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:Ka,oneof:"value"}])),Ka=na.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}])),Za=na.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Ha=na.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:na.getEnumType(za)},{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}])),za=na.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Ga=na.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:na.getEnumType(Wa)},{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}])),Wa=na.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"}]),Ja=na.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Qa},{no:2,name:"screen",kind:"message",T:Qa},{no:3,name:"resume_connection",kind:"enum",T:na.getEnumType(fa)},{no:4,name:"disabled_codecs",kind:"message",T:Ya},{no:5,name:"force_relay",kind:"enum",T:na.getEnumType(fa)}])),Qa=na.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:na.getEnumType(fa)}])),Ya=na.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:Sa,repeated:!0},{no:2,name:"publish",kind:"message",T:Sa,repeated:!0}])),Xa=na.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),eo=na.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),to=na.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:na.getEnumType(eo)},{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"}),io=na.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),no=na.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:na.getEnumType(Ra)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:to,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:io,oneof:"content_header"}]),{localName:"DataStream_Header"}),so=na.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"}),ro=na.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"}),ao=na.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),oo=na.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),co=na.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),lo=na.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:ko,oneof:"message"},{no:2,name:"answer",kind:"message",T:ko,oneof:"message"},{no:3,name:"trickle",kind:"message",T:mo,oneof:"message"},{no:4,name:"add_track",kind:"message",T:po,oneof:"message"},{no:5,name:"mute",kind:"message",T:go,oneof:"message"},{no:6,name:"subscription",kind:"message",T:So,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Co,oneof:"message"},{no:8,name:"leave",kind:"message",T:_o,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Ro,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:$o,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:qo,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Zo,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:xo,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ho,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:wo,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Eo,oneof:"message"}])),uo=na.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:fo,oneof:"message"},{no:2,name:"answer",kind:"message",T:ko,oneof:"message"},{no:3,name:"offer",kind:"message",T:ko,oneof:"message"},{no:4,name:"trickle",kind:"message",T:mo,oneof:"message"},{no:5,name:"update",kind:"message",T:To,oneof:"message"},{no:6,name:"track_published",kind:"message",T:yo,oneof:"message"},{no:8,name:"leave",kind:"message",T:_o,oneof:"message"},{no:9,name:"mute",kind:"message",T:go,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Oo,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Ao,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Do,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Lo,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Fo,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Vo,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:bo,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:vo,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:zo,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Jo,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Qo,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Xo,oneof:"message"}])),ho=na.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),po=na.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:na.getEnumType(ha)},{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:na.getEnumType(pa)},{no:9,name:"layers",kind:"message",T:Oa,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:ho,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:na.getEnumType(Ra)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:na.getEnumType(ua)}])),mo=na.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:na.getEnumType(ao)},{no:3,name:"final",kind:"scalar",T:8}])),go=na.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),fo=na.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:Ta},{no:2,name:"participant",kind:"message",T:wa},{no:3,name:"other_participants",kind:"message",T:wa,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Io,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:Ja},{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:Ha},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Sa,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),vo=na.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Io,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Ja}])),yo=na.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Ia}])),bo=na.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),ko=na.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}])),To=na.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:wa,repeated:!0}])),So=na.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:Za,repeated:!0}])),Co=na.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:na.getEnumType(ma)},{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}])),wo=na.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:na.getEnumType(ka),repeated:!0}])),Eo=na.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}])),_o=na.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:na.getEnumType(va)},{no:3,name:"action",kind:"enum",T:na.getEnumType(Po)},{no:4,name:"regions",kind:"message",T:Go}])),Po=na.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Ro=na.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Oa,repeated:!0}])),xo=na.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}])),Io=na.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}])),Oo=na.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Ma,repeated:!0}])),Ao=na.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:Ta}])),No=na.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:na.getEnumType(ga)},{no:3,name:"score",kind:"scalar",T:2}])),Do=na.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:No,repeated:!0}])),Mo=na.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:na.getEnumType(oo)}])),Lo=na.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Mo,repeated:!0}])),Uo=na.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:na.getEnumType(ma)},{no:2,name:"enabled",kind:"scalar",T:8}])),jo=na.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Uo,repeated:!0}])),Fo=na.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Uo,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:jo,repeated:!0}])),Bo=na.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}])),$o=na.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Bo,repeated:!0}])),Vo=na.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}])),qo=na.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:ko},{no:2,name:"subscription",kind:"message",T:So},{no:3,name:"publish_tracks",kind:"message",T:yo,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ko,repeated:!0},{no:5,name:"offer",kind:"message",T:ko},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}])),Ko=na.makeMessageType("livekit.DataChannelInfo",(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:na.getEnumType(ao)}])),Zo=na.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:na.getEnumType(co),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"}])),Ho=na.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),zo=na.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Go=na.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Wo,repeated:!0}])),Wo=na.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}])),Jo=na.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:na.getEnumType(ba)}])),Qo=na.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:na.getEnumType(Yo)},{no:3,name:"message",kind:"scalar",T:9}])),Yo=na.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Xo=na.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));function ec(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var tc,ic,nc,sc,rc,ac,oc,cc,dc={exports:{}},lc=(tc||(tc=1,nc=dc.exports,sc=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"],s={},r=null;function a(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(n){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(),s=0;s<n.length;s++){var r=n[s];this[r]=s<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 d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?o:void 0!==console[n]?a(console,n):void 0!==console.log?a(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var a,o,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(r){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(r){}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 new 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||l,u.getLevel=function(){return null!=d?d:null!=o?o:a},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(s){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(s){}}}(d),c.call(u)},u.setDefaultLevel=function(e){o=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(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&&(a=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},a=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[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 s},r.default=r,r},(ic=dc).exports?ic.exports=sc():nc.log=sc()),dc.exports);(ac=rc||(rc={}))[ac.trace=0]="trace",ac[ac.debug=1]="debug",ac[ac.info=2]="info",ac[ac.warn=3]="warn",ac[ac.error=4]="error",ac[ac.silent=5]="silent",(cc=oc||(oc={})).Default="livekit",cc.Room="livekit-room",cc.Participant="livekit-participant",cc.Track="livekit-track",cc.Publication="livekit-track-publication",cc.Engine="livekit-engine",cc.Signal="livekit-signal",cc.PCManager="livekit-pc-manager",cc.PCTransport="livekit-pc-transport",cc.E2EE="lk-e2ee";let uc=lc.getLogger("livekit");function hc(e){const t=lc.getLogger(e);return t.setDefaultLevel(uc.getLevel()),t}Object.values(oc).map((e=>lc.getLogger(e))),uc.setDefaultLevel(rc.info);const pc=lc.getLogger("lk-e2ee"),mc=7e3,gc=[0,300,1200,2700,4800,mc,mc,mc,mc,mc];function fc(e,t,i,n){return new(i||(i=Promise))((function(s,r){function a(e){try{c(n.next(e))}catch(t){r(t)}}function o(e){try{c(n.throw(e))}catch(t){r(t)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,o)}c((n=n.apply(e,t||[])).next())}))}function vc(e){if(!Symbol.asyncIterator)throw new 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 new 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,s){!function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)}(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var yc,bc={exports:{}},kc=function(){if(yc)return bc.exports;yc=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 s(){s.init.call(this)}bc.exports=s,bc.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,r,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,s)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,r,c,d;if(a(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),(s=o(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new 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,d=l,console&&console.warn&&console.warn(d)}return e}function d(){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 l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.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=new 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)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(r){n.once&&e.removeEventListener(t,s),i(r)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),s.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},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return a(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,r,o;if(a(t),void 0===(n=this._events))return this;if(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(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){o=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.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 s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);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},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},bc.exports}();let Tc=!0,Sc=!0;function Cc(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function wc(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const 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),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const 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 Ec(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Tc=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function _c(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Sc=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Pc(){if("object"==typeof window){if(Tc)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Rc(e,t){Sc&&console.warn(e+" is deprecated, please use "+t+" instead.")}function xc(e){return"[object Object]"===Object.prototype.toString.call(e)}function Ic(e){return xc(e)?Object.keys(e).reduce((function(t,i){const n=xc(e[i]),s=n?Ic(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})}),{}):e}function Oc(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Oc(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Oc(e,e.get(t),i)}))})))}function Ac(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const 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&&Oc(e,i,s)}))})),s}const Nc=Pc;function Dc(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=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[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const 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});const a=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||a)){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 a=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!a&&i.length&&t.includes("back")&&(a=i[i.length-1]),a&&(e.video.deviceId=r.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=n(e.video),Nc("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return Nc("chrome: "+JSON.stringify(e)),s(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){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(r(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(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 Mc(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Lc(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){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});const 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};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),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};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else wc(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Uc(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const 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()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const 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))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const 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)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const 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 jc(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Ac(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),wc(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Ac(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Fc(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const 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};const 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")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const 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)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Bc(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Fc(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const 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]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.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||{},s.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");const 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||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const 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){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const 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)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=o.get.apply(this);return""===e.type?e:r(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){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");let t;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 $c(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function Vc(e,t){wc(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var qc=Object.freeze({__proto__:null,fixNegotiationNeeded:Vc,shimAddTrackRemoveTrack:Bc,shimAddTrackRemoveTrackWithNative:Fc,shimGetSendersWithDtmf:Uc,shimGetUserMedia:Dc,shimMediaStream:Mc,shimOnTrack:Lc,shimPeerConnection:$c,shimSenderReceiverGetStats:jc});function Kc(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Rc("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const 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&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Zc(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 Hc(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){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const 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(){const[e,s,r]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(n){if("TypeError"!==n.name)throw n;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(s,r)}}function zc(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const 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 Gc(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),wc(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Wc(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Rc("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Jc(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Qc(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{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 Yc(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Xc(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const 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 ed(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const 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 td=Object.freeze({__proto__:null,shimAddTransceiver:Qc,shimCreateAnswer:ed,shimCreateOffer:Xc,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){const 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:Yc,shimGetUserMedia:Kc,shimOnTrack:Zc,shimPeerConnection:Hc,shimRTCDataChannel:Jc,shimReceiverGetStats:Gc,shimRemoveStream:Wc,shimSenderGetStats:zc});function id(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)){const 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=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];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=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function nd(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);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const 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);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function sd(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let o=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=o,o=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=o,o=function(e,t,i){const n=a.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=o}function rd(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(ad(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function ad(e){return e&&void 0!==e.video?Object.assign({},e,{video:Ic(e.video)}):e}function od(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(Rc("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),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 cd(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 dd(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const 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);const 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 ld(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ud,hd=Object.freeze({__proto__:null,shimAudioContext:ld,shimCallbacksAPI:sd,shimConstraints:ad,shimCreateOfferLegacy:dd,shimGetUserMedia:rd,shimLocalStreamsAPI:id,shimRTCIceServerUrls:od,shimRemoteStreamsAPI:nd,shimTrackEventTransceiver:cd}),pd={exports:{}},md=(ud||(ud=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[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 n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const 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);const 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(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const 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(" ")}},t.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"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let s=0;s<n.length;s++)i=n[s].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const 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},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.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},t.parseSsrcMedia=function(e){const 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},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.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},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const 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}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.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},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],a=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(a){const n=t.parseRtpMap(a),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",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((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),o=a.length>0&&a[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===o&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:o,codecPayloadType:parseInt(e.parameters.apt,10)};o&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:o,mechanism:r?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&o&&i.push({ssrc:o});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},t.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},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const a=t.matchPrefix(e,"a=sctpmap:");if(a.length>0){const e=a[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.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("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"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]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(pd)),pd.exports),gd=ec(md),fd=Ps({__proto__:null,default:gd},[md]);function vd(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const 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){const i=new t(e),n=gd.parseCandidate(e.candidate);for(const 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,wc(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function yd(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||wc(e,"icecandidate",(e=>{if(e.candidate){const t=gd.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function bd(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}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{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(function(e){if(!e||!e.sdp)return!1;const t=gd.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=gd.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=gd.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function kd(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},wc(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Td(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const 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}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function Sd(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const 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 Cd(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const 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 wd(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const 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},!e.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 Ed=Object.freeze({__proto__:null,removeExtmapAllowMixed:Sd,shimAddIceCandidateNullOrEmpty:Cd,shimConnectionState:Td,shimMaxMessageSize:bd,shimParameterlessSetLocalDescription:wd,shimRTCIceCandidate:vd,shimRTCIceCandidateRelayProtocol:yd,shimSendThrowTypeError:kd});!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};const i=Pc,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=Cc(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Cc(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Cc(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:n,commonShim:Ed,extractVersion:Cc,disableLog:Ec,disableWarnings:_c,sdp:fd};switch(n.browser){case"chrome":if(!qc||!$c||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=qc,Cd(e,n),wd(e),Dc(e,n),Mc(e),$c(e,n),Lc(e),Bc(e,n),Uc(e),jc(e),Vc(e,n),vd(e),yd(e),Td(e),bd(e,n),kd(e),Sd(e,n);break;case"firefox":if(!td||!Hc||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=td,Cd(e,n),wd(e),Kc(e,n),Hc(e,n),Zc(e),Wc(e),zc(e),Gc(e),Jc(e),Qc(e),Yc(e),Xc(e),ed(e),vd(e),Td(e),bd(e,n),kd(e);break;case"safari":if(!hd||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=hd,Cd(e,n),wd(e),od(e),dd(e),sd(e),id(e),nd(e),cd(e),rd(e),ld(e),vd(e),yd(e),bd(e,n),kd(e),Sd(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const _d="lk_e2ee";var Pd,Rd,xd,Id,Od,Ad,Nd,Dd,Md,Ld,Ud,jd,Fd,Bd,$d,Vd,qd,Kd,Zd,Hd;function zd(){return void 0!==window.RTCRtpScriptTransform}(Rd=Pd||(Pd={})).SetKey="setKey",Rd.RatchetRequest="ratchetRequest",Rd.KeyRatcheted="keyRatcheted",(xd||(xd={})).KeyRatcheted="keyRatcheted",(Od=Id||(Id={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Od.EncryptionError="encryptionError",(Ad||(Ad={})).Error="cryptorError",kc.EventEmitter;class Gd extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}(Dd=Nd||(Nd={}))[Dd.NotAllowed=0]="NotAllowed",Dd[Dd.ServerUnreachable=1]="ServerUnreachable",Dd[Dd.InternalError=2]="InternalError",Dd[Dd.Cancelled=3]="Cancelled",Dd[Dd.LeaveRequest=4]="LeaveRequest";class Wd extends Gd{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=Nd[t]}}class Jd extends Gd{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Qd extends Gd{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Yd extends Gd{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Xd extends Gd{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class el extends Gd{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class tl extends Gd{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class il extends Gd{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:Yo[t]}}(Ld=Md||(Md={})).PermissionDenied="PermissionDenied",Ld.NotFound="NotFound",Ld.DeviceInUse="DeviceInUse",Ld.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(Md||(Md={})),(jd=Ud||(Ud={}))[jd.InvalidKey=0]="InvalidKey",jd[jd.MissingKey=1]="MissingKey",jd[jd.InternalError=2]="InternalError",(Bd=Fd||(Fd={})).Connected="connected",Bd.Reconnecting="reconnecting",Bd.SignalReconnecting="signalReconnecting",Bd.Reconnected="reconnected",Bd.Disconnected="disconnected",Bd.ConnectionStateChanged="connectionStateChanged",Bd.MediaDevicesChanged="mediaDevicesChanged",Bd.ParticipantConnected="participantConnected",Bd.ParticipantDisconnected="participantDisconnected",Bd.TrackPublished="trackPublished",Bd.TrackSubscribed="trackSubscribed",Bd.TrackSubscriptionFailed="trackSubscriptionFailed",Bd.TrackUnpublished="trackUnpublished",Bd.TrackUnsubscribed="trackUnsubscribed",Bd.TrackMuted="trackMuted",Bd.TrackUnmuted="trackUnmuted",Bd.LocalTrackPublished="localTrackPublished",Bd.LocalTrackUnpublished="localTrackUnpublished",Bd.LocalAudioSilenceDetected="localAudioSilenceDetected",Bd.ActiveSpeakersChanged="activeSpeakersChanged",Bd.ParticipantMetadataChanged="participantMetadataChanged",Bd.ParticipantNameChanged="participantNameChanged",Bd.ParticipantAttributesChanged="participantAttributesChanged",Bd.RoomMetadataChanged="roomMetadataChanged",Bd.DataReceived="dataReceived",Bd.SipDTMFReceived="sipDTMFReceived",Bd.TranscriptionReceived="transcriptionReceived",Bd.ConnectionQualityChanged="connectionQualityChanged",Bd.TrackStreamStateChanged="trackStreamStateChanged",Bd.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Bd.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Bd.AudioPlaybackStatusChanged="audioPlaybackChanged",Bd.VideoPlaybackStatusChanged="videoPlaybackChanged",Bd.MediaDevicesError="mediaDevicesError",Bd.ParticipantPermissionsChanged="participantPermissionsChanged",Bd.SignalConnected="signalConnected",Bd.RecordingStatusChanged="recordingStatusChanged",Bd.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Bd.EncryptionError="encryptionError",Bd.DCBufferStatusChanged="dcBufferStatusChanged",Bd.ActiveDeviceChanged="activeDeviceChanged",Bd.ChatMessage="chatMessage",Bd.LocalTrackSubscribed="localTrackSubscribed",Bd.MetricsReceived="metricsReceived",(Vd=$d||($d={})).TrackPublished="trackPublished",Vd.TrackSubscribed="trackSubscribed",Vd.TrackSubscriptionFailed="trackSubscriptionFailed",Vd.TrackUnpublished="trackUnpublished",Vd.TrackUnsubscribed="trackUnsubscribed",Vd.TrackMuted="trackMuted",Vd.TrackUnmuted="trackUnmuted",Vd.LocalTrackPublished="localTrackPublished",Vd.LocalTrackUnpublished="localTrackUnpublished",Vd.ParticipantMetadataChanged="participantMetadataChanged",Vd.ParticipantNameChanged="participantNameChanged",Vd.DataReceived="dataReceived",Vd.SipDTMFReceived="sipDTMFReceived",Vd.TranscriptionReceived="transcriptionReceived",Vd.IsSpeakingChanged="isSpeakingChanged",Vd.ConnectionQualityChanged="connectionQualityChanged",Vd.TrackStreamStateChanged="trackStreamStateChanged",Vd.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Vd.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Vd.MediaDevicesError="mediaDevicesError",Vd.AudioStreamAcquired="audioStreamAcquired",Vd.ParticipantPermissionsChanged="participantPermissionsChanged",Vd.PCTrackAdded="pcTrackAdded",Vd.AttributesChanged="attributesChanged",Vd.LocalTrackSubscribed="localTrackSubscribed",Vd.ChatMessage="chatMessage",(Kd=qd||(qd={})).TransportsCreated="transportsCreated",Kd.Connected="connected",Kd.Disconnected="disconnected",Kd.Resuming="resuming",Kd.Resumed="resumed",Kd.Restarting="restarting",Kd.Restarted="restarted",Kd.SignalResumed="signalResumed",Kd.SignalRestarted="signalRestarted",Kd.Closing="closing",Kd.MediaTrackAdded="mediaTrackAdded",Kd.ActiveSpeakersUpdate="activeSpeakersUpdate",Kd.DataPacketReceived="dataPacketReceived",Kd.RTPVideoMapUpdate="rtpVideoMapUpdate",Kd.DCBufferStatusChanged="dcBufferStatusChanged",Kd.ParticipantUpdate="participantUpdate",Kd.RoomUpdate="roomUpdate",Kd.SpeakersChanged="speakersChanged",Kd.StreamStateChanged="streamStateChanged",Kd.ConnectionQualityUpdate="connectionQualityUpdate",Kd.SubscriptionError="subscriptionError",Kd.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Kd.RemoteMute="remoteMute",Kd.SubscribedQualityUpdate="subscribedQualityUpdate",Kd.LocalTrackUnpublished="localTrackUnpublished",Kd.LocalTrackSubscribed="localTrackSubscribed",Kd.Offline="offline",Kd.SignalRequestResponse="signalRequestResponse",Kd.SignalConnected="signalConnected",(Hd=Zd||(Zd={})).Message="message",Hd.Muted="muted",Hd.Unmuted="unmuted",Hd.Restarted="restarted",Hd.Ended="ended",Hd.Subscribed="subscribed",Hd.Unsubscribed="unsubscribed",Hd.UpdateSettings="updateSettings",Hd.UpdateSubscription="updateSubscription",Hd.AudioPlaybackStarted="audioPlaybackStarted",Hd.AudioPlaybackFailed="audioPlaybackFailed",Hd.AudioSilenceDetected="audioSilenceDetected",Hd.VisibilityChanged="visibilityChanged",Hd.VideoDimensionsChanged="videoDimensionsChanged",Hd.VideoPlaybackStarted="videoPlaybackStarted",Hd.VideoPlaybackFailed="videoPlaybackFailed",Hd.ElementAttached="elementAttached",Hd.ElementDetached="elementDetached",Hd.UpstreamPaused="upstreamPaused",Hd.UpstreamResumed="upstreamResumed",Hd.SubscriptionPermissionChanged="subscriptionPermissionChanged",Hd.SubscriptionStatusChanged="subscriptionStatusChanged",Hd.SubscriptionFailed="subscriptionFailed",Hd.TrackProcessorUpdate="trackProcessorUpdate",Hd.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",Hd.TranscriptionReceived="transcriptionReceived",Hd.TimeSyncUpdate="timeSyncUpdate";const nl=/version\/(\d+(\.?_?\d+)+)/i;let sl;function rl(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===sl||t){const e=al.find((e=>{let{test:t}=e;return t.test(i)}));sl=null==e?void 0:e.describe(i)}return sl}const al=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:ol(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:cl(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:ol(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:cl(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:ol(nl,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:cl(e)})}];function ol(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function cl(e){return e.includes("mac os")?ol(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class dl{}dl.setTimeout=function(){return setTimeout(...arguments)},dl.setInterval=function(){return setInterval(...arguments)},dl.clearTimeout=function(){return clearTimeout(...arguments)},dl.clearInterval=function(){return clearInterval(...arguments)};const ll=[];var ul,hl;(hl=ul||(ul={}))[hl.LOW=0]="LOW",hl[hl.MEDIUM=1]="MEDIUM",hl[hl.HIGH=2]="HIGH";class pl extends kc.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=pl.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=uc,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=hc(null!==(n=i.loggerName)&&void 0!==n?n:oc.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=pl.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ku(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===pl.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===pl.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(ll.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&ll.splice(ll.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),ml(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(n?Zd.AudioPlaybackStarted:Zd.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(n?Zd.AudioPlaybackFailed:Zd.VideoPlaybackFailed,t):"AbortError"===t.name?uc.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):uc.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(Zd.ElementAttached,e),e}detach(e){try{if(e){gl(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Zd.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{gl(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Zd.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=hc(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ll.forEach((e=>{e.parentElement||(t=!1)})),t&&ll.push(e)}}handleAppVisibilityChanged(){return fc(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==pl.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){Ll()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ll()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ml(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),Dl()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Dl()||Nl())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function gl(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t;var i;let n;var s;let r;var a;(i=t=e.Kind||(e.Kind={})).Audio="audio",i.Video="video",i.Unknown="unknown",(s=n=e.Source||(e.Source={})).Camera="camera",s.Microphone="microphone",s.ScreenShare="screen_share",s.ScreenShareAudio="screen_share_audio",s.Unknown="unknown",(a=r=e.StreamState||(e.StreamState={})).Active="active",a.Paused="paused",a.Unknown="unknown",e.kindToProto=function(e){switch(e){case t.Audio:return ha.AUDIO;case t.Video:return ha.VIDEO;default:return ha.DATA}},e.kindFromProto=function(e){switch(e){case ha.AUDIO:return t.Audio;case ha.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return pa.CAMERA;case n.Microphone:return pa.MICROPHONE;case n.ScreenShare:return pa.SCREEN_SHARE;case n.ScreenShareAudio:return pa.SCREEN_SHARE_AUDIO;default:return pa.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case pa.CAMERA:return n.Camera;case pa.MICROPHONE:return n.Microphone;case pa.SCREEN_SHARE:return n.ScreenShare;case pa.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case oo.ACTIVE:return r.Active;case oo.PAUSED:return r.Paused;default:return r.Unknown}}}(pl||(pl={}));class fl{constructor(e,t,i,n,s){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)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const vl=["vp8","h264"],yl=["vp8","h264","vp9","av1"];function bl(e){return!!vl.find((t=>t===e))}var kl,Tl,Sl,Cl;(Tl=kl||(kl={}))[Tl.PREFER_REGRESSION=0]="PREFER_REGRESSION",Tl[Tl.SIMULCAST=1]="SIMULCAST",Tl[Tl.REGRESSION=2]="REGRESSION",(Cl=Sl||(Sl={})).telephone={maxBitrate:12e3},Cl.speech={maxBitrate:24e3},Cl.music={maxBitrate:48e3},Cl.musicStereo={maxBitrate:64e3},Cl.musicHighQuality={maxBitrate:96e3},Cl.musicHighQualityStereo={maxBitrate:128e3};const wl={h90:new fl(160,90,9e4,20),h180:new fl(320,180,16e4,20),h216:new fl(384,216,18e4,20),h360:new fl(640,360,45e4,20),h540:new fl(960,540,8e5,25),h720:new fl(1280,720,17e5,30),h1080:new fl(1920,1080,3e6,30),h1440:new fl(2560,1440,5e6,30),h2160:new fl(3840,2160,8e6,30)},El={h120:new fl(160,120,7e4,20),h180:new fl(240,180,125e3,20),h240:new fl(320,240,14e4,20),h360:new fl(480,360,33e4,20),h480:new fl(640,480,5e5,20),h540:new fl(720,540,6e5,25),h720:new fl(960,720,13e5,30),h1080:new fl(1440,1080,23e5,30),h1440:new fl(1920,1440,38e5,30)},_l={h360fps3:new fl(640,360,2e5,3,"medium"),h360fps15:new fl(640,360,4e5,15,"medium"),h720fps5:new fl(1280,720,8e5,5,"medium"),h720fps15:new fl(1280,720,15e5,15,"medium"),h720fps30:new fl(1280,720,2e6,30,"medium"),h1080fps15:new fl(1920,1080,25e5,15,"medium"),h1080fps30:new fl(1920,1080,5e6,30,"medium"),original:new fl(0,0,7e6,30,"medium")},Pl="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Rl(e){return fc(this,void 0,void 0,(function*(){return new Promise((t=>dl.setTimeout(t,e)))}))}function xl(){return"addTransceiver"in RTCPeerConnection.prototype}function Il(){return"addTrack"in RTCPeerConnection.prototype}function Ol(e){return"av1"===e||"vp9"===e}function Al(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function Nl(){var e;return"Firefox"===(null===(e=rl())||void 0===e?void 0:e.name)}function Dl(){var e;return"Safari"===(null===(e=rl())||void 0===e?void 0:e.name)}function Ml(){var e,t;return!!Ll()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function Ll(){return"undefined"!=typeof document}function Ul(){return"ReactNative"==navigator.product}function jl(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Fl(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Bl(){if(!Ul())return;let e=Fl();return e?e.platform:void 0}function $l(){if(Ll())return window.devicePixelRatio;if(Ul()){let e=Fl();if(e)return e.devicePixelRatio}return 1}function Vl(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let r=0;r<s;++r){const e=parseInt(i[r],10),t=parseInt(n[r],10);if(e>t)return 1;if(e<t)return-1;if(r===s-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function ql(e){for(const t of e)t.target.handleResize(t)}function Kl(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Zl=null;const Hl=()=>(Zl||(Zl=new ResizeObserver(ql)),Zl);let zl=null;const Gl=()=>(zl||(zl=new IntersectionObserver(Kl,{root:null,rootMargin:"0px"})),zl);function Wl(){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];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=i,o}let Jl;function Ql(){if(!Jl){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[Jl]=n.stream.getAudioTracks(),!Jl)throw Error("Could not get empty media stream audio track");Jl.enabled=!1}return Jl.clone()}class Yl{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>fc(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}function Xl(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function eu(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function tu(e){switch(e.reason){case Nd.LeaveRequest:return e.context;case Nd.Cancelled:return va.CLIENT_INITIATED;case Nd.NotAllowed:return va.USER_REJECTED;case Nd.ServerUnreachable:return va.JOIN_FAILURE;default:return va.UNKNOWN_REASON}}function iu(e){return void 0!==e?Number(e):void 0}function nu(e){return void 0!==e?BigInt(e):void 0}function su(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function ru(e){return!!e&&e.kind==pl.Kind.Audio}function au(e){return!!e&&e.kind==pl.Kind.Video}function ou(e){return su(e)&&au(e)}function cu(e){return su(e)&&ru(e)}function du(e){return!!e&&!e.isLocal}function lu(e){return!!e&&!e.isLocal}function uu(e){return du(e)&&au(e)}function hu(e,t,i){var n,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=Tu(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=o?o:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(pu(h.audio,t),null!==(n=(r=h.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(pu(h.video,i),null!==(s=(a=h.video).deviceId)&&void 0!==s||(a.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function pu(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function mu(e){var t,i,n,s;const r={};if(e.video)if("object"==typeof e.video){const i={},s=i,a=e.video;Object.keys(a).forEach((e=>{"resolution"===e?pu(s,a.resolution):s[e]=a[e]})),r.video=i,null!==(t=(n=r.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else r.video=!!e.video&&{deviceId:{ideal:"default"}};else r.video=!1;return e.audio?"object"==typeof e.audio?(r.audio=e.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function gu(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>fc(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(n){console.warn("Error trying to auto-resume audio context",n)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}));window.document.body.addEventListener("click",e)}return i}}function fu(e){return"audioinput"===e?pl.Source.Microphone:"videoinput"===e?pl.Source.Camera:pl.Source.Unknown}function vu(e){return e===pl.Source.Microphone?"audioinput":e===pl.Source.Camera?"videoinput":void 0}function yu(e){return e.split("/")[1].toLowerCase()}function bu(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new yo({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function ku(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?ku(e.track):{})}}function Tu(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}class Su extends kc.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":uc.error(s.error.message),this.emit(Id.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(Id.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(Id.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(Pd.KeyRatcheted,s.material,s.keyIndex)}},this.onWorkerError=e=>{uc.error("e2ee worker encountered an error:",{error:e.error}),this.emit(Id.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||zd()))throw new Jd("tried to setup end-to-end encryption on an unsupported browser");if(uc.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:pc.getLevel()}};this.worker&&(uc.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){uc.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):uc.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(qd.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(e,t){e.on(Fd.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==Ra.NONE,t.identity))),e.on(Fd.ConnectionStateChanged,(t=>{t===Bh.Connected&&e.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==Ra.NONE,e.identity)}))}))})).on(Fd.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(Fd.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(Fd.SignalConnected,(()=>{if(!this.room)throw new 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($d.LocalTrackPublished,(e=>fc(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),t.on(Pd.SetKey,(e=>this.postKey(e))).on(Pd.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}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?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const 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");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?yu(i.mimeType):void 0)}}setupE2EESender(e,t){su(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||uc.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return fc(this,void 0,void 0,(function*(){if(this.worker){if(zd()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(_d in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const a={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(a,[r,s])}e[_d]=!0}}))}handleSender(e,t,i){var n;if(!(_d in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?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(zd()){uc.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{uc.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[n.readable,n.writable])}e[_d]=!0}}}const Cu="default";class wu{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new wu),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return fc(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=wu.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){uc.debug("awaiting getUserMedia promise");try{e?yield wu.userMediaPromiseMap.get(e):yield Promise.all(wu.userMediaPromiseMap.values())}catch(r){uc.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!Dl()||!t.hasDeviceInUse(e))&&(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n})))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return fc(this,void 0,void 0,(function*(){if(t!==Cu)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===Cu));if(!s)return void uc.warn("could not reliably determine default device");const r=n.find((e=>e.deviceId!==Cu&&e.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;uc.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?wu.userMediaPromiseMap.has(e):wu.userMediaPromiseMap.size>0}}var Eu,_u;wu.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],wu.userMediaPromiseMap=new Map,(_u=Eu||(Eu={}))[_u.WAITING=0]="WAITING",_u[_u.RUNNING=1]="RUNNING",_u[_u.COMPLETED=2]="COMPLETED";class Pu{constructor(){this.pendingTasks=new Map,this.taskMutex=new Is,this.nextTaskIndex=0}run(e){return fc(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Eu.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Eu.RUNNING,yield e()}finally{t.status=Eu.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return fc(this,void 0,void 0,(function*(){return this.run((()=>fc(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function Ru(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}const xu=["syncState","trickle","offer","answer","simulate","leave"];var Iu,Ou;(Ou=Iu||(Iu={}))[Ou.CONNECTING=0]="CONNECTING",Ou[Ou.CONNECTED=1]="CONNECTED",Ou[Ou.RECONNECTING=2]="RECONNECTING",Ou[Ou.DISCONNECTING=3]="DISCONNECTING",Ou[Ou.DISCONNECTED=4]="DISCONNECTED";class Au{get currentState(){return this.state}get isDisconnected(){return this.state===Iu.DISCONNECTING||this.state===Iu.DISCONNECTED}get isEstablishingConnection(){return this.state===Iu.CONNECTING||this.state===Iu.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Iu.DISCONNECTED,this.log=uc,this._requestId=0,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.log=hc(null!==(i=t.loggerName)&&void 0!==i?i:oc.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Pu,this.queuedRequests=[],this.closingLock=new Is,this.connectionLock=new Is,this.state=Iu.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return fc(this,void 0,void 0,(function*(){return this.state=Iu.CONNECTING,this.options=i,yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return fc(this,void 0,void 0,(function*(){if(this.options)return this.state=Iu.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}));this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)}))}connect(e,t,i,n){this.connectOptions=i;const s=function(e,t,i){var n;const s=new URLSearchParams;return s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid)),s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",Ul()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel),t.os&&s.set("os",t.os),t.osVersion&&s.set("os_version",t.osVersion),t.browser&&s.set("browser",t.browser),t.browserVersion&&s.set("browser_version",t.browserVersion),i.adaptiveStream&&s.set("adaptive_stream","1"),i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString()),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type),s}(t,function(){var e;const t=new Ga({sdk:Wa.JS,protocol:15,version:"2.11.4"});return Ul()&&(t.os=null!==(e=Bl())&&void 0!==e?e:""),t}(),i),r=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{i.searchParams.set(t,e)})),Ru(i,"rtc")}(e,s),a=Ru(new URL(eu(r)),"validate");return new Promise(((e,t)=>fc(this,void 0,void 0,(function*(){const s=yield this.connectionLock.lock();try{const s=()=>fc(this,void 0,void 0,(function*(){this.close(),clearTimeout(o),t(new Wd("room connection has been cancelled (signal)",Nd.Cancelled))})),o=setTimeout((()=>{this.close(),t(new Wd("room connection has timed out (signal)",Nd.ServerUnreachable))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&s(),null==n||n.addEventListener("abort",s);const c=new URL(r);c.searchParams.has("access_token")&&c.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(c),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(o)},this.ws.onerror=e=>fc(this,void 0,void 0,(function*(){if(this.state===Iu.CONNECTED)this.handleWSError(e);else{this.state=Iu.DISCONNECTED,clearTimeout(o);try{const i=yield fetch(a);if(i.status.toFixed(0).startsWith("4")){const e=yield i.text();t(new Wd(e,Nd.NotAllowed,i.status))}else t(new Wd("Encountered unknown websocket error during connection: ".concat(e.toString()),Nd.InternalError,i.status))}catch(i){t(new Wd(i instanceof Error?i.message:"server was not reachable",Nd.ServerUnreachable))}}})),this.ws.onmessage=r=>fc(this,void 0,void 0,(function*(){var a,o,c;let d;if("string"==typeof r.data){const e=JSON.parse(r.data);d=uo.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(r.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof r.data),this.logContext);d=uo.fromBinary(new Uint8Array(r.data))}if(this.state!==Iu.CONNECTED){let r=!1;if("join"===(null===(a=d.message)||void 0===a?void 0:a.case)?(this.state=Iu.CONNECTED,null==n||n.removeEventListener("abort",s),this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.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})),this.startPingInterval()),e(d.message.value)):this.state===Iu.RECONNECTING&&"leave"!==d.message.case?(this.state=Iu.CONNECTED,null==n||n.removeEventListener("abort",s),this.startPingInterval(),"reconnect"===(null===(o=d.message)||void 0===o?void 0:o.case)?e(d.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),r=!0)):this.isEstablishingConnection&&"leave"===d.message.case?t(new Wd("Received leave request while trying to (re)connect",Nd.LeaveRequest,void 0,d.message.value.reason)):i.reconnect||t(new Wd("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"),Nd.InternalError)),!r)return}this.signalLatency&&(yield Rl(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new Wd("Websocket got closed during a (re)connection attempt",Nd.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{s()}}))))}close(){return fc(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Iu.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,Rl(250)])),e.ws=void 0}}finally{t&&(e.state=Iu.DISCONNECTED),i()}}()}))}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Du(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Du(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new mo({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new go({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return fc(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new xo({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}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 Ro({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new $o({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Js.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ho({timestamp:Js.parse(Date.now()),rtt:Js.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new wo({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new _o({reason:va.CLIENT_INITIATED,action:Po.DISCONNECT})})}sendRequest(e){return fc(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=xu.indexOf(e.case)>=0;return uc.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===Iu.RECONNECTING)return void t.queuedRequests.push((()=>fc(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield Rl(t.signalLatency)),!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new lo({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(r){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:r}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=Nu(n.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.case){const e=Nu(n.value);this.onOffer&&this.onOffer(e)}else if("trickle"===n.case){const 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)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?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(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return fc(this,void 0,void 0,(function*(){if(this.state===Iu.DISCONNECTED)return;const t=this.onClose;yield this.close(),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=dl.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&&dl.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=dl.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&&dl.clearInterval(this.pingInterval)}}function Nu(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function Du(e){return new ko({sdp:e.sdp,type:e.type})}var Mu,Lu,Uu,ju,Fu,Bu={},$u={},Vu={exports:{}};function qu(){if(Mu)return Vu.exports;Mu=1;var e=Vu.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",t+=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","maxMessageSize"],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:new 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:new 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",t+=null!=e.mediaClockValue?"=%s":"",(t+=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")}))})),Vu.exports}function Ku(){if(ju)return Uu;ju=1;var e=qu(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,(function(e){if(i>=s)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 s=[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 a=t.names[r];t.name?s.push(n[t.name][a]):s.push(n[t.names[r]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Uu=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var a=i.outerOrder||s,o=i.innerOrder||r,c=[];return a.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"}}var Zu=function(){if(Fu)return Bu;Fu=1;var e=(Lu||(Lu=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=qu(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),a=r[r.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var c=n[t][o];if(c.reg.test(s))return i(c,a,s)}})),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}($u)),$u),t=Ku(),i=qu();return Bu.grammar=i,Bu.write=t,Bu.parse=e.parse,Bu.parseParams=e.parseParams,Bu.parseFmtpConfig=e.parseFmtpConfig,Bu.parsePayloads=e.parsePayloads,Bu.parseRemoteCandidates=e.parseRemoteCandidates,Bu.parseImageAttributes=e.parseImageAttributes,Bu.parseSimulcastStreamList=e.parseSimulcastStreamList,Bu}();function Hu(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var a=null!=(n=i.isImmediate)&&n,o=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise((function(s,u){var h=a&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!a){var t=e.apply(n,i);o&&o(t),l.forEach((function(e){return(0,e.resolve)(t)})),l=[]}}),function(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return o&&o(p),s(p)}l.push({resolve:s,reject:u})}))};return u.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},u}const zu="negotiationStarted",Gu="negotiationComplete",Wu="rtpVideoPayloadTypes";class Ju extends kc.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=uc,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Hu((e=>fc(this,void 0,void 0,(function*(){this.emit(zu);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(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=hc(null!==(i=t.loggerName)&&void 0!==i?i:oc.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return fc(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){return fc(this,void 0,void 0,(function*(){var t;let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=Zu.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===r&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const n=Zu.parse(null!==(t=e.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),i=Zu.write(n)}yield this.setMungedSDP(e,i,!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(Gu),e.sdp)&&Zu.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Wu,e.rtp)}))}))}createAndSendOffer(e){return fc(this,void 0,void 0,(function*(){var t;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){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}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);const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const n=Zu.parse(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{Yu(e),"audio"===e.type?Qu(e,[],[]):"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)return!0;if(Ol(t.codec)&&this.ensureVideoDDExtensionForSVC(e,n),"av1"!==t.codec)return!0;const s=Math.round(.7*t.maxbr);for(const n of e.fmtp)if(n.payload===i){n.config.includes("x-google-start-bitrate")||(n.config+=";x-google-start-bitrate=".concat(s));break}return!0}))})),yield this.setMungedSDP(i,Zu.write(n)),this.onOffer(i)}))}createAndSetAnswer(){return fc(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=Zu.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Yu(e),"audio"===e.type&&Qu(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Zu.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Xd("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 Xd("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return fc(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const 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;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return fc(this,void 0,void 0,(function*(){if(t){const s=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(n){let t="unknown error";n instanceof Error?t=n.message:"string"==typeof n&&(t=n);const s={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new el(t)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Pl)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:Pl})}}}function Qu(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Yu(e){if(e.connection){const 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)}}const Xu="vp8",eh={audioPreset:Sl.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:_l.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Xu,backupCodec:!0},th={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ih={deviceId:{ideal:"default"},resolution:wl.h720.resolution},nh={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:gc}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1},sh={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var rh,ah;(ah=rh||(rh={}))[ah.NEW=0]="NEW",ah[ah.CONNECTING=1]="CONNECTING",ah[ah.CONNECTED=2]="CONNECTED",ah[ah.FAILED=3]="FAILED",ah[ah.CLOSING=4]="CLOSING",ah[ah.CLOSED=5]="CLOSED";class oh{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=sh.peerConnectionTimeout,this.log=uc,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=rh.CONNECTED:i.some((e=>"failed"===e))?this.state=rh.FAILED:i.some((e=>"connecting"===e))?this.state=rh.CONNECTING:i.every((e=>"closed"===e))?this.state=rh.CLOSED:i.some((e=>"closed"===e))?this.state=rh.CLOSING:i.every((e=>"new"===e))&&(this.state=rh.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(rh[t]," to ").concat(rh[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=hc(null!==(n=i.loggerName)&&void 0!==n?n:oc.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Ju(e,i),this.subscriber=new Ju(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,ao.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,ao.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=e=>{var t;null===(t=this.onPublisherOffer)||void 0===t||t.call(this,e)},this.state=rh.NEW,this.connectionLock=new Is,this.remoteOfferLock=new Is}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return fc(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return fc(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return fc(this,void 0,void 0,(function*(){t===ao.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e){return fc(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return fc(this,void 0,void 0,(function*(){var i;const 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?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return fc(this,void 0,void 0,(function*(){return new Promise(((t,i)=>fc(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(zu,(()=>{e.signal.aborted||this.publisher.once(Gu,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===ao.PUBLISHER||e===ao.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return fc(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,s)=>fc(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),dl.clearTimeout(r),s(new Wd("room connection has been cancelled",Nd.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const r=dl.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),s(new Wd("could not establish pc connection",Nd.InternalError))}),n);for(;this.state!==rh.CONNECTED;)if(yield Rl(50),null==t?void 0:t.signal.aborted)return void s(new Wd("room connection has been cancelled",Nd.Cancelled));dl.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}class ch extends Error{constructor(e,t,i){super(t),this.code=e,this.message=lh(t,ch.MAX_MESSAGE_BYTES),this.data=i?lh(i,ch.MAX_DATA_BYTES):void 0}static fromProto(e){return new ch(e.code,e.message,e.data)}toProto(){return new Ka({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ch(ch.ErrorCode[e],ch.ErrorMessage[e],t)}}function dh(e){return(new TextEncoder).encode(e).length}function lh(e,t){if(dh(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(e.slice(0,r)).length<=t?i=r:n=r-1}return e.slice(0,i)}ch.MAX_MESSAGE_BYTES=256,ch.MAX_DATA_BYTES=15360,ch.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},ch.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"};const uh=2e3;function hh(e,t){if(!t)return 0;let i,n;return"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:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class ph extends pl{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),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=Hu((()=>fc(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>fc(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(Zd.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new Is,this.pauseUpstreamLock=new Is,this.processorLock=new Is,this.restartLock=new Is,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==pl.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}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?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return fc(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{gl(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){const t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(ml(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(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=>{ml(null!=n?n:e,t)})))}))}waitForDimensions(){return fc(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===pl.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=rl())||void 0===i?void 0:i.os)&&(yield Rl(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield Rl(50)}throw new Qd("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return fc(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Xl(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Xl(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return fc(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===pl.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===pl.Kind.Audio?"audioinput":"videoinput";return t?wu.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return fc(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return fc(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return fc(this,void 0,void 0,(function*(){if(!this.sender)throw new Qd("unable to replace an unpublished track");let i,n;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.stopProcessor()),this}))}restart(e){return fc(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===pl.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||{deviceId:t},this.attachedElements.forEach((e=>{gl(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return 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(Zd.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?Zd.Muted:Zd.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return fc(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ml()&&(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)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return fc(this,void 0,void 0,(function*(){var e;const 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(Zd.UpstreamPaused,this);const t=rl();if("Safari"===(null==t?void 0:t.name)&&Vl(t.version,"12.0")<0)throw new Jd("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}}))}resumeUpstream(){return fc(this,void 0,void 0,(function*(){var e;const 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(Zd.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}}))}getRTCStatsReport(){return fc(this,void 0,void 0,(function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()}))}setProcessor(e){return fc(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),r={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(r),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(ml(t._mediaStreamTrack,s),s.muted=!0,s.play().catch((e=>t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e})))),t.processor=e,t.processorElement=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(gl(t._mediaStreamTrack,e),ml(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(Zd.TrackProcessorUpdate,t.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return fc(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)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Zd.TrackProcessorUpdate))}()}))}}class mh extends ph{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,s=arguments.length>4?arguments[4]:void 0;super(e,pl.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>fc(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(t){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}e&&this.prevStats&&(this._currentBitrate=hh(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Zd.AudioTrackFeatureUpdate,this,ka.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Zd.AudioTrackFeatureUpdate,this,ka.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return fc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===pl.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(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return fc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Xl(this._constraints.deviceId);return this.source!==pl.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 fc(this,void 0,void 0,(function*(){let t;if(e){const i=mu({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return fc(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){Ll()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),uh)))}setProcessor(e){return fc(this,void 0,void 0,(function*(){var t;const i=yield this.processorLock.lock();try{if(!Ul()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const 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?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(Zd.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return fc(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;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 fc(this,void 0,void 0,(function*(){const e=yield function(e){return fc(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=gu();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield Rl(t),n.getByteTimeDomainData(r);const a=r.some((e=>128!==e&&0!==e));return i.close(),!a}return!1}()}))}(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(Zd.AudioSilenceDetected)),e}))}}const gh=Object.values(wl),fh=Object.values(El),vh=Object.values(_l),yh=[wl.h180,wl.h360],bh=[El.h180,El.h360],kh=["q","h","f"];function Th(e,t,i,n){var s,r;let a=null==n?void 0:n.videoEncoding;e&&(a=null==n?void 0:n.screenShareEncoding);const o=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!a&&!o&&!c||!t||!i)return[{}];a||(a=function(e,t,i,n){const s=function(e,t,i){if(e)return vh;const n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?gh:fh}(e,t,i);let{encoding:r}=s[0];const a=Math.max(t,i);for(let o=0;o<s.length;o+=1){const e=s[o];if(r=e.encoding,e.width>=a)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),uc.debug("using video encoding",a));const l=a.maxFramerate,u=new fl(t,i,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Ol(d)){const e=new Eh(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=rl();if(Dl()||Ul()||"Chrome"===(null==i?void 0:i.name)&&Vl(null==i?void 0:i.version,"113")<0){const i="h"==e.suffix?2:3;for(let n=0;n<e.spatial;n+=1)t.push({rid:kh[2-n],maxBitrate:a.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate});t[0].scalabilityMode=c}else t.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),uc.debug("using svc encoding",{encodings:t}),t}if(!o)return[a];let h,p=[];if(p=e?null!==(s=wh(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:Sh(e,u):null!==(r=wh(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:Sh(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return Ch(t,i,[e,h,u],l);if(n>=480)return Ch(t,i,[e,u],l)}return Ch(t,i,[u])}function Sh(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map((e=>{var t,n;return new fl(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)}));var i;const{width:n,height:s}=t,r=n>s?n/s:s/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?yh:bh}function Ch(e,t,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=kh.length)return;const a=Math.min(e,t),o={rid:kh[r],scaleResolutionDownBy:Math.max(1,a/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);const d=Nl()||0===r;i.encoding.priority&&d&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),s.push(o)})),Ul()&&"ios"===Bl()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,uc.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),uc.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return s}function wh(e){if(e)return e.sort(((e,t)=>{const{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 Eh{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new 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)&&void 0!==e?e:"")}}class _h extends ph{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,pl.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>fc(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(i){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:i}))}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=hh(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Is}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ll())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),uh))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return fc(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var a,o=!0,c=vc(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){s=a.value,o=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(d){i={error:d}}finally{try{o||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return fc(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var a,o=!0,c=vc(this.simulcastCodecs.values());!(t=(a=yield c.next()).done);o=!0){s=a.value,o=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{o||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return fc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==pl.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return fc(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==pl.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return fc(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={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)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(e){const t=[];for(let i=ul.LOW;i<=ul.HIGH;i+=1)t.push(new Uo({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return fc(this,void 0,void 0,(function*(){var t,i,n,s,r;let a;if(e){const t=mu({video:e});"boolean"!=typeof t.video&&(a=t.video)}yield this.restart(a);try{for(var o,c=!0,d=vc(this.simulcastCodecs.values());!(t=(o=yield d.next()).done);c=!0){s=o.value,c=!1;const e=s;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(l){i={error:l}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return fc(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,a,o,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=vc(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){o=l.value,u=!1;const e=o;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(p){r={error:p}}finally{try{u||s||!(a=h.return)||(yield a.call(h))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(e){return fc(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},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);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return fc(this,void 0,void 0,(function*(){var t,i,n,s,r,a,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(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=vc(e);!(s=(n=yield i.next()).done);t=!0){o=n.value,t=!1;const e=o;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield Ph(t.sender,t.encodings,e.qualities,this.senderLock,this.log,this.logContext));else for(const i of e.qualities)if(i.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(d){r={error:d}}finally{try{t||s||!(a=i.return)||(yield a.call(i))}finally{if(r)throw r.error}}return c}))}setPublishingLayers(e){return fc(this,void 0,void 0,(function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),this.sender&&this.encodings&&(yield Ph(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return fc(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ml()&&this.isInBackground&&this.source===pl.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function Ph(e,t,i,n,s,r){return fc(this,void 0,void 0,(function*(){const a=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:t}));let o=!1;const c=rl();if("Chrome"===(null==c?void 0:c.name)&&Vl(null==c?void 0:c.version,"133")>0&&a[0].scalabilityMode){const e=a[0],n=new Eh(e.scalabilityMode);let s=ma.OFF;if(i.forEach((e=>{e.enabled&&(s===ma.OFF||e.quality>s)&&(s=e.quality)})),s===ma.OFF)e.active&&(e.active=!1,o=!0);else if(!e.active||n.spatial!==s+1){o=!0,e.active=!0;const i=new Eh(t[0].scalabilityMode);n.spatial=s+1,n.suffix=i.suffix,1===n.spatial&&(n.suffix=void 0),e.scalabilityMode=n.toString(),e.scaleResolutionDownBy=Math.pow(2,2-s),t[0].maxBitrate&&(e.maxBitrate=t[0].maxBitrate/(e.scaleResolutionDownBy*e.scaleResolutionDownBy))}}else a.forEach(((e,n)=>{var a;let c=null!==(a=e.rid)&&void 0!==a?a:"";""===c&&(c="q");const d=Rh(c),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(o=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),Nl()&&(l.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)))}));o&&(n.encodings=a,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}}))}function Rh(e){switch(e){case"f":default:return ul.HIGH;case"h":return ul.MEDIUM;case"q":return ul.LOW}}function xh(e,t,i,n){if(!i)return[new Oa({quality:ul.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new Eh(n),r=[],a="h"==s.suffix?1.5:2,o="h"==s.suffix?2:3;for(let c=0;c<s.spatial;c+=1)r.push(new Oa({quality:Math.min(ul.HIGH,s.spatial-1)-c,width:Math.ceil(e/Math.pow(a,c)),height:Math.ceil(t/Math.pow(a,c)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(o,c)):0,ssrc:0}));return r}return i.map((i=>{var n,s,r;const a=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let o=Rh(null!==(s=i.rid)&&void 0!==s?s:"");return new Oa({quality:o,width:Math.ceil(e/a),height:Math.ceil(t/a),bitrate:null!==(r=i.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const Ih="_lossy",Oh="_reliable",Ah="leave-reconnect";var Nh,Dh,Mh,Lh,Uh,jh,Fh,Bh,$h,Vh,qh;(Dh=Nh||(Nh={}))[Dh.New=0]="New",Dh[Dh.Connected=1]="Connected",Dh[Dh.Disconnected=2]="Disconnected",Dh[Dh.Reconnecting=3]="Reconnecting",Dh[Dh.Closed=4]="Closed";class Kh extends kc.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=sh.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Nh.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=uc,this.handleDataChannel=e=>fc(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===Oh)t.reliableDCSub=i;else{if(i.label!==Ih)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=>fc(this,void 0,void 0,(function*(){var t,i;const n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=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}));n=yield e.data.arrayBuffer()}const s=Aa.fromBinary(new Uint8Array(n));"speaker"===(null===(t=s.value)||void 0===t?void 0:t.case)?this.emit(qd.ActiveSpeakersUpdate,s.value.value.speakers):("user"===(null===(i=s.value)||void 0===i?void 0:i.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(s,s.value.value),this.emit(qd.DataPacketReceived,s))}finally{n()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{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=>{const t=0===e.currentTarget.maxRetransmits?Na.LOSSY:Na.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());const i=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});null!==n?(e===Ah&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=dl.setTimeout((()=>this.attemptReconnect(t).finally((()=>this.reconnectTimeout=void 0))),n)):(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(qd.Disconnected),this.close()})(i)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===Nh.Connected&&e();const i=()=>{this.off(qd.Disconnected,n),e()},n=()=>{this.off(qd.Restarted,i),t()};this.once(qd.Restarted,i),this.once(qd.Disconnected,n)})),this.updateAndEmitDCBufferStatus=e=>{const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(qd.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Iu.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ya.RR_SIGNAL_DISCONNECTED))},this.log=hc(null!==(t=e.loggerName)&&void 0!==t?t:oc.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Au(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Is,this.dataProcessLock=new Is,this.dcBufferStatus=new Map([[Na.LOSSY,!0],[Na.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(qd.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(qd.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(qd.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(qd.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(qd.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(qd.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(qd.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(qd.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,r,a,o;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:null===(o=null===(a=this.latestJoinResponse)||void 0===a?void 0:a.participant)||void 0===o?void 0:o.sid}}join(e,t,i,n){return fc(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout((()=>{this.emit(qd.SignalConnected)}),10),s}catch(s){if(s instanceof Wd&&s.reason===Nd.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw s}}))}close(){return fc(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(qd.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}}))}cleanupPeerConnections(){return fc(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const 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}))}cleanupClient(){return fc(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Qd("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new Wd("publication of local track timed out, no response from server",Nd.InternalError))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return fc(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return fc(this,void 0,void 0,(function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==rh.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const n=this.makeRTCConfiguration(e);var s;this.pcManager=new oh(n,e.subscriberPrimary,this.loggerOptions),this.emit(qd.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=e=>{this.client.sendOffer(e)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>fc(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===rh.CONNECTED){const t=this.pcState===Nh.New;this.pcState=Nh.Connected,t&&this.emit(qd.Connected,e)}else t===rh.FAILED&&this.pcState===Nh.Connected&&(this.pcState=Nh.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?ya.RR_SUBSCRIBER_FAILED:ya.RR_PUBLISHER_FAILED));const s=this.client.isDisconnected||this.client.currentState===Iu.RECONNECTING,r=[rh.FAILED,rh.CLOSING,rh.CLOSED].includes(t);s&&r&&!this._isClosed&&this.emit(qd.Offline)})),this.pcManager.onTrack=e=>{this.emit(qd.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(s=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=e=>fc(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))})),this.client.onTrickle=(e,t)=>{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=>fc(this,void 0,void 0,(function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(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?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}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(qd.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(qd.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(qd.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(qd.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ya.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(e.regions)),e.action){case Po.DISCONNECT:this.emit(qd.Disconnected,null==e?void 0:e.reason),this.close();break;case Po.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Ah);break;case Po.RESUME:this.handleDisconnect(Ah)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const 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===fa.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(Ih,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Oh,{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)}createSender(e,t,i){return fc(this,void 0,void 0,(function*(){if(xl())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Il())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Xd("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return fc(this,void 0,void 0,(function*(){if(xl())return this.createSimulcastTransceiverSender(e,t,i,n);if(Il())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Xd("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return fc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Xd("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),au(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return fc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Xd("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(e){return fc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Xd("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(e){return fc(this,void 0,void 0,(function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)uc.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==fa.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:rh.NEW)!==rh.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let e=!0;s instanceof Xd?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),e=!1):s instanceof Zh||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",ya.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(qd.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return fc(this,void 0,void 0,(function*(){var t,i,n;try{if(!this.url||!this.token)throw new Xd("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(qd.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 Zh;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(s){if(s instanceof Wd&&s.reason===Nd.NotAllowed)throw new Xd("could not reconnect, token might be expired");throw new Zh}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(qd.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Iu.CONNECTED)throw new Zh("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(qd.Restarted)}catch(r){const e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),r}}))}resumeConnection(e){return fc(this,void 0,void 0,(function*(){var t;if(!this.url||!this.token)throw new Xd("could not reconnect, url or token not saved");if(!this.pcManager)throw new Xd("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(qd.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(n){let e="";if(n instanceof Error&&(e=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof Wd&&n.reason===Nd.NotAllowed)throw new Xd("could not reconnect, token might be expired");if(n instanceof Wd&&n.reason===Nd.LeaveRequest)throw n;throw new Zh(e)}if(this.emit(qd.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Iu.CONNECTED)throw new Zh("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(qd.Resumed)}))}waitForPCInitialConnection(e,t){return fc(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Xd("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return fc(this,void 0,void 0,(function*(){this.pcState=Nh.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Rl(2e3),!this.pcManager)throw new Xd("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Nh.Connected}catch(e){throw this.pcState=Nh.Disconnected,new Wd("could not establish PC connection, ".concat(e.message),Nd.InternalError)}}))}publishRpcResponse(e,t,i,n){return fc(this,void 0,void 0,(function*(){const s=new Aa({destinationIdentities:[e],kind:Na.RELIABLE,value:{case:"rpcResponse",value:new qa({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,Na.RELIABLE)}))}publishRpcAck(e,t){return fc(this,void 0,void 0,(function*(){const i=new Aa({destinationIdentities:[e],kind:Na.RELIABLE,value:{case:"rpcAck",value:new Va({requestId:t})}});yield this.sendDataPacket(i,Na.RELIABLE)}))}sendDataPacket(e,t){return fc(this,void 0,void 0,(function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const n=this.dataChannelForKind(t);n&&n.send(i),this.updateAndEmitDCBufferStatus(t)}))}waitForBufferStatusLow(e){return new Promise(((t,i)=>fc(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i("Engine closed");for(this.once(qd.Closing,n);!this.dcBufferStatus.get(e);)yield Rl(10);this.off(qd.Closing,n),t()}}))))}ensureDataTransportConnected(e){return fc(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 Xd("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw new Wd("".concat(r," connection not set"),Nd.InternalError);let a=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),a=!0),a||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(a=!0),a&&t.negotiate();const o=t.dataChannelForKind(e,i);if("open"===(null==o?void 0:o.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield Rl(50)}throw new Wd("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()),Nd.InternalError)}()}))}ensurePublisherConnected(e){return fc(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===rh.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return fc(this,void 0,void 0,(function*(){return new Promise(((e,t)=>fc(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new el("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(qd.Closing,n),this.pcManager.publisher.once(Wu,(e=>{const t=new Map;e.forEach((e=>{const i=e.codec.toLowerCase();var n;n=i,yl.includes(n)&&t.set(e.payload,i)})),this.emit(qd.RTPVideoMapUpdate,t)}));try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof el&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ya.RR_UNKNOWN),t(s)}finally{this.off(qd.Closing,n)}}))))}))}dataChannelForKind(e,t){if(t){if(e===Na.LOSSY)return this.lossyDCSub;if(e===Na.RELIABLE)return this.reliableDCSub}else{if(e===Na.LOSSY)return this.lossyDC;if(e===Na.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),r=this.pcManager.subscriber.getRemoteDescription(),a=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,o=new Array,c=new Array;e.forEach((e=>{e.isDesired!==a&&o.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new qo({answer:s?Du({sdp:s.sdp,type:s.type}):void 0,offer:r?Du({sdp:r.sdp,type:r.type}):void 0,subscription:new So({trackSids:o,subscribe:!a,participantTracks:[]}),publishTracks:bu(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Ko({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(Na.LOSSY),ao.PUBLISHER),t(this.dataChannelForKind(Na.RELIABLE),ao.PUBLISHER),t(this.dataChannelForKind(Na.LOSSY,!0),ao.SUBSCRIBER),t(this.dataChannelForKind(Na.RELIABLE,!0),ao.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&dl.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ll()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ll()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Zh extends Error{}class Hh{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return jl(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return fc(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),uc.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return fc(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new Wd("Could not fetch region settings: ".concat(t.statusText),401===t.status?Nd.NotAllowed:Nd.InternalError,t.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class zh{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class Gh extends zh{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>fc(this,void 0,void 0,(function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch(t){return{done:!0,value:void 0}}})),return(){return fc(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return fc(this,void 0,void 0,(function*(){var e,t,i,n;let s=new Set;try{for(var r,a=!0,o=vc(this);!(e=(r=yield o.next()).done);a=!0){n=r.value,a=!1;const e=n;s.add(e)}}catch(c){t={error:c}}finally{try{a||e||!(i=o.return)||(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(s)}))}}class Wh extends zh{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=iu(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>fc(this,void 0,void 0,(function*(){try{const{done:i,value:n}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:t.decode(n.content)})}catch(i){return{done:!0,value:void 0}}})),return(){return fc(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return fc(this,void 0,void 0,(function*(){var e,t,i,n;let s="";try{for(var r,a=!0,o=vc(this);!(e=(r=yield o.next()).done);a=!0)n=r.value,a=!1,s+=n}catch(c){t={error:c}}finally{try{a||e||!(i=o.return)||(yield i.call(o))}finally{if(t)throw t.error}}return s}))}}class Jh{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 fc(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class Qh extends Jh{}class Yh extends Jh{}class Xh extends pl{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Zd.Muted:Zd.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const 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(Zd.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return fc(this,void 0,void 0,(function*(){var e;if(null===(e=this.receiver)||void 0===e?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;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()),uh)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame((()=>e()));const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(Zd.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class ep extends Xh{constructor(e,t,i,n,s,r){super(e,t,pl.Kind.Audio,i,r),this.monitorReceiver=()=>fc(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=hh(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Ul()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ul())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return fc(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Al(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Al(e)&&e.setSinkId(this.sinkId),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(Zd.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(Zd.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return fc(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;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 tp extends Xh{constructor(e,t,i,n,s){super(e,t,pl.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>fc(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=hh(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Hu((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?gl(this._mediaStreamTrack,t):ml(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new ip(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);const t=this.elementInfos.filter((t=>t===e));for(const i of t)i.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);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return fc(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return fc(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),n=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),r=this.elementInfos.some((e=>e.visible))&&!n||s;this.lastVisible!==r&&(!r&&Date.now()-i<100?dl.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=r,this.emit(Zd.VisibilityChanged,r,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const r of this.elementInfos){const e=r.width()*s,t=r.height()*s;e+t>i+n&&(i=e,n=t)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Zd.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?$l():t||($l()>2?2:1)}}class ip{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=np(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=np(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=np(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:sp(e),this.isPiP=Ll()&&np(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=sp(this.element),this.isPiP=np(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Gl().observe(this.element),Hl().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=Gl())||void 0===e||e.unobserve(this.element),null===(t=Hl())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function np(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&sp(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function sp(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const r=e.offsetWidth,a=e.offsetHeight,{hidden:o}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+a>i.pageYOffset&&s+r>i.pageXOffset&&!o&&"none"!==c}class rp extends kc.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=Ra.NONE,this.log=uc,this.handleMuted=()=>{this.emit(Zd.Muted)},this.handleUnmuted=()=>{this.emit(Zd.Unmuted)},this.log=hc(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:oc.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=pl.Source.Unknown}setTrack(e){this.track&&(this.track.off(Zd.Muted,this.handleMuted),this.track.off(Zd.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Zd.Muted,this.handleMuted),e.on(Zd.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ku(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==Ra.NONE}get audioTrack(){if(ru(this.track))return this.track}get videoTrack(){if(au(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=pl.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===pl.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}))}}(Lh=(Mh=rp||(rp={})).SubscriptionStatus||(Mh.SubscriptionStatus={})).Desired="desired",Lh.Subscribed="subscribed",Lh.Unsubscribed="unsubscribed",(Uh=Mh.PermissionStatus||(Mh.PermissionStatus={})).Allowed="allowed",Uh.NotAllowed="not_allowed";class ap extends rp{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Zd.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(Zd.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(Zd.Ended,this.handleTrackEnded)}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 fc(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return fc(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return fc(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return fc(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(ru(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ka.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ka.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ka.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ka.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(ka.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ka.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function op(e,t){return fc(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=Tu(e);let a=r.audio,o=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),e.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const e=r.audio.deviceId;r.audio.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:e}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const e=r.video.deviceId;r.video.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:e}})}(!0===r.audio||"object"==typeof r.audio&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),(!0===r.video||"object"==typeof r.video&&!r.video.deviceId)&&(r.video={deviceId:"default"});const c=hu(r,th,ih),d=mu(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(wu.userMediaPromiseMap.set("audioinput",l),l.catch((()=>wu.userMediaPromiseMap.delete("audioinput")))),r.video&&(wu.userMediaPromiseMap.set("videoinput",l),l.catch((()=>wu.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>fc(this,void 0,void 0,(function*(){const r="audio"===i.kind;let a,o=r?c.audio:c.video;"boolean"!=typeof o&&o||(o={});const l=r?d.audio:d.video;"boolean"!=typeof l&&(a=l);const u=i.getSettings().deviceId;(null==a?void 0:a.deviceId)&&Xl(a.deviceId)!==u?a.deviceId=u:a||(a={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new mh(e,t,!1,void 0,i);case"video":return new _h(e,t,!1,i);default:throw new Qd("unsupported track type: ".concat(e.kind))}}(i,a,t);return h.kind===pl.Kind.Video?h.source=pl.Source.Camera:h.kind===pl.Kind.Audio&&(h.source=pl.Source.Microphone),h.mediaStream=e,ru(h)&&n?yield h.setProcessor(n):au(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(u){if(!i)throw u;return op(Object.assign(Object.assign({},e),{audio:a,video:o}),t)}}))}(Fh=jh||(jh={})).Excellent="excellent",Fh.Good="good",Fh.Poor="poor",Fh.Lost="lost",Fh.Unknown="unknown";class cp extends kc.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?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?void 0:e.agent)||this.kind===_a.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,r){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:_a.STANDARD;var o;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=jh.Unknown,this.log=uc,this.log=hc(null!==(o=null==r?void 0:r.loggerName)&&void 0!==o?o:oc.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=a,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(pl.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(pl.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(pl.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){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.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),0))}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit($d.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit($d.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit($d.AttributesChanged,t)}setPermissions(e){var t,i,n,s,r,a;const o=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(r=this.permissions)||void 0===r?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?void 0:i.canPublishSources[t])}))||e.canSubscribeMetrics!==(null===(a=this.permissions)||void 0===a?void 0:a.canSubscribeMetrics);return this.permissions=e,c&&this.emit($d.ParticipantPermissionsChanged,o),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit($d.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case ga.EXCELLENT:return jh.Excellent;case ga.GOOD:return jh.Good;case ga.POOR:return jh.Poor;case ga.LOST:return jh.Lost;default:return jh.Unknown}}(e),t!==this._connectionQuality&&this.emit($d.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>ru(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(e){e.on(Zd.Muted,(()=>{this.emit($d.TrackMuted,e)})),e.on(Zd.Unmuted,(()=>{this.emit($d.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case pl.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case pl.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class dp extends cp{constructor(e,t,i,n,s){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=Ra.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Yl)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==Yo.OK&&s.reject(new il(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=ch.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.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 new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Bo({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&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),ku(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ku(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ku(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const 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.handleSubscribedQualityUpdate=e=>fc(this,void 0,void 0,(function*(){var t,i,n,s,r,a;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const o=this.videoTrackPublications.get(e.trackSid);if(o)if(e.subscribedCodecs.length>0){if(!o.videoTrack)return;const r=yield o.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=vc(r);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;bl(e)&&(this.log.debug("publish ".concat(e," for ").concat(o.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ku(o))),yield this.publishAdditionalCodecForTrack(o.videoTrack,e,o.options))}}catch(u){i={error:u}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(a=o.videoTrack)||void 0===a?void 0:a.setPublishingLayers(e.subscribedQualities));else this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))})),this.handleLocalTrackUnpublished=e=>{const 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=>fc(this,void 0,void 0,(function*(){if(e.source===pl.Source.ScreenShare||e.source===pl.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ku(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(cu(e)||ou(e))try{if(Ll())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===pl.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),ku(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(t){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ku(e))),cu(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),ku(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=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Ra.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(qd.RemoteMute,((e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())})),this.engine.on(qd.Connected,this.handleReconnected).on(qd.SignalRestarted,this.handleReconnected).on(qd.SignalResumed,this.handleReconnected).on(qd.Restarting,this.handleReconnecting).on(qd.Resuming,this.handleReconnecting).on(qd.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(qd.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(qd.Disconnected,this.handleDisconnected).on(qd.SignalRequestResponse,this.handleSignalRequestResponse).on(qd.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return fc(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return fc(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return fc(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return fc(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,r)=>fc(t,void 0,void 0,(function*(){var t,a;try{let o=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(a=null!=n?n:this.name)&&void 0!==a?a:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),o=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!o;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield Rl(50)}r(new il("Request to update local metadata timed out","TimeoutError"))}catch(o){o instanceof Error&&r(o)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(pl.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(pl.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(pl.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit($d.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return fc(this,void 0,void 0,(function*(){this.encryptionType=e?Ra.GCM:Ra.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(e,t,i,n){return fc(this,void 0,void 0,(function*(){var s,r;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)){const 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 pl.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case pl.Source.Microphone:t=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case pl.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Qd(e)}}catch(o){throw null==t||t.forEach((e=>{e.stop()})),o instanceof Error&&this.emit($d.MediaDevicesError,o),this.pendingPublishing.delete(e),o}try{const e=[];for(const s of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ku(s))),e.push(this.publishTrack(s,n));const i=yield Promise.all(e);[a]=i}catch(o){throw null==t||t.forEach((e=>{e.stop()})),o}finally{this.pendingPublishing.delete(e)}}else if(!(null==a?void 0:a.track)&&this.pendingPublishing.has(e)&&(a=yield this.waitForPendingPublicationOfSource(e),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),a&&a.track)if(e===pl.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const e=this.getTrackPublication(pl.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a}))}enableCameraAndMicrophone(){return fc(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(pl.Source.Camera)&&!this.pendingPublishing.has(pl.Source.Microphone)){this.pendingPublishing.add(pl.Source.Camera),this.pendingPublishing.add(pl.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(pl.Source.Camera),this.pendingPublishing.delete(pl.Source.Microphone)}}}))}createTracks(e){return fc(this,void 0,void 0,(function*(){var t,i;null!=e||(e={});const n=hu(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield op(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map((e=>(ru(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=pl.Source.Microphone,this.emit($d.AudioStreamAcquired)),au(e)&&(this.cameraError=void 0,e.source=pl.Source.Camera),e)))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}}))}createScreenTracks(e){return fc(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Jd("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=rl();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")}()||(e.resolution=_l.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=Dl()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new Qd("no video track found");const s=new _h(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=pl.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit($d.AudioStreamAcquired);const e=new mh(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=pl.Source.ScreenShareAudio,r.push(e)}return r}))}publishTrack(e,t){return fc(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return fc(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,a,o;let c,d;if(cu(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),su(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case pl.Source.Microphone:t="audioinput";break;case pl.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new mh(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new _h(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Qd("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&&(d=t)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),ku(d))),d;const l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(r=null==t?void 0:t.forceStereo)&&void 0!==r?r:l;u&&(t||(t={}),void 0===t.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),ku(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(a=t.dtx)&&void 0!==a||(t.dtx=!1),null!==(o=t.red)&&void 0!==o||(t.red=!1));const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){const e=rl(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Vl(t,e.osVersion)>=0)||"Safari"===e.name&&Vl(t,e.version)>=0}()&&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)),h.simulcast=!1),h.source&&(e.source=h.source);const p=new Promise(((t,n)=>fc(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==Iu.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ku(e)}));const i=()=>fc(this,void 0,void 0,(function*(){try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}));setTimeout((()=>{this.engine.off(qd.SignalConnected,i),n(new tl("publishing rejected as engine not connected within timeout",408))}),15e3),this.engine.once(qd.SignalConnected,i),this.engine.on(qd.Closing,(()=>{this.engine.off(qd.SignalConnected,i),n(new tl("publishing rejected as engine closed",499))}))}else try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}catch(i){n(i)}}))));i.pendingPublishPromises.set(e,p);try{return yield p}catch(m){throw m}finally{i.pendingPublishPromises.delete(e)}}()}))}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ku(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map((e=>function(e){switch(e){case pa.CAMERA:return pl.Source.Camera;case pa.MICROPHONE:return pl.Source.Microphone;case pa.SCREEN_SHARE:return pl.Source.ScreenShare;case pa.SCREEN_SHARE_AUDIO:return pl.Source.ScreenShareAudio;default:return pl.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ku(e))),!1)}publish(e,t,i){return fc(this,void 0,void 0,(function*(){var n,s,r,a,o,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new tl("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((t=>su(e)&&t.source===e.source))&&e.source!==pl.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ku(e))),t.stopMicTrackOnMute&&ru(e)&&(e.stopOnMute=!0),e.source===pl.Source.ScreenShare&&Nl()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Dl())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Nl())return!1;if(Dl()){const e=rl();if((null==e?void 0:e.version)&&Vl(e.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=Xu),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>t.videoCodec===yu(e.mime)))||(t.videoCodec=yu(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(Zd.Muted,this.onTrackMuted),e.on(Zd.Unmuted,this.onTrackUnmuted),e.on(Zd.Ended,this.handleTrackEnded),e.on(Zd.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Zd.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Zd.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=new po({cid:e.mediaStreamTrack.id,name:t.name,type:pl.kindToProto(e.kind),muted:e.isMuted,source:pl.sourceToProto(e.source),disableDtx:!(null===(n=t.dtx)||void 0===n||n),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy});let g;if(e.kind===pl.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(b){const t=null!==(a=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==a?a:wl.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),ku(e)),{dims:i}))}m.width=i.width,m.height=i.height,ou(e)&&(Ol(p)&&(e.source===pl.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),ku(e))))),t.scalabilityMode=null!==(o=t.scalabilityMode)&&void 0!==o?o:"L3T3_KEY"),m.simulcastCodecs=[new ho({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:Xu}),t.backupCodec&&p!==t.backupCodec.codec&&m.encryption===Ra.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new ho({codec:t.backupCodec.codec,cid:""})))),g=Th(e.source===pl.Source.ScreenShare,m.width,m.height,t),m.layers=xh(m.width,m.height,g,Ol(t.videoCodec))}else e.kind===pl.Kind.Audio&&(g=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Xd("cannot publish track when not connected");const f=()=>fc(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new Xd("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,g),ou(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===pl.Source.ScreenShare||e.constraints.height&&Xl(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),g)if(Nl()&&e.kind===pl.Kind.Audio){let t;for(const 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===(n=g[0])||void 0===n?void 0:n.maxBitrate)?g[0].maxBitrate/1e3:0})}else e.codec&&Ol(e.codec)&&(null===(s=g[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:m.cid,codec:e.codec,maxbr:g[0].maxBitrate/1e3});yield this.engine.negotiate()}));let v;if(this.enabledPublishVideoCodecs.length>0)v=(yield Promise.all([this.engine.addTrack(m),f()]))[0];else{let i;if(v=yield this.engine.addTrack(m),v.codecs.forEach((e=>{void 0===i&&(i=e.mimeType)})),i&&e.kind===pl.Kind.Video){const n=yu(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ku(e)),{codec:n})),t.videoCodec=n,g=Th(e.source===pl.Source.ScreenShare,m.width,m.height,t))}yield f()}const y=new ap(e.kind,v,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return y.options=t,e.sid=v.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:g,trackInfo:v})),ou(e)?e.startMonitor(this.engine.client):cu(e)&&e.startMonitor(),this.addTrackPublication(y),this.emit($d.LocalTrackPublished,y),y}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return fc(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==Ra.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new Qd("track is not published");if(!ou(e))throw new Qd("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),a=function(e,t,i){var n,s,r,a;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&uc.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const o=e.mediaStreamTrack.getSettings(),c=null!==(n=o.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=o.height)&&void 0!==r?r:null===(a=e.dimensions)||void 0===a?void 0:a.height;return e.source===pl.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),Th(e.source===pl.Source.ScreenShare,c,d,i)}(e,t,r);if(!a)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ku(e)));const o=e.addSimulcastTrack(t,a);if(!o)return;const c=new po({cid:o.mediaStreamTrack.id,type:pl.kindToProto(e.kind),muted:e.isMuted,source:pl.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=xh(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new Xd("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>fc(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,o,r,a),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:d}))}))}unpublishTrack(e,t){return fc(this,void 0,void 0,(function*(){var i,n;if(su(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ku(e))),yield t)}const s=this.getPublicationForTrack(e),r=s?ku(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(e=s.track).off(Zd.Muted,this.onTrackMuted),e.off(Zd.Unmuted,this.onTrackUnmuted),e.off(Zd.Ended,this.handleTrackEnded),e.off(Zd.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Zd.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Zd.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let a=!1;const o=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<rh.FAILED&&o)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===o&&(e.direction="inactive",a=!0);if(this.engine.removeTrack(o)&&(a=!0),ou(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(a=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:c}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case pl.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case pl.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit($d.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return fc(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return fc(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 Promise(((n,s)=>fc(t,void 0,void 0,(function*(){try{const 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=>fc(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===pl.Source.ScreenShare||t.source===pl.Source.ScreenShareAudio||!cu(t)&&!ou(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(t){s(t)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return fc(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?Na.RELIABLE:Na.LOSSY,s=i.destinationIdentities,r=i.topic,a=new Aa({kind:n,value:{case:"user",value:new La({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r})}});yield t.engine.sendDataPacket(a,n)}()}))}publishDtmf(e,t){return fc(this,void 0,void 0,(function*(){const i=new Aa({kind:Na.RELIABLE,value:{case:"sipDtmf",value:new Ua({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Na.RELIABLE)}))}sendChatMessage(e,t){return fc(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new Aa({value:{case:"chatMessage",value:new Ba(Object.assign(Object.assign({},i),{timestamp:Js.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,Na.RELIABLE),this.emit($d.ChatMessage,i),i}))}editChatMessage(e,t){return fc(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new Aa({value:{case:"chatMessage",value:new Ba(Object.assign(Object.assign({},i),{timestamp:Js.parse(i.timestamp),editTimestamp:Js.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,Na.RELIABLE),this.emit($d.ChatMessage,i),i}))}sendText(e,t){return fc(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,r=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),a=new Array(r?r.length+1:1).fill(0),o=(e,i)=>{var n;a[i]=e;const s=a.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,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)=>fc(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 fc(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},r=new no({streamId:n,mimeType:s.mimeType,topic:s.topic,timestamp:nu(s.timestamp),totalLength:nu(null==e?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new to({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?eo.UPDATE:eo.CREATE})}}),a=null==e?void 0:e.destinationIdentities,o=new Aa({destinationIdentities:a,value:{case:"streamHeader",value:r}});yield this.engine.sendDataPacket(o,Na.RELIABLE);let c=0;const d=this,l=new WritableStream({write(e){return fc(this,void 0,void 0,(function*(){for(const t of function(e){const t=[];let i=(new TextEncoder).encode(e);for(;i.length>15e3;){let e=15e3;for(;e>0;){const t=i[e];if(void 0!==t&&128!=(192&t))break;e--}t.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&t.push(i),t}(e)){yield d.engine.waitForBufferStatusLow(Na.RELIABLE);const e=new so({content:t,streamId:n,chunkIndex:nu(c)}),i=new Aa({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield d.engine.sendDataPacket(i,Na.RELIABLE),c+=1}}))},close(){return fc(this,void 0,void 0,(function*(){const e=new ro({streamId:n}),t=new Aa({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield d.engine.sendDataPacket(t,Na.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let u=()=>fc(this,void 0,void 0,(function*(){yield h.close()}));d.engine.once(qd.Closing,u);const h=new Qh(l,s,(()=>this.engine.off(qd.Closing,u)));return h}))}sendFile(e,t){return fc(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return fc(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=t.stream().getReader();for(;;){const{done:e,value:t}=yield r.read();if(e)break;yield s.write(t)}return yield s.close(),s.info}))}streamBytes(e){return fc(this,void 0,void 0,(function*(){var t,i,n,s,r;const a=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),o=null==e?void 0:e.destinationIdentities,c={id:a,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown"},d=new no({totalLength:nu(null!==(r=c.size)&&void 0!==r?r:0),mimeType:c.mimeType,streamId:a,topic:c.topic,timestamp:nu(Date.now()),contentHeader:{case:"byteHeader",value:new io({name:c.name})}}),l=new Aa({destinationIdentities:o,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(l,Na.RELIABLE);let u=0;const h=new Is,p=this.engine,m=this.log,g=new WritableStream({write(e){return fc(this,void 0,void 0,(function*(){const t=yield h.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3);yield p.waitForBufferStatusLow(Na.RELIABLE);const n=new Aa({destinationIdentities:o,value:{case:"streamChunk",value:new so({content:t,streamId:a,chunkIndex:nu(u)})}});yield p.sendDataPacket(n,Na.RELIABLE),u+=1,i+=t.byteLength}}finally{t()}}))},close(){return fc(this,void 0,void 0,(function*(){const e=new ro({streamId:a}),t=new Aa({destinationIdentities:o,value:{case:"streamTrailer",value:e}});yield p.sendDataPacket(t,Na.RELIABLE)}))},abort(e){m.error("Sink error:",e)}});return new Yh(g,c)}))}performRpc(e){return fc(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:r=1e4}=e;return function*(){return new Promise(((e,a)=>fc(t,void 0,void 0,(function*(){var t,o,c,d;if(dh(s)>15360)return void a(ch.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(o=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===o?void 0:o.version)&&Vl(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void a(ch.builtIn("UNSUPPORTED_SERVER"));const l=crypto.randomUUID();yield this.publishRpcRequest(i,l,n,s,r-2e3);const u=setTimeout((()=>{this.pendingAcks.delete(l),a(ch.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(h)}),2e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:i});const h=setTimeout((()=>{this.pendingResponses.delete(l),a(ch.builtIn("RESPONSE_TIMEOUT"))}),r);this.pendingResponses.set(l,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(l)&&(console.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?a(i):e(null!=t?t:"")},participantIdentity:i})}))))}()}))}registerRpcMethod(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){const 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){const 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,s){return fc(this,void 0,void 0,(function*(){const r=new Aa({destinationIdentities:[e],kind:Na.RELIABLE,value:{case:"rpcRequest",value:new $a({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,Na.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,ch.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return e.sid===this.sid&&!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ku(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(cu(n)||ou(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return fc(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[i]=t;return i.source===e}));if(t)return t[1];yield Rl(20)}}))}}class lp extends rp{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=ul.HIGH,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Zd.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new So({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Za({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Zd.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?rp.SubscriptionStatus.Unsubscribed:super.isSubscribed?rp.SubscriptionStatus.Subscribed:rp.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?rp.PermissionStatus.Allowed:rp.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(uu(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&uu(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(Zd.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Zd.VisibilityChanged,this.handleVisibilityChange),n.off(Zd.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Zd.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Zd.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Zd.VisibilityChanged,this.handleVisibilityChange),e.on(Zd.Ended,this.handleEnded),this.emit(Zd.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Zd.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Zd.Muted:Zd.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Zd.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Zd.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===pl.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return uu(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Co({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=ul.HIGH,this.emit(Zd.UpdateSettings,e)}}class up extends cp{static fromParticipantInfo(e,t,i){return new up(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,s,r,a){super(t,i||"",n,s,r,a,arguments.length>7&&void 0!==arguments[7]?arguments[7]:_a.STANDARD),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(Zd.UpdateSettings,(t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),ku(e))),this.signalClient.sendUpdateTrackSettings(t)})),e.on(Zd.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(Zd.SubscriptionPermissionChanged,(t=>{this.emit($d.TrackSubscriptionPermissionChanged,e,t)})),e.on(Zd.SubscriptionStatusChanged,(t=>{this.emit($d.TrackSubscriptionStatusChanged,e,t)})),e.on(Zd.Subscribed,(t=>{this.emit($d.TrackSubscribed,t,e)})),e.on(Zd.Unsubscribed,(t=>{this.emit($d.TrackUnsubscribed,t,e)})),e.on(Zd.SubscriptionFailed,(t=>{this.emit($d.TrackSubscriptionFailed,e.trackSid,t)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:pl.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:pl.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,r){let a,o=this.getTrackPublicationBySid(t);return o||t.startsWith("TR")||this.trackPublications.forEach((t=>{o||e.kind!==t.kind.toString()||(o=t)})),o?"ended"===e.readyState?(this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ku(o))),void this.emit($d.TrackSubscriptionFailed,t)):(a="video"===e.kind?new tp(e,t,n,s):new ep(e,t,n,this.audioContext,this.audioOutput),a.source=o.source,a.isMuted=o.isMuted,a.setMediaStream(i),a.start(),o.setTrack(a),this.volumeMap.has(o.source)&&du(a)&&ru(a)&&a.setVolume(this.volumeMap.get(o.source)),o):0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit($d.TrackSubscriptionFailed,t)):(void 0===r&&(r=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,r-1)}),150))}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach((e=>{var n,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const t=pl.kindFromProto(e.type);if(!t)return;r=new lp(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(e),i.set(e.sid,r);const a=Array.from(this.trackPublications.values()).find((e=>e.source===(null==r?void 0:r.source)));a&&r.source!==pl.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:ku(a),newTrack:ku(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),ku(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit($d.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case pl.Kind.Audio:this.audioTrackPublications.delete(e);break;case pl.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit($d.TrackUnpublished,i)}setAudioOutput(e){return fc(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;ru(i.track)&&du(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new 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)}}($h=Bh||(Bh={})).Disconnected="disconnected",$h.Connecting="connecting",$h.Connected="connected",$h.Reconnecting="reconnecting",$h.SignalReconnecting="signalReconnecting";class hp extends kc.EventEmitter{constructor(e){var t,i,n,s;if(super(),t=this,this.state=Bh.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=uc,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(e,t,i)=>fc(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!xl()&&!Il())throw Ul()?Error("WebRTC isn't detected, have you called registerGlobals?"):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.");const s=yield this.disconnectLock.lock();if(this.state===Bh.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(Bh.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),jl(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Hh(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const r=(n,a,o)=>fc(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{yield this.attemptConnection(null!=o?o:e,t,i,l),this.abortController=void 0,n()}catch(u){if(this.regionUrlProvider&&u instanceof Wd&&u.reason!==Nd.Cancelled&&u.reason!==Nd.NotAllowed){let e=null;try{e=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(h){if(h instanceof Wd&&(401===h.status||h.reason===Nd.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void a(h)}e&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(u.message,". Retrying with another region: ").concat(e),this.logContext),this.recreateEngine(),yield r(n,a,e)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,tu(u)),a(u))}else{let e=va.UNKNOWN_REASON;u instanceof Wd&&(e=tu(u)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),a(u)}}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Yl(((e,t)=>{r(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,r)=>fc(this,void 0,void 0,(function*(){var a,o,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(a=d.room)||void 0===a?void 0:a.name,roomSid:null===(o=d.room)||void 0===o?void 0:o.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Yd("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(i){this.log.error(i instanceof Error?i.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:i}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>fc(this,void 0,void 0,(function*(){var s,r;this.state===Bh.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},sh),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(Fd.SignalConnected)}catch(a){yield this.engine.close(),this.recreateEngine();const e=new Wd("could not establish signal connection",Nd.ServerUnreachable);throw a instanceof Error&&(e.message="".concat(e.message,": ").concat(a.message)),a instanceof Wd&&(e.reason=a.reason,e.status=a.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:a})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Wd("Connection attempt aborted",Nd.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(o){throw yield this.engine.close(),this.recreateEngine(),o}Ll()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ll()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Bh.Connected),this.emit(Fd.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return fc(t,[...i],void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s,r;const a=yield e.disconnectLock.lock();try{if(e.state===Bh.Disconnected)return void e.log.debug("already disconnected",e.logContext);e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===Bh.Connecting||e.state===Bh.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null===(i=e.abortController)||void 0===i||i.abort(),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new Wd("Client initiated disconnect",Nd.Cancelled)),e.connectFuture=void 0),(null===(r=e.engine)||void 0===r?void 0:r.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,va.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()}))},this.onPageLeave=()=>fc(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>fc(this,void 0,void 0,(function*(){const e=[],t=rl();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=Ql();e.enabled=!0;const 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(Fd.Disconnected,(()=>{null==i||i.remove(),i=null}))}e.push(i)}this.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(i){throw this.handleAudioPlaybackFailed(i),i}})),this.startVideo=()=>fc(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||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=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Bh.Reconnecting)&&this.emit(Fd.Reconnecting)},this.handleSignalRestarted=e=>fc(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(t){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:t}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(i){return}this.setAndEmitConnectionState(Bh.Connected),this.emit(Fd.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))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===Ea.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=e=>{const 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{const 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.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emitWhenConnected(Fd.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{const 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))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(Fd.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=pl.streamStateFromProto(e.state);n!==i.track.streamState&&(i.track.streamState=n,t.emit($d.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Fd.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case)this.handleStreamHeader(e.value.value,e.participantIdentity);else if("streamChunk"===e.value.case)this.handleStreamChunk(e.value.value);else if("streamTrailer"===e.value.case)this.handleStreamTrailer(e.value.value);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(Fd.DataReceived,t.payload,e,i,t.topic),null==e||e.emit($d.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(Fd.SipDTMFReceived,t,e),null==e||e.emit($d.SipDTMFReceived,t)},this.bufferedSegments=new Map,this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:r,endTime:a,final:o}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return o?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(a.toString()),final:o,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(t,this.transcriptionReceivedTimes);null==n||n.emit(Zd.TranscriptionReceived,s),null==i||i.emit($d.TranscriptionReceived,s,n),this.emit(Fd.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(Fd.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(Fd.MetricsReceived,e,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Fd.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(Fd.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Fd.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Fd.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>fc(this,void 0,void 0,(function*(){var e,t,i;const n=wu.getInstance().previousDevices,s=yield wu.getInstance().getDevices(void 0,!1),r=rl();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let o of s){const e=n.find((e=>e.deviceId===o.deviceId));e&&""!==e.label&&e.kind===o.kind&&e.label!==o.label&&"default"===this.getActiveDevice(o.kind)&&this.emit(Fd.ActiveDeviceChanged,o.kind,o.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let o of a){const r=fu(o),a=this.localParticipant.getTrackPublication(r);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter((e=>e.kind===o)),d=this.getActiveDevice(o);d===(null===(t=n.filter((e=>e.kind===o))[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(o,c[0].deviceId):"audioinput"===o&&!Dl()||"videoinput"===o||c.length>0&&!c.find((e=>e.deviceId===this.getActiveDevice(o)))&&(yield this.switchActiveDevice(o,c[0].deviceId))}this.emit(Fd.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Fd.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(Fd.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=e=>{this.emit(Fd.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Fd.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Fd.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Fd.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Fd.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>fc(this,void 0,void 0,(function*(){var t,i,n,s,r,a;null===(t=e.track)||void 0===t||t.on(Zd.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(Zd.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(Fd.LocalTrackPublished,e,this.localParticipant),cu(e.track)&&(yield e.track.checkForSilence())&&this.emit(Fd.LocalAudioSilenceDetected,e);const o=yield null===(a=e.track)||void 0===a?void 0:a.getDeviceId(!1),c=vu(e.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,o),this.emit(Fd.ActiveDeviceChanged,c,o))})),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(Zd.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(Zd.Restarted,this.onLocalTrackRestarted),this.emit(Fd.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>fc(this,void 0,void 0,(function*(){const t=yield e.getDeviceId(!1),i=vu(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(Fd.ActiveDeviceChanged,i,t))})),this.onLocalConnectionQualityChanged=e=>{this.emit(Fd.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=e=>{this.emit(Fd.MediaDevicesError,e)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Fd.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Fd.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},nh),e),this.log=hc(null!==(i=this.options.loggerName)&&void 0!==i?i:oc.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},th),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ih),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},eh),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Is,this.localParticipant=new dp("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Xl(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Xl(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Xl(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE(),Ll()){const e=new AbortController;null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),hp.cleanupRegistry&&hp.cleanupRegistry.register(this,(()=>{e.abort()}))}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(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)}handleIncomingRpcRequest(e,t,i,n,s,r){return fc(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==r)return void(yield this.engine.publishRpcResponse(e,t,null,ch.builtIn("UNSUPPORTED_VERSION")));const a=this.rpcHandlers.get(i);if(!a)return void(yield this.engine.publishRpcResponse(e,t,null,ch.builtIn("UNSUPPORTED_METHOD")));let o=null,c=null;try{const r=yield a({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});dh(r)>15360?(o=ch.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=r}catch(d){d instanceof ch?o=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),o=ch.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,o)}))}setE2EEEnabled(e){return fc(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Su(this.options.e2ee),this.e2eeManager.on(Id.ParticipantEncryptionStatusChanged,((e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(Fd.ParticipantEncryptionStatusChanged,e,t)})),this.e2eeManager.on(Id.EncryptionError,(e=>this.emit(Fd.EncryptionError,e))),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?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?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return fc(this,void 0,void 0,(function*(){return this.state===Bh.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(qd.RoomUpdate,i),e(t.sid))};this.engine.on(qd.RoomUpdate,i),this.once(Fd.Disconnected,(()=>{this.engine.off(qd.RoomUpdate,i),t("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Kh(this.options),this.engine.on(qd.ParticipantUpdate,this.handleParticipantUpdates).on(qd.RoomUpdate,this.handleRoomUpdate).on(qd.SpeakersChanged,this.handleSpeakersChanged).on(qd.StreamStateChanged,this.handleStreamStateUpdate).on(qd.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(qd.SubscriptionError,this.handleSubscriptionError).on(qd.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(qd.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(qd.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(qd.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(qd.DataPacketReceived,this.handleDataPacket).on(qd.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Bh.SignalReconnecting)&&this.emit(Fd.SignalReconnecting)})).on(qd.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Bh.Connected)&&this.emit(Fd.Reconnected)})).on(qd.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Bh.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(qd.Restarting,this.handleRestarting).on(qd.SignalRestarted,this.handleSignalRestarted).on(qd.Offline,(()=>{this.setAndEmitConnectionState(Bh.Reconnecting)&&this.emit(Fd.Reconnecting)})).on(qd.DCBufferStatusChanged,((e,t)=>{this.emit(Fd.DCBufferStatusChanged,e,t)})).on(qd.LocalTrackSubscribed,(e=>{const t=this.localParticipant.getTrackPublications().find((t=>{let{trackSid:i}=t;return i===e}));t?(this.localParticipant.emit($d.LocalTrackSubscribed,t),this.emitWhenConnected(Fd.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return wu.getInstance().getDevices(e,t)}prepareConnection(e,t){return fc(this,void 0,void 0,(function*(){if(this.state===Bh.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(jl(new URL(e))&&t){this.regionUrlProvider=new Hh(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Bh.Disconnected&&(this.regionUrl=i,yield fetch(eu(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(eu(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return fc(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Zo({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Zo({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Zo({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Zo({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=()=>fc(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Zo({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>fc(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Zo({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 Zo({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>fc(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new _o({reason:va.CLIENT_INITIATED,action:Po.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Zo({scenario:{case:"subscriberBandwidth",value:nu(t)}});break;case"leave-full-reconnect":i=new Zo({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 fc(this,arguments,void 0,(function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,a,o,c,d,l,u;let h=!0,p=!1;const m=n?{exact:t}:t;if("audioinput"===e){p=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===pl.Source.Microphone));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.audioCaptureDefaults.deviceId=t,g}}else if("videoinput"===e){p=0===i.localParticipant.videoTrackPublications.size;const t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===pl.Source.Camera));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.videoCaptureDefaults.deviceId=t,g}}else if("audiooutput"===e){if(!Al()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");i.options.webAudioMix&&(t=null!==(a=yield wu.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==a?a:""),null!==(o=(u=i.options).audioOutput)&&void 0!==o||(u.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(g){throw i.options.audioOutput.deviceId=n,g}}return(p||"audiooutput"===e)&&(i.localParticipant.activeDeviceMap.set(e,"audiooutput"===e&&(null===(l=i.options.audioOutput)||void 0===l?void 0:l.deviceId)||t),i.emit(Fd.ActiveDeviceChanged,e,t)),h}()}))}setupLocalParticipantEvents(){this.localParticipant.on($d.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on($d.ParticipantNameChanged,this.onLocalParticipantNameChanged).on($d.AttributesChanged,this.onLocalAttributesChanged).on($d.TrackMuted,this.onLocalTrackMuted).on($d.TrackUnmuted,this.onLocalTrackUnmuted).on($d.LocalTrackPublished,this.onLocalTrackPublished).on($d.LocalTrackUnpublished,this.onLocalTrackUnpublished).on($d.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on($d.MediaDevicesError,this.onMediaDevicesError).on($d.AudioStreamAcquired,this.startAudio).on($d.ChatMessage,this.onLocalChatMessageSent).on($d.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===Bh.Connecting||this.state===Bh.Reconnecting){const n=()=>{this.onTrackAdded(e,t,i),s()},s=()=>{this.off(Fd.Reconnected,n),this.off(Fd.Connected,n),this.off(Fd.Disconnected,s)};return this.once(Fd.Reconnected,n),this.once(Fd.Connected,n),void this.once(Fd.Disconnected,s)}if(this.state===Bh.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);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let r=n[1],a=e.id;if(r&&r.startsWith("TR")&&(a=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const o=Array.from(this.remoteParticipants.values()).find((e=>e.sid===s));if(!o)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),o.addSubscribedMediaTrack(e,a,t,i,c)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Bh.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((t=>{var i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off($d.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off($d.ParticipantNameChanged,this.onLocalParticipantNameChanged).off($d.AttributesChanged,this.onLocalAttributesChanged).off($d.TrackMuted,this.onLocalTrackMuted).off($d.TrackUnmuted,this.onLocalTrackUnmuted).off($d.LocalTrackPublished,this.onLocalTrackPublished).off($d.LocalTrackUnpublished,this.onLocalTrackUnpublished).off($d.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off($d.MediaDevicesError,this.onMediaDevicesError).off($d.AudioStreamAcquired,this.startAudio).off($d.ChatMessage,this.onLocalChatMessageSent).off($d.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),Ll()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Bh.Disconnected),this.emit(Fd.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit(Fd.ParticipantDisconnected,t),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return fc(this,void 0,void 0,(function*(){var i;if("byteHeader"===e.contentHeader.case){const n=this.byteStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const r={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:iu(e.timestamp),attributes:e.attributes},a=new ReadableStream({start:t=>{s=t,this.byteStreamControllers.set(e.streamId,{info:r,controller:s,startTime:Date.now()})}});n(new Gh(r,a,iu(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){const i=this.textStreamHandlers.get(e.topic);if(!i)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let n;const 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},r=new ReadableStream({start:t=>{n=t,this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now()})}});i(new Wh(s,r,iu(e.totalLength)),{identity:t})}}))}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return fc(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=gu())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),Rl(200)])}catch(n){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:n}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Fd.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var i;let n;return n=t?up.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new up(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?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)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Fd.ParticipantConnected,i),i.on($d.TrackPublished,(e=>{this.emitWhenConnected(Fd.TrackPublished,e,i)})).on($d.TrackSubscribed,((e,t)=>{e.kind===pl.Kind.Audio?(e.on(Zd.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Zd.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===pl.Kind.Video&&(e.on(Zd.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Zd.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Fd.TrackSubscribed,e,t,i)})).on($d.TrackUnpublished,(e=>{this.emit(Fd.TrackUnpublished,e,i)})).on($d.TrackUnsubscribed,((e,t)=>{this.emit(Fd.TrackUnsubscribed,e,t,i)})).on($d.TrackMuted,(e=>{this.emitWhenConnected(Fd.TrackMuted,e,i)})).on($d.TrackUnmuted,(e=>{this.emitWhenConnected(Fd.TrackUnmuted,e,i)})).on($d.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(Fd.ParticipantMetadataChanged,e,i)})).on($d.ParticipantNameChanged,(e=>{this.emitWhenConnected(Fd.ParticipantNameChanged,e,i)})).on($d.AttributesChanged,(e=>{this.emitWhenConnected(Fd.ParticipantAttributesChanged,e,i)})).on($d.ConnectionQualityChanged,(e=>{this.emitWhenConnected(Fd.ConnectionQualityChanged,e,i)})).on($d.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(Fd.ParticipantPermissionsChanged,e,i)})).on($d.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(Fd.TrackSubscriptionStatusChanged,e,t,i)})).on($d.TrackSubscriptionFailed,((e,t)=>{this.emit(Fd.TrackSubscriptionFailed,e,i,t)})).on($d.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(Fd.TrackSubscriptionPermissionChanged,e,t,i)})),t&&i.updateInfo(t),i}sendSyncState(){const 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(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&lu(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=dl.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,va.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&dl.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Fd.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=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===Bh.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Bh.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return fc(this,void 0,void 0,(function*(){var t,i;const n=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 Ta({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Js.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new wa({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Fd.SignalConnected),this.emit(Fd.Connected),this.setAndEmitConnectionState(Bh.Connected),n.video){const e=new ap(pl.Kind.Video,new Ia({source:pa.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:ha.AUDIO,name:"video-dummy"}),new _h(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Wl(160*(null!==(t=s.aspectRatios[0])&&void 0!==t?t: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($d.LocalTrackPublished,e)}if(n.audio){const e=new ap(pl.Kind.Audio,new Ia({source:pa.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:ha.AUDIO}),new mh(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ql(),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($d.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new wa({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Ea.ACTIVE,tracks:[],joinedAt:Js.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=Wl(160*(null!==(i=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),a=new Ia({source:pa.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:ha.AUDIO});n.addSubscribedMediaTrack(r,a.sid,new MediaStream([r]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(s.audio){const e=Ql(),i=new Ia({source:pa.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:ha.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==Fd.ActiveSpeakersChanged&&e!==Fd.TranscriptionReceived){const t=pp(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function pp(e){return e.map((e=>{if(e)return Array.isArray(e)?pp(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}hp.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()})),(qh=Vh||(Vh={}))[qh.IDLE=0]="IDLE",qh[qh.RUNNING=1]="RUNNING",qh[qh.SKIPPED=2]="SKIPPED",qh[qh.SUCCESS=3]="SUCCESS",qh[qh.FAILED=4]="FAILED",kc.EventEmitter,kc.EventEmitter;const mp=Object.freeze(Object.defineProperty({__proto__:null,ObiSession:class{constructor(e={}){this.currentState=Rn.READY,this.assistantAudioContext=null,this.userAudioContext=null,this.emitter=Ss(),this.apiBaseUrl=e.apiBaseUrl||"/api",this.token=e.token}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async connect(e={}){if(this.token=e.token??this.token??new URLSearchParams(window.location.search).get("token")??void 0,!this.token)return console.error("No token found"),void this.emitter.emit("error",{session:this,error:new Error("No session token provided")});await this.requestMicrophone();try{this.room=new hp({adaptiveStream:!0,dynacast:!0}),this.room.on(Fd.LocalTrackUnpublished,(e=>{console.log("Local track unpublished",e.source),e.source===pl.Source.ScreenShare&&(this.screenStream=void 0)})),this.room.on(Fd.Disconnected,(()=>{console.log("LiveKit room disconnected"),this.disconnect()})),this.room.on(Fd.ParticipantDisconnected,(()=>{this.disconnect()})),this.room.on(Fd.TrackSubscribed,((e,t,i)=>{if("audio"===e.kind&&e.attach(),e.source===pl.Source.Microphone&&i.identity.includes("agent-")){const t=e.mediaStream;if(!t)return void console.error("No media stream available for assistant track");const i=new AudioContext,n=i.createAnalyser();i.createMediaStreamSource(t).connect(n),n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,s,"ASSISTANT"),this.assistantAudioContext=i}})),this.room.on(Fd.ParticipantAttributesChanged,(e=>{if(!e["lk.agent.state"])return;if(this.currentState===Rn.RESEARCHING||this.currentState===Rn.PAUSED)return;const t=Ge(e["lk.agent.state"]).with("listening",(()=>Rn.USER_SPEAKING)).with("speaking",(()=>Rn.AGENT_SPEAKING)).with("thinking",(()=>Rn.AGENT_SPEAKING)).otherwise((()=>{}));t&&this.setState(t)})),this.room.on(Fd.DataReceived,(async e=>{try{const t=JSON.parse((new TextDecoder).decode(e));Ge(t.status||t.request).with("using_tool",(()=>{const e=this.currentState;this.currentState=Rn.RESEARCHING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:e})})).with("using_tool_ended",(()=>{const e=this.currentState;this.currentState=Rn.AGENT_SPEAKING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:e})})).with("share_screen",(()=>{this.shareScreen()})).with("prompt_user",(()=>{this.promptContinue()})).with("capture_page_html",(()=>{this.emitter.emit("capturePageHTML",{session:this})})).otherwise((()=>{console.warn("Unknown data received:",t)}))}catch(t){console.error("Error parsing data:",t)}}));const e=`${this.apiBaseUrl}/join-token?token=${this.token}`,t=await fetch(e).then((e=>e.json()));if(await this.room.connect(t.url,t.token),this.microphoneStream){const e=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(e,{name:"microphone",source:pl.Source.Microphone})}}catch(t){throw console.error("Failed to connect to LiveKit:",t),this.disconnect(),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))}),t}}disconnect(){this.room&&this.room.disconnect(!0),this.screenStream?.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach((e=>e.stop())),this.setState(Rn.READY)}setState(e){if(e===this.currentState)return;const t=this.currentState;this.currentState=e,this.emitter.emit("stateChanged",{session:this,newState:e,oldState:t})}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const i=t.createAnalyser(),n=t.createMediaStreamSource(e),s=t.createGain();s.gain.value=1.5,n.connect(s),s.connect(i),i.fftSize=2048;const r=new Uint8Array(i.frequencyBinCount);this.analyzeAudio(i,r,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){this.emitter.emit("preScreenShare",{session:this});try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream)return void console.warn("Failed to share screen");await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",{session:this,error:e instanceof Error?e:new Error(String(e))})}}pauseRecording(){this.room&&(this.setState(Rn.PAUSED),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleMuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!1))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!1)),this.screenStream?.track?.mute(),this.userAudioContext&&this.userAudioContext.resume(),this.assistantAudioContext&&this.assistantAudioContext.resume())}resumeRecording(){this.room&&(this.setState(Rn.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleUnmuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!0))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!0)),this.screenStream?.track?.unmute())}async promptContinue(){await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,i){e.getByteFrequencyData(t);const n=t.reduce(((e,t)=>e+t),0)/t.length,s=Math.max(.01,Math.min(1,n/128));"USER"===i&&this.currentState===Rn.USER_SPEAKING?this.emitter.emit("volume",{speaker:"USER",spectrum:Array.from(t),volume:s}):"ASSISTANT"===i&&this.currentState===Rn.AGENT_SPEAKING&&this.emitter.emit("volume",{speaker:"ASSISTANT",spectrum:Array.from(t),volume:s}),setTimeout((()=>this.analyzeAudio(e,t,i)),50)}async sendHTML(e){if(this.room)try{const t={type:"page_content",html:e,timestamp:(new Date).toISOString()},i=JSON.stringify(t),n=(new TextEncoder).encode(i);await this.room.localParticipant.publishData(n,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))})}else console.log("Cannot send HTML: Not connected to LiveKit room")}}},Symbol.toStringTag,{value:"Module"}));return e.EventType=Pn,e.ObiAssistant=class{static init(e){customElements.get("obi-widget")||customElements.define("obi-widget",Ts);const t=document.createElement("obi-widget");return e.apiKey&&(t.apiKey=e.apiKey),e.position&&(t.position=e.position),e.user&&(t.user=e.user),window.obiWidgetConfig=e,document.body.appendChild(t),console.log("Obi Widget initialized and mounted"),t}},e.ObiSDK=class{constructor(e={}){this.state=Rn.READY,this.emitter=Ss(),this.voiceEnabled=!1,this.screenCaptureEnabled=!1,this.config=_n.parse(e),this.config.debug&&console.log("ObiSDK initialized with config:",this.config)}async init(){try{this.config.enableVoice&&await this.initVoice(),this.config.enableScreenCapture&&await this.initScreenCapture(),this.setState(Rn.READY),this.emitter.emit(Pn.READY),this.config.debug&&console.log("ObiSDK ready")}catch(e){const t={code:"init_failed",message:"Failed to initialize SDK",details:e};this.handleError(t)}}async initVoice(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getUserMedia)throw new Error("Voice recording not supported in this browser");try{await window.navigator.mediaDevices.getUserMedia({audio:!0}),this.voiceEnabled=!0,this.config.debug&&console.log("Voice capabilities initialized")}catch(e){throw new Error(`Microphone access denied: ${e}`)}}async initScreenCapture(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getDisplayMedia)throw new Error("Screen capture not supported in this browser");this.screenCaptureEnabled=!0,this.config.debug&&console.log("Screen capture capabilities initialized")}setState(e){this.state=e,this.emitter.emit(Pn.STATE_CHANGE,e)}handleError(e){this.setState(Rn.ERROR),this.emitter.emit(Pn.ERROR,e),this.config.debug&&console.error("ObiSDK error:",e)}async startVoiceRecording(){if(this.voiceEnabled)try{this.setState(Rn.AGENT_SPEAKING),this.emitter.emit(Pn.VOICE_START),this.config.debug&&console.log("Voice recording started")}catch(e){this.handleError({code:"voice_start_failed",message:"Failed to start voice recording",details:e})}else this.handleError({code:"voice_disabled",message:"Voice recording is not enabled or available"})}async stopVoiceRecording(){if(this.state===Rn.READY)return{transcript:void 0};try{const e={transcript:"Sample transcript"};return this.setState(Rn.READY),this.emitter.emit(Pn.VOICE_STOP,e),this.config.debug&&console.log("Voice recording stopped:",e),e}catch(e){return this.handleError({code:"voice_stop_failed",message:"Failed to stop voice recording",details:e}),{transcript:void 0}}}async startScreenCapture(){if(this.screenCaptureEnabled)try{this.setState(Rn.AGENT_SPEAKING),this.emitter.emit(Pn.SCREEN_CAPTURE_START),this.config.debug&&console.log("Screen capture started")}catch(e){this.handleError({code:"screen_capture_start_failed",message:"Failed to start screen capture",details:e})}else this.handleError({code:"screen_capture_disabled",message:"Screen capture is not enabled or available"})}async stopScreenCapture(){if(this.state===Rn.READY)return{screenshot:void 0};try{const e={screenshot:"data:image/png;base64,..."};return this.setState(Rn.READY),this.emitter.emit(Pn.SCREEN_CAPTURE_STOP,e),this.config.debug&&console.log("Screen capture stopped"),e}catch(e){return this.handleError({code:"screen_capture_stop_failed",message:"Failed to stop screen capture",details:e}),{screenshot:void 0}}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getState(){return this.state}dispose(){this.emitter.all.clear(),this.config.debug&&console.log("ObiSDK disposed")}},e.ObiWidget=Ts,e.SDKState=Rn,e.initObi=async e=>(ws.obiWidgetConfig=e,new Promise(((t,i)=>{if(ws.ObiAssistant)try{const i=_s(e);return void t(i)}catch(n){return void i(new Error(`Error creating widget: ${n}`))}ws.__obiSDKLoading?function(){const s=setInterval((()=>{"function"!=typeof ws.ObiAssistant&&"object"!=typeof ws.ObiAssistant||(clearInterval(s),(()=>{try{const i=_s(e);t(i)}catch(n){i(new Error(`Error creating widget after waiting: ${n}`))}})())}),100)}():async function(){return new Promise((e=>{try{const t=new XMLHttpRequest;t.open("GET","https://registry.npmjs.org/obi-sdk/latest"),t.onload=()=>{if(200===t.status)try{const i=JSON.parse(t.responseText);e(i.version)}catch(i){e(null)}else e(null)},t.onerror=()=>e(null),t.send()}catch(t){e(null)}}))}().then((s=>{Es(s,(()=>{ws.__obiSDKLoading=!1;try{const i=_s(e);t(i)}catch(n){i(new Error(`Error creating widget after loading SDK: ${n}`))}}),i)})).catch((()=>{Es(null,(()=>{ws.__obiSDKLoading=!1;try{const i=_s(e);t(i)}catch(n){i(new Error(`Error creating widget with latest version: ${n}`))}}),i)}))}))),Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
531
531
  //# sourceMappingURL=obi-sdk.standalone.iife.js.map