livekit-client 1.14.2 → 1.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/livekit-client.esm.mjs +157 -111
- package/dist/livekit-client.esm.mjs.map +1 -1
- package/dist/livekit-client.umd.js +1 -1
- package/dist/livekit-client.umd.js.map +1 -1
- package/dist/src/room/PCTransport.d.ts.map +1 -1
- package/dist/src/room/RTCEngine.d.ts.map +1 -1
- package/dist/src/room/Room.d.ts +1 -1
- package/dist/src/room/Room.d.ts.map +1 -1
- package/dist/src/room/events.d.ts +2 -0
- package/dist/src/room/events.d.ts.map +1 -1
- package/dist/src/room/participant/LocalParticipant.d.ts.map +1 -1
- package/dist/src/room/participant/Participant.d.ts +1 -0
- package/dist/src/room/participant/Participant.d.ts.map +1 -1
- package/dist/src/room/track/Track.d.ts.map +1 -1
- package/dist/ts4.2/src/room/Room.d.ts +1 -1
- package/dist/ts4.2/src/room/events.d.ts +2 -0
- package/dist/ts4.2/src/room/participant/Participant.d.ts +1 -0
- package/package.json +4 -4
- package/src/room/PCTransport.ts +6 -4
- package/src/room/RTCEngine.ts +7 -7
- package/src/room/Room.ts +4 -2
- package/src/room/events.ts +4 -0
- package/src/room/participant/LocalParticipant.ts +3 -12
- package/src/room/participant/Participant.ts +1 -0
- package/src/room/track/Track.ts +6 -1
@@ -1,2 +1,2 @@
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(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 i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r={exports:{}};!function(e){var t,n;t=i,n=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"];function r(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(t,i){for(var r=0;r<n.length;r++){var s=n[r];this[s]=r<t?e:this.methodFactory(s,t,i)}this.log=this.debug}function a(e,i,n){return function(){typeof console!==t&&(o.call(this,i,n),this[e].apply(this,arguments))}}function c(n,o,c){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?s:void 0!==console[n]?r(console,n):void 0!==console.log?r(console,"log"):e)}(n)||a.apply(this,arguments)}function d(e,i,r){var s,a=this;i=null==i?"WARN":i;var d="loglevel";function u(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=i.indexOf(encodeURIComponent(d)+"=");-1!==n&&(e=/^([^;]+)/.exec(i.slice(n))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=r||c,a.getLevel=function(){return s},a.setLevel=function(i,r){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(s=i,!1!==r&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+i+";"}catch(e){}}}(i),o.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,u()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var l=u();null==l&&(l=i),a.setLevel(l,!1)}var u=new d,l={};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=l[e];return t||(t=l[e]=new d(e,u.getLevel(),u.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=h),u},u.getLoggers=function(){return l},u.default=u,u},e.exports?e.exports=n():t.log=n()}(r);var s,o=r.exports;e.LogLevel=void 0,(s=e.LogLevel||(e.LogLevel={}))[s.trace=0]="trace",s[s.debug=1]="debug",s[s.info=2]="info",s[s.warn=3]="warn",s[s.error=4]="error",s[s.silent=5]="silent";const a=o.getLogger("livekit");function c(e,t){if(!e)throw new Error(t)}a.setDefaultLevel(e.LogLevel.info),o.getLogger("lk-e2ee");const d=34028234663852886e22,u=-34028234663852886e22,l=4294967295,h=2147483647,p=-2147483648;function m(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>h||e<p)throw new Error("invalid int 32: "+e)}function f(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>l||e<0)throw new Error("invalid uint 32: "+e)}function v(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>d||e<u))throw new Error("invalid float 32: "+e)}const g=Symbol("@bufbuild/protobuf/enum-type");function y(e){const t=e[g];return c(t,"missing enum type on enum object"),t}function k(e,t,i,n){e[g]=b(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function b(e,t,i){const n=Object.create(null),r=Object.create(null),s=[];for(const e of t){const t=S(e);s.push(t),n[e.name]=t,r[e.no]=t}return{typeName:e,values:s,findName:e=>n[e],findNumber:e=>r[e]}}function T(e,t,i){const n={};for(const e of t){const t=S(e);n[t.localName]=t.no,n[t.no]=t.localName}return k(n,e,t),n}function S(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class w{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,r=n.makeReadOptions(t);return n.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}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}}var E;function C(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,0==(128&n))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,0==(128&i))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,0==(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function P(e,t,i){for(let n=0;n<28;n+=7){const r=e>>>n,s=!(r>>>7==0&&0==t),o=255&(s?128|r:r);if(i.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,r=!(t>>3==0);if(i.push(255&(r?128|n:n)),r){for(let e=3;e<31;e+=7){const n=t>>>e,r=!(n>>>7==0),s=255&(r?128|n:n);if(i.push(s),!r)return}i.push(t>>>31&1)}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(E||(E={}));const R=4294967296;function I(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,r=0;function s(t,s){const o=Number(e.slice(t,s));r*=i,n=n*i+o,n>=R&&(r+=n/R|0,n%=R)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?L(n,r):_(n,r)}function D(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(R*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let r=(16777215&e)+6777216*i+6710656*n,s=i+8147497*n,o=2*n;const a=1e7;return r>=a&&(s+=Math.floor(r/a),r%=a),s>=a&&(o+=Math.floor(s/a),s%=a),o.toString()+N(s)+N(r)}function _(e,t){return{lo:0|e,hi:0|t}}function L(e,t){return t=~t,e?e=1+~e:t+=1,_(e,t)}const N=e=>{const t=String(e);return"0000000".slice(t.length)+t};function A(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 O(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const M=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"),r=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>r||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=>c(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>c(/^[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),I(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),I(e)),dec:(e,t)=>function(e,t){let i=_(e,t);const n=2147483648&i.hi;n&&(i=L(i.lo,i.hi));const r=D(i.lo,i.hi);return n?"-"+r:r}(e,t),uDec:(e,t)=>D(e,t)}}();var x;!function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(x||(x={}));class U{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw 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(f(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return m(e),A(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){v(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){f(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){m(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return m(e),A(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=M.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=M.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=M.enc(e);return P(t.lo,t.hi,this.buf),this}sint64(e){let t=M.enc(e),i=t.hi>>31;return P(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=M.uEnc(e);return P(t.lo,t.hi,this.buf),this}}class B{constructor(e,t){this.varint64=C,this.uint32=O,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){let t=this.pos;switch(e){case x.Varint:for(;128&this.buf[this.pos++];);break;case x.Bit64:this.pos+=4;case x.Bit32:this.pos+=4;break;case x.LengthDelimited:let t=this.uint32();this.pos+=t;break;case x.StartGroup:let i;for(;(i=this.tag()[1])!==x.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return M.dec(...this.varint64())}uint64(){return M.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,M.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 M.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return M.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 F(e,t){return t instanceof w||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}function J(e,t,i){if(t===i)return!0;if(e==E.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 E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return t==i}return!1}function j(e){switch(e){case E.BOOL:return!1;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return M.zero;case E.DOUBLE:case E.FLOAT:return 0;case E.BYTES:return new Uint8Array(0);case E.STRING:return"";default:return 0}}function V(e,t){const i=void 0===t;let n=x.Varint,r=0===t;switch(e){case E.STRING:r=i||!t.length,n=x.LengthDelimited;break;case E.BOOL:r=!1===t;break;case E.DOUBLE:n=x.Bit64;break;case E.FLOAT:n=x.Bit32;break;case E.INT64:case E.UINT64:r=i||0==t;break;case E.FIXED64:r=i||0==t,n=x.Bit64;break;case E.BYTES:r=i||!t.byteLength,n=x.LengthDelimited;break;case E.FIXED32:case E.SFIXED32:n=x.Bit32;break;case E.SFIXED64:r=i||0==t,n=x.Bit64;break;case E.SINT64:r=i||0==t}return[n,E[e].toLowerCase(),i||r]}E.DOUBLE,E.FLOAT,E.INT64,E.UINT64,E.INT32,E.UINT32,E.BOOL,E.STRING,E.BYTES;const q=Symbol("@bufbuild/protobuf/unknown-fields"),K={readUnknownFields:!0,readerFactory:e=>new B(e)},W={writeUnknownFields:!0,writerFactory:()=>new U};function H(e){return e?Object.assign(Object.assign({},K),e):K}function G(e){return e?Object.assign(Object.assign({},W),e):W}function z(e,t,i){return t.getType().runtime.bin.readMessage(t,e,e.uint32(),i),t}function Q(e,t,i){const n=t.uint32(),r=t.pos+n;let s,o;for(;t.pos<r;){let[n]=t.tag();switch(n){case 1:s=Y(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=Y(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=z(t,new e.V.T,i)}}}if(void 0===s){let t=j(e.K);s=e.K==E.BOOL?t.toString():t}if("string"!=typeof s&&"number"!=typeof s&&(s=s.toString()),void 0===o)switch(e.V.kind){case"scalar":o=j(e.V.T);break;case"enum":o=0;break;case"message":o=new e.V.T}return[s,o]}function Y(e,t){switch(t){case E.STRING:return e.string();case E.BOOL:return e.bool();case E.DOUBLE:return e.double();case E.FLOAT:return e.float();case E.INT32:return e.int32();case E.INT64:return e.int64();case E.UINT64:return e.uint64();case E.FIXED64:return e.fixed64();case E.BYTES:return e.bytes();case E.FIXED32:return e.fixed32();case E.SFIXED32:return e.sfixed32();case E.SFIXED64:return e.sfixed64();case E.SINT64:return e.sint64();case E.UINT32:return e.uint32();case E.SINT32:return e.sint32()}}function X(e,t,i,n,r){e.tag(i.no,x.LengthDelimited),e.fork();let s=n;switch(i.K){case E.INT32:case E.FIXED32:case E.UINT32:case E.SFIXED32:case E.SINT32:s=Number.parseInt(n);break;case E.BOOL:c("true"==n||"false"==n),s="true"==n}switch($(e,i.K,1,s,!0),i.V.kind){case"scalar":$(e,i.V.T,2,r,!0);break;case"enum":$(e,E.INT32,2,r,!0);break;case"message":Z(e,t,i.V.T,2,r)}e.join()}function Z(e,t,i,n,r){if(void 0!==r){const s=F(i,r);e.tag(n,x.LengthDelimited).bytes(s.toBinary(t))}}function $(e,t,i,n,r){let[s,o,a]=V(t,n);a&&!r||e.tag(i,s)[o](n)}function ee(e,t,i,n){if(!n.length)return;e.tag(i,x.LengthDelimited).fork();let[,r]=V(t);for(let t=0;t<n.length;t++)e[r](n[t]);e.join()}let te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ie=[];for(let e=0;e<te.length;e++)ie[te[e].charCodeAt(0)]=e;ie["-".charCodeAt(0)]=te.indexOf("+"),ie["_".charCodeAt(0)]=te.indexOf("/");const ne={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),r=0,s=0,o=0;for(let t=0;t<e.length;t++){if(i=ie[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=i,s=1;break;case 1:n[r++]=o<<2|(48&i)>>4,o=i,s=2;break;case 2:n[r++]=(15&o)<<4|(60&i)>>2,o=i,s=3;break;case 3:n[r++]=(3&o)<<6|i,s=0}}if(1==s)throw Error("invalid base64 string.");return n.subarray(0,r)},enc(e){let t,i="",n=0,r=0;for(let s=0;s<e.length;s++)switch(t=e[s],n){case 0:i+=te[t>>2],r=(3&t)<<4,n=1;break;case 1:i+=te[r|t>>4],r=(15&t)<<2,n=2;break;case 2:i+=te[r|t>>6],i+=te[63&t],n=0}return n&&(i+=te[r],i+="=",1==n&&(i+="=")),i}},re={ignoreUnknownFields:!1},se={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function oe(e){return e?Object.assign(Object.assign({},re),e):re}function ae(e){return e?Object.assign(Object.assign({},se),e):se}function ce(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 de(e,t){switch(e){case E.DOUBLE:case E.FLOAT:if(null===t)return 0;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 i=Number(t);if(Number.isNaN(i))break;if(!Number.isFinite(i))break;return e==E.FLOAT&&v(i),i;case E.INT32:case E.FIXED32:case E.SFIXED32:case E.SINT32:case E.UINT32:if(null===t)return 0;let n;if("number"==typeof t?n=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(n=Number(t)),void 0===n)break;return e==E.UINT32?f(n):m(n),n;case E.INT64:case E.SFIXED64:case E.SINT64:if(null===t)return M.zero;if("number"!=typeof t&&"string"!=typeof t)break;return M.parse(t);case E.FIXED64:case E.UINT64:if(null===t)return M.zero;if("number"!=typeof t&&"string"!=typeof t)break;return M.uParse(t);case E.BOOL:if(null===t)return!1;if("boolean"!=typeof t)break;return t;case E.STRING:if(null===t)return"";if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case E.BYTES:if(null===t||""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ne.dec(t)}throw new Error}function ue(e,t,i){if(null===t)return 0;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(n||i)return null==n?void 0:n.no}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(ce(t)))}function le(e,t,i,n){var r;if(void 0===t)return t;if(0===t&&!i)return;if(n)return t;if("google.protobuf.NullValue"==e.typeName)return null;const s=e.findNumber(t);return null!==(r=null==s?void 0:s.name)&&void 0!==r?r:t}function he(e,t,i){if(void 0!==t)switch(e){case E.INT32:case E.SFIXED32:case E.SINT32:case E.FIXED32:case E.UINT32:return c("number"==typeof t),0!=t||i?t:void 0;case E.FLOAT:case E.DOUBLE:return c("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":0!==t||i?t:void 0;case E.STRING:return c("string"==typeof t),t.length>0||i?t:void 0;case E.BOOL:return c("boolean"==typeof t),t||i?t:void 0;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return c("bigint"==typeof t||"string"==typeof t||"number"==typeof t),i||0!=t?t.toString(10):void 0;case E.BYTES:return c(t instanceof Uint8Array),i||t.byteLength>0?ne.enc(t):void 0}}function pe(e){if(void 0===e)return e;if(e instanceof w)return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function me(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class fe{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 ve(e,t){const i=ye(e);return t?i:we(Se(i))}const ge=ye;function ye(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let r=e.charAt(n);switch(r){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(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),i.push(r)}}return i.join("")}const ke=new Set(["constructor","toString","toJSON","valueOf"]),be=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Te=e=>"".concat(e,"$"),Se=e=>be.has(e)?Te(e):e,we=e=>ke.has(e)?Te(e):e;class Ee{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=ve(e,!1)}addField(e){c(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 Ce=(Pe="proto3",Re=function(e){const t=e(le,he);return{makeReadOptions:oe,makeWriteOptions:ae,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(this.debug(t)));n=null!=n?n:new e;const r={};for(const[s,o]of Object.entries(t)){const t=e.fields.findJsonName(s);if(!t){if(!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(s,'" is unknown'));continue}let a=t.localName,c=n;if(t.oneof){if(null===o&&"scalar"==t.kind)continue;const i=r[t.oneof.localName];if(i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(s,'"'));r[t.oneof.localName]=s,c=c[t.oneof.localName]={case:a},a="value"}if(t.repeated){if(null===o)continue;if(!Array.isArray(o))throw new Error("cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(o)));const n=c[a];for(const r of o){if(null===r)throw new Error("cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(r)));let s;switch(t.kind){case"message":s=t.T.fromJson(r,i);break;case"enum":if(s=ue(t.T,r,i.ignoreUnknownFields),void 0===s)continue;break;case"scalar":try{s=de(t.T,r)}catch(i){let n="cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(r));throw i instanceof Error&&i.message.length>0&&(n+=": ".concat(i.message)),new Error(n)}}n.push(s)}}else if("map"==t.kind){if(null===o)continue;if(Array.isArray(o)||"object"!=typeof o)throw new Error("cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(o)));const n=c[a];for(const[r,s]of Object.entries(o)){if(null===s)throw new Error("cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: map value null"));let a;switch(t.V.kind){case"message":a=t.V.T.fromJson(s,i);break;case"enum":if(a=ue(t.V.T,s,i.ignoreUnknownFields),void 0===a)continue;break;case"scalar":try{a=de(t.V.T,s)}catch(i){let n="cannot decode map value for field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(o));throw i instanceof Error&&i.message.length>0&&(n+=": ".concat(i.message)),new Error(n)}}try{n[de(t.K,t.K==E.BOOL?"true"==r||"false"!=r&&r:r).toString()]=a}catch(i){let n="cannot decode map key for field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(o));throw i instanceof Error&&i.message.length>0&&(n+=": ".concat(i.message)),new Error(n)}}}else switch(t.kind){case"message":const n=t.T;if(null===o&&"google.protobuf.Value"!=n.typeName){if(t.oneof)throw new Error("cannot decode field ".concat(e.typeName,".").concat(t.name,' from JSON: null is invalid for oneof field "').concat(s,'"'));continue}c[a]instanceof w?c[a].fromJson(o,i):(c[a]=n.fromJson(o,i),n.fieldWrapper&&!t.oneof&&(c[a]=n.fieldWrapper.unwrapField(c[a])));break;case"enum":const r=ue(t.T,o,i.ignoreUnknownFields);void 0!==r&&(c[a]=r);break;case"scalar":try{c[a]=de(t.T,o)}catch(i){let n="cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(o));throw i instanceof Error&&i.message.length>0&&(n+=": ".concat(i.message)),new Error(n)}}}return n},writeMessage(e,i){const n=e.getType(),r={};let s;try{for(const o of n.fields.byMember()){let n;if("oneof"==o.kind){const r=e[o.localName];if(void 0===r.value)continue;if(s=o.findField(r.case),!s)throw"oneof case not found: "+r.case;n=t(s,r.value,i)}else s=o,n=t(s,e[s.localName],i);void 0!==n&&(r[i.useProtoFieldName?s.name:s.jsonName]=n)}}catch(e){const t=s?"cannot encode field ".concat(n.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=e instanceof Error?e.message:String(e);throw new Error(t+(i.length>0?": ".concat(i):""))}return r},readScalar:de,writeScalar:he,debug:ce}}(((e,t)=>function(i,n,r){if("map"==i.kind){const s={};switch(i.V.kind){case"scalar":for(const[e,r]of Object.entries(n)){const n=t(i.V.T,r,!0);c(void 0!==n),s[e.toString()]=n}break;case"message":for(const[e,t]of Object.entries(n))s[e.toString()]=t.toJson(r);break;case"enum":const o=i.V.T;for(const[t,i]of Object.entries(n)){c(void 0===i||"number"==typeof i);const n=e(o,i,!0,r.enumAsInteger);c(void 0!==n),s[t.toString()]=n}}return r.emitDefaultValues||Object.keys(s).length>0?s:void 0}if(i.repeated){const s=[];switch(i.kind){case"scalar":for(let e=0;e<n.length;e++)s.push(t(i.T,n[e],!0));break;case"enum":for(let t=0;t<n.length;t++)s.push(e(i.T,n[t],!0,r.enumAsInteger));break;case"message":for(let e=0;e<n.length;e++)s.push(F(i.T,n[e]).toJson(r))}return r.emitDefaultValues||s.length>0?s:void 0}switch(i.kind){case"scalar":return t(i.T,n,!!i.oneof||i.opt||r.emitDefaultValues);case"enum":return e(i.T,n,!!i.oneof||i.opt||r.emitDefaultValues,r.enumAsInteger);case"message":return void 0!==n?F(i.T,n).toJson(r):void 0}})),Ie=Object.assign(Object.assign({},{makeReadOptions:H,makeWriteOptions:G,listUnknownFields(e){var t;return null!==(t=e[q])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[q]},writeUnknownFields(e,t){const i=e[q];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const r=e;Array.isArray(r[q])||(r[q]=[]),r[q].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n){const r=e.getType(),s=void 0===i?t.len:t.pos+i;for(;t.pos<s;){const[i,s]=t.tag(),o=r.fields.find(i);if(!o){const r=t.skip(s);n.readUnknownFields&&this.onUnknownField(e,i,s,r);continue}let a=e,c=o.repeated,d=o.localName;switch(o.oneof&&(a=a[o.oneof.localName],a.case!=d&&delete a.value,a.case=d,d="value"),o.kind){case"scalar":case"enum":const e="enum"==o.kind?E.INT32:o.T;if(c){let i=a[d];if(s==x.LengthDelimited&&e!=E.STRING&&e!=E.BYTES){let n=t.uint32()+t.pos;for(;t.pos<n;)i.push(Y(t,e))}else i.push(Y(t,e))}else a[d]=Y(t,e);break;case"message":const i=o.T;c?a[d].push(z(t,new i,n)):a[d]instanceof w?z(t,a[d],n):(a[d]=z(t,new i,n),!i.fieldWrapper||o.oneof||o.repeated||(a[d]=i.fieldWrapper.unwrapField(a[d])));break;case"map":let[r,u]=Q(o,t,n);a[d][r]=u}}}}),{writeMessage(e,t,i){const n=e.getType();for(const r of n.fields.byNumber()){let n,s=r.repeated,o=r.localName;if(r.oneof){const t=e[r.oneof.localName];if(t.case!==o)continue;n=t.value}else n=e[o];switch(r.kind){case"scalar":case"enum":let e="enum"==r.kind?E.INT32:r.T;if(s)if(r.packed)ee(t,e,r.no,n);else for(const i of n)$(t,e,r.no,i,!0);else void 0!==n&&$(t,e,r.no,n,!!r.oneof||r.opt);break;case"message":if(s)for(const e of n)Z(t,i,r.T,r.no,e);else Z(t,i,r.T,r.no,n);break;case"map":for(const[e,s]of Object.entries(n))X(t,i,r,e,s)}}return i.writeUnknownFields&&this.writeUnknownFields(e,t),t}}),De=Object.assign(Object.assign({},{setEnumType:k,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,r=t,s=e;if(void 0!==s[i])switch(n.kind){case"oneof":const e=s[i].case;if(void 0===e)continue;const t=n.findField(e);let o=s[i].value;!t||"message"!=t.kind||o instanceof t.T?t&&"scalar"===t.kind&&t.T===E.BYTES&&(o=me(o)):o=new t.T(o),r[i]={case:e,value:o};break;case"scalar":case"enum":let a=s[i];n.T===E.BYTES&&(a=n.repeated?a.map(me):me(a)),r[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===E.BYTES)for(const[e,t]of Object.entries(s[i]))r[i][e]=me(t);else Object.assign(r[i],s[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(s[i])){let n=s[i][t];e.fieldWrapper||(n=new e(n)),r[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)r[i]=s[i].map((e=>e instanceof c?e:new c(e)));else if(void 0!==s[i]){const e=s[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?r[i]=me(e):r[i]=e:r[i]=e instanceof c?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],r=i[e.localName];if(e.repeated){if(n.length!==r.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,r[i])));case"scalar":return n.every(((t,i)=>J(e.T,t,r[i])));case"enum":return n.every(((e,t)=>J(E.INT32,e,r[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(n,r);case"enum":return J(E.INT32,n,r);case"scalar":return J(e.T,n,r);case"oneof":if(n.case!==r.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,r.value);case"enum":return J(E.INT32,n.value,r.value);case"scalar":return J(t.T,n.value,r.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const i=Object.keys(n).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return i.every((e=>t.equals(n[e],r[e])));case"enum":return i.every((e=>J(E.INT32,n[e],r[e])));case"scalar":const s=e.V.T;return i.every((e=>J(s,n[e],r[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const i of t.fields.byMember()){const t=e[i.localName];let r;if(i.repeated)r=t.map(pe);else if("map"==i.kind){r=n[i.localName];for(const[e,i]of Object.entries(t))r[e]=pe(i)}else r="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:pe(t.value)}:{case:void 0}:pe(t);n[i.localName]=r}return i}}),{newFieldList:e=>new fe(e,je),initFields(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]=j(t.T)}}}}),{syntax:Pe,json:Re,bin:Ie,util:De,makeMessageType(e,t,i){return function(e,t,i,n){var r;const s=null!==(r=null==n?void 0:n.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),o={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(o.prototype,new w),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:T,makeEnumType:b,getEnumType:y});var Pe,Re,Ie,De,_e,Le,Ne,Ae,Oe,Me,xe,Ue,Be,Fe,Je;function je(e){var t,i,n;const r=[];let s;for(const o of"function"==typeof e?e():e){const e=o;if(e.localName=ve(o.name,void 0!==o.oneof),e.jsonName=null!==(t=o.jsonName)&&void 0!==t?t:ge(o.name),e.repeated=null!==(i=o.repeated)&&void 0!==i&&i,e.packed=null!==(n=o.packed)&&void 0!==n?n:"enum"==o.kind||"scalar"==o.kind&&o.T!=E.BYTES&&o.T!=E.STRING,void 0!==o.oneof){const t="string"==typeof o.oneof?o.oneof:o.oneof.name;s&&s.name==t||(s=new Ee(t)),e.oneof=s,s.addField(e)}r.push(e)}return r}class Ve extends w{constructor(e){super(),this.seconds=M.zero,this.nanos=0,Ce.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Ce.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=M.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 Ve.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ve({seconds:M.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new Ve).fromBinary(e,t)}static fromJson(e,t){return(new Ve).fromJson(e,t)}static fromJsonString(e,t){return(new Ve).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Ve,e,t)}}Ve.runtime=Ce,Ve.typeName="google.protobuf.Timestamp",Ve.fields=Ce.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}])),function(e){e[e.DEFAULT_AC=0]="DEFAULT_AC",e[e.OPUS=1]="OPUS",e[e.AAC=2]="AAC"}(_e||(_e={})),Ce.util.setEnumType(_e,"livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"}]),function(e){e[e.DEFAULT_VC=0]="DEFAULT_VC",e[e.H264_BASELINE=1]="H264_BASELINE",e[e.H264_MAIN=2]="H264_MAIN",e[e.H264_HIGH=3]="H264_HIGH",e[e.VP8=4]="VP8"}(Le||(Le={})),Ce.util.setEnumType(Le,"livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),function(e){e[e.IC_DEFAULT=0]="IC_DEFAULT",e[e.IC_JPEG=1]="IC_JPEG"}(Ne||(Ne={})),Ce.util.setEnumType(Ne,"livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.DATA=2]="DATA"}(Ae||(Ae={})),Ce.util.setEnumType(Ae,"livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.CAMERA=1]="CAMERA",e[e.MICROPHONE=2]="MICROPHONE",e[e.SCREEN_SHARE=3]="SCREEN_SHARE",e[e.SCREEN_SHARE_AUDIO=4]="SCREEN_SHARE_AUDIO"}(Oe||(Oe={})),Ce.util.setEnumType(Oe,"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"}]),e.VideoQuality=void 0,(Me=e.VideoQuality||(e.VideoQuality={}))[Me.LOW=0]="LOW",Me[Me.MEDIUM=1]="MEDIUM",Me[Me.HIGH=2]="HIGH",Me[Me.OFF=3]="OFF",Ce.util.setEnumType(e.VideoQuality,"livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),function(e){e[e.POOR=0]="POOR",e[e.GOOD=1]="GOOD",e[e.EXCELLENT=2]="EXCELLENT"}(xe||(xe={})),Ce.util.setEnumType(xe,"livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"}]),function(e){e[e.UNSET=0]="UNSET",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(Ue||(Ue={})),Ce.util.setEnumType(Ue,"livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),e.DisconnectReason=void 0,(Be=e.DisconnectReason||(e.DisconnectReason={}))[Be.UNKNOWN_REASON=0]="UNKNOWN_REASON",Be[Be.CLIENT_INITIATED=1]="CLIENT_INITIATED",Be[Be.DUPLICATE_IDENTITY=2]="DUPLICATE_IDENTITY",Be[Be.SERVER_SHUTDOWN=3]="SERVER_SHUTDOWN",Be[Be.PARTICIPANT_REMOVED=4]="PARTICIPANT_REMOVED",Be[Be.ROOM_DELETED=5]="ROOM_DELETED",Be[Be.STATE_MISMATCH=6]="STATE_MISMATCH",Be[Be.JOIN_FAILURE=7]="JOIN_FAILURE",Ce.util.setEnumType(e.DisconnectReason,"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"}]),function(e){e[e.RR_UNKNOWN=0]="RR_UNKNOWN",e[e.RR_SIGNAL_DISCONNECTED=1]="RR_SIGNAL_DISCONNECTED",e[e.RR_PUBLISHER_FAILED=2]="RR_PUBLISHER_FAILED",e[e.RR_SUBSCRIBER_FAILED=3]="RR_SUBSCRIBER_FAILED",e[e.RR_SWITCH_CANDIDATE=4]="RR_SWITCH_CANDIDATE"}(Fe||(Fe={})),Ce.util.setEnumType(Fe,"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"}]),function(e){e[e.SE_UNKNOWN=0]="SE_UNKNOWN",e[e.SE_CODEC_UNSUPPORTED=1]="SE_CODEC_UNSUPPORTED",e[e.SE_TRACK_NOTFOUND=2]="SE_TRACK_NOTFOUND"}(Je||(Je={})),Ce.util.setEnumType(Je,"livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]);let qe=class e extends w{constructor(e){super(),this.sid="",this.name="",this.emptyTimeout=0,this.maxParticipants=0,this.creationTime=M.zero,this.turnPassword="",this.enabledCodecs=[],this.metadata="",this.numParticipants=0,this.numPublishers=0,this.activeRecording=!1,Ce.util.initPartial(e,this)}static fromBinary(t,i){return(new e).fromBinary(t,i)}static fromJson(t,i){return(new e).fromJson(t,i)}static fromJsonString(t,i){return(new e).fromJsonString(t,i)}static equals(t,i){return Ce.util.equals(e,t,i)}};qe.runtime=Ce,qe.typeName="livekit.Room",qe.fields=Ce.util.newFieldList((()=>[{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:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Ke,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}]));class Ke extends w{constructor(e){super(),this.mime="",this.fmtpLine="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Ke).fromBinary(e,t)}static fromJson(e,t){return(new Ke).fromJson(e,t)}static fromJsonString(e,t){return(new Ke).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Ke,e,t)}}Ke.runtime=Ce,Ke.typeName="livekit.Codec",Ke.fields=Ce.util.newFieldList((()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]));class We extends w{constructor(e){super(),this.enabled=!1,this.min=0,this.max=0,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new We).fromBinary(e,t)}static fromJson(e,t){return(new We).fromJson(e,t)}static fromJsonString(e,t){return(new We).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(We,e,t)}}We.runtime=Ce,We.typeName="livekit.PlayoutDelay",We.fields=Ce.util.newFieldList((()=>[{no:1,name:"enabled",kind:"scalar",T:8},{no:2,name:"min",kind:"scalar",T:13},{no:3,name:"max",kind:"scalar",T:13}]));class He extends w{constructor(e){super(),this.canSubscribe=!1,this.canPublish=!1,this.canPublishData=!1,this.canPublishSources=[],this.hidden=!1,this.recorder=!1,this.canUpdateMetadata=!1,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new He).fromBinary(e,t)}static fromJson(e,t){return(new He).fromJson(e,t)}static fromJsonString(e,t){return(new He).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(He,e,t)}}He.runtime=Ce,He.typeName="livekit.ParticipantPermission",He.fields=Ce.util.newFieldList((()=>[{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:Ce.getEnumType(Oe),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}]));class Ge extends w{constructor(e){super(),this.sid="",this.identity="",this.state=ze.JOINING,this.tracks=[],this.metadata="",this.joinedAt=M.zero,this.name="",this.version=0,this.region="",this.isPublisher=!1,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Ge).fromBinary(e,t)}static fromJson(e,t){return(new Ge).fromJson(e,t)}static fromJsonString(e,t){return(new Ge).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Ge,e,t)}}var ze,Qe,Ye,Xe,Ze;Ge.runtime=Ce,Ge.typeName="livekit.ParticipantInfo",Ge.fields=Ce.util.newFieldList((()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Ce.getEnumType(ze)},{no:4,name:"tracks",kind:"message",T:tt,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",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:He},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8}])),function(e){e[e.JOINING=0]="JOINING",e[e.JOINED=1]="JOINED",e[e.ACTIVE=2]="ACTIVE",e[e.DISCONNECTED=3]="DISCONNECTED"}(ze||(ze={})),Ce.util.setEnumType(ze,"livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]);class $e extends w{constructor(e){super(),Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new $e).fromBinary(e,t)}static fromJson(e,t){return(new $e).fromJson(e,t)}static fromJsonString(e,t){return(new $e).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals($e,e,t)}}$e.runtime=Ce,$e.typeName="livekit.Encryption",$e.fields=Ce.util.newFieldList((()=>[])),function(e){e[e.NONE=0]="NONE",e[e.GCM=1]="GCM",e[e.CUSTOM=2]="CUSTOM"}(Qe||(Qe={})),Ce.util.setEnumType(Qe,"livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]);class et extends w{constructor(e){super(),this.mimeType="",this.mid="",this.cid="",this.layers=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new et).fromBinary(e,t)}static fromJson(e,t){return(new et).fromJson(e,t)}static fromJsonString(e,t){return(new et).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(et,e,t)}}et.runtime=Ce,et.typeName="livekit.SimulcastCodecInfo",et.fields=Ce.util.newFieldList((()=>[{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:it,repeated:!0}]));class tt extends w{constructor(e){super(),this.sid="",this.type=Ae.AUDIO,this.name="",this.muted=!1,this.width=0,this.height=0,this.simulcast=!1,this.disableDtx=!1,this.source=Oe.UNKNOWN,this.layers=[],this.mimeType="",this.mid="",this.codecs=[],this.stereo=!1,this.disableRed=!1,this.encryption=Qe.NONE,this.stream="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new tt).fromBinary(e,t)}static fromJson(e,t){return(new tt).fromJson(e,t)}static fromJsonString(e,t){return(new tt).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(tt,e,t)}}tt.runtime=Ce,tt.typeName="livekit.TrackInfo",tt.fields=Ce.util.newFieldList((()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Ce.getEnumType(Ae)},{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:Ce.getEnumType(Oe)},{no:10,name:"layers",kind:"message",T:it,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:et,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:Ce.getEnumType(Qe)},{no:17,name:"stream",kind:"scalar",T:9}]));class it extends w{constructor(t){super(),this.quality=e.VideoQuality.LOW,this.width=0,this.height=0,this.bitrate=0,this.ssrc=0,Ce.util.initPartial(t,this)}static fromBinary(e,t){return(new it).fromBinary(e,t)}static fromJson(e,t){return(new it).fromJson(e,t)}static fromJsonString(e,t){return(new it).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(it,e,t)}}it.runtime=Ce,it.typeName="livekit.VideoLayer",it.fields=Ce.util.newFieldList((()=>[{no:1,name:"quality",kind:"enum",T:Ce.getEnumType(e.VideoQuality)},{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}]));class nt extends w{constructor(t){super(),this.kind=e.DataPacket_Kind.RELIABLE,this.value={case:void 0},Ce.util.initPartial(t,this)}static fromBinary(e,t){return(new nt).fromBinary(e,t)}static fromJson(e,t){return(new nt).fromJson(e,t)}static fromJsonString(e,t){return(new nt).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(nt,e,t)}}nt.runtime=Ce,nt.typeName="livekit.DataPacket",nt.fields=Ce.util.newFieldList((()=>[{no:1,name:"kind",kind:"enum",T:Ce.getEnumType(e.DataPacket_Kind)},{no:2,name:"user",kind:"message",T:ot,oneof:"value"},{no:3,name:"speaker",kind:"message",T:rt,oneof:"value"}])),e.DataPacket_Kind=void 0,(Ye=e.DataPacket_Kind||(e.DataPacket_Kind={}))[Ye.RELIABLE=0]="RELIABLE",Ye[Ye.LOSSY=1]="LOSSY",Ce.util.setEnumType(e.DataPacket_Kind,"livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]);class rt extends w{constructor(e){super(),this.speakers=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new rt).fromBinary(e,t)}static fromJson(e,t){return(new rt).fromJson(e,t)}static fromJsonString(e,t){return(new rt).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(rt,e,t)}}rt.runtime=Ce,rt.typeName="livekit.ActiveSpeakerUpdate",rt.fields=Ce.util.newFieldList((()=>[{no:1,name:"speakers",kind:"message",T:st,repeated:!0}]));class st extends w{constructor(e){super(),this.sid="",this.level=0,this.active=!1,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new st).fromBinary(e,t)}static fromJson(e,t){return(new st).fromJson(e,t)}static fromJsonString(e,t){return(new st).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(st,e,t)}}st.runtime=Ce,st.typeName="livekit.SpeakerInfo",st.fields=Ce.util.newFieldList((()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]));class ot extends w{constructor(e){super(),this.participantSid="",this.participantIdentity="",this.payload=new Uint8Array(0),this.destinationSids=[],this.destinationIdentities=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new ot).fromBinary(e,t)}static fromJson(e,t){return(new ot).fromJson(e,t)}static fromJsonString(e,t){return(new ot).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(ot,e,t)}}ot.runtime=Ce,ot.typeName="livekit.UserPacket",ot.fields=Ce.util.newFieldList((()=>[{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}]));class at extends w{constructor(e){super(),this.participantSid="",this.trackSids=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new at).fromBinary(e,t)}static fromJson(e,t){return(new at).fromJson(e,t)}static fromJsonString(e,t){return(new at).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(at,e,t)}}at.runtime=Ce,at.typeName="livekit.ParticipantTracks",at.fields=Ce.util.newFieldList((()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]));class ct extends w{constructor(e){super(),this.edition=Xe.Standard,this.version="",this.protocol=0,this.region="",this.nodeId="",this.debugInfo="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new ct).fromBinary(e,t)}static fromJson(e,t){return(new ct).fromJson(e,t)}static fromJsonString(e,t){return(new ct).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(ct,e,t)}}ct.runtime=Ce,ct.typeName="livekit.ServerInfo",ct.fields=Ce.util.newFieldList((()=>[{no:1,name:"edition",kind:"enum",T:Ce.getEnumType(Xe)},{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}])),function(e){e[e.Standard=0]="Standard",e[e.Cloud=1]="Cloud"}(Xe||(Xe={})),Ce.util.setEnumType(Xe,"livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]);class dt extends w{constructor(e){super(),this.sdk=Ze.UNKNOWN,this.version="",this.protocol=0,this.os="",this.osVersion="",this.deviceModel="",this.browser="",this.browserVersion="",this.address="",this.network="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new dt).fromBinary(e,t)}static fromJson(e,t){return(new dt).fromJson(e,t)}static fromJsonString(e,t){return(new dt).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(dt,e,t)}}dt.runtime=Ce,dt.typeName="livekit.ClientInfo",dt.fields=Ce.util.newFieldList((()=>[{no:1,name:"sdk",kind:"enum",T:Ce.getEnumType(Ze)},{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}])),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.JS=1]="JS",e[e.SWIFT=2]="SWIFT",e[e.ANDROID=3]="ANDROID",e[e.FLUTTER=4]="FLUTTER",e[e.GO=5]="GO",e[e.UNITY=6]="UNITY",e[e.REACT_NATIVE=7]="REACT_NATIVE",e[e.RUST=8]="RUST",e[e.PYTHON=9]="PYTHON",e[e.CPP=10]="CPP"}(Ze||(Ze={})),Ce.util.setEnumType(Ze,"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"}]);class ut extends w{constructor(e){super(),this.resumeConnection=Ue.UNSET,this.forceRelay=Ue.UNSET,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new ut).fromBinary(e,t)}static fromJson(e,t){return(new ut).fromJson(e,t)}static fromJsonString(e,t){return(new ut).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(ut,e,t)}}ut.runtime=Ce,ut.typeName="livekit.ClientConfiguration",ut.fields=Ce.util.newFieldList((()=>[{no:1,name:"video",kind:"message",T:lt},{no:2,name:"screen",kind:"message",T:lt},{no:3,name:"resume_connection",kind:"enum",T:Ce.getEnumType(Ue)},{no:4,name:"disabled_codecs",kind:"message",T:ht},{no:5,name:"force_relay",kind:"enum",T:Ce.getEnumType(Ue)}]));class lt extends w{constructor(e){super(),this.hardwareEncoder=Ue.UNSET,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new lt).fromBinary(e,t)}static fromJson(e,t){return(new lt).fromJson(e,t)}static fromJsonString(e,t){return(new lt).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(lt,e,t)}}lt.runtime=Ce,lt.typeName="livekit.VideoConfiguration",lt.fields=Ce.util.newFieldList((()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Ce.getEnumType(Ue)}]));class ht extends w{constructor(e){super(),this.codecs=[],this.publish=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new ht).fromBinary(e,t)}static fromJson(e,t){return(new ht).fromJson(e,t)}static fromJsonString(e,t){return(new ht).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(ht,e,t)}}ht.runtime=Ce,ht.typeName="livekit.DisabledCodecs",ht.fields=Ce.util.newFieldList((()=>[{no:1,name:"codecs",kind:"message",T:Ke,repeated:!0},{no:2,name:"publish",kind:"message",T:Ke,repeated:!0}]));class pt extends w{constructor(e){super(),this.duration=0,this.startTimestamp=M.zero,this.endTimestamp=M.zero,this.rtpClockTicks=M.zero,this.driftSamples=M.zero,this.driftMs=0,this.clockRate=0,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new pt).fromBinary(e,t)}static fromJson(e,t){return(new pt).fromJson(e,t)}static fromJsonString(e,t){return(new pt).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(pt,e,t)}}pt.runtime=Ce,pt.typeName="livekit.RTPDrift",pt.fields=Ce.util.newFieldList((()=>[{no:1,name:"start_time",kind:"message",T:Ve},{no:2,name:"end_time",kind:"message",T:Ve},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"start_timestamp",kind:"scalar",T:4},{no:5,name:"end_timestamp",kind:"scalar",T:4},{no:6,name:"rtp_clock_ticks",kind:"scalar",T:4},{no:7,name:"drift_samples",kind:"scalar",T:3},{no:8,name:"drift_ms",kind:"scalar",T:1},{no:9,name:"clock_rate",kind:"scalar",T:1}]));class mt extends w{constructor(e){super(),this.duration=0,this.packets=0,this.packetRate=0,this.bytes=M.zero,this.headerBytes=M.zero,this.bitrate=0,this.packetsLost=0,this.packetLossRate=0,this.packetLossPercentage=0,this.packetsDuplicate=0,this.packetDuplicateRate=0,this.bytesDuplicate=M.zero,this.headerBytesDuplicate=M.zero,this.bitrateDuplicate=0,this.packetsPadding=0,this.packetPaddingRate=0,this.bytesPadding=M.zero,this.headerBytesPadding=M.zero,this.bitratePadding=0,this.packetsOutOfOrder=0,this.frames=0,this.frameRate=0,this.jitterCurrent=0,this.jitterMax=0,this.gapHistogram={},this.nacks=0,this.nackAcks=0,this.nackMisses=0,this.nackRepeated=0,this.plis=0,this.firs=0,this.rttCurrent=0,this.rttMax=0,this.keyFrames=0,this.layerLockPlis=0,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new mt).fromBinary(e,t)}static fromJson(e,t){return(new mt).fromJson(e,t)}static fromJsonString(e,t){return(new mt).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(mt,e,t)}}mt.runtime=Ce,mt.typeName="livekit.RTPStats",mt.fields=Ce.util.newFieldList((()=>[{no:1,name:"start_time",kind:"message",T:Ve},{no:2,name:"end_time",kind:"message",T:Ve},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"packets",kind:"scalar",T:13},{no:5,name:"packet_rate",kind:"scalar",T:1},{no:6,name:"bytes",kind:"scalar",T:4},{no:39,name:"header_bytes",kind:"scalar",T:4},{no:7,name:"bitrate",kind:"scalar",T:1},{no:8,name:"packets_lost",kind:"scalar",T:13},{no:9,name:"packet_loss_rate",kind:"scalar",T:1},{no:10,name:"packet_loss_percentage",kind:"scalar",T:2},{no:11,name:"packets_duplicate",kind:"scalar",T:13},{no:12,name:"packet_duplicate_rate",kind:"scalar",T:1},{no:13,name:"bytes_duplicate",kind:"scalar",T:4},{no:40,name:"header_bytes_duplicate",kind:"scalar",T:4},{no:14,name:"bitrate_duplicate",kind:"scalar",T:1},{no:15,name:"packets_padding",kind:"scalar",T:13},{no:16,name:"packet_padding_rate",kind:"scalar",T:1},{no:17,name:"bytes_padding",kind:"scalar",T:4},{no:41,name:"header_bytes_padding",kind:"scalar",T:4},{no:18,name:"bitrate_padding",kind:"scalar",T:1},{no:19,name:"packets_out_of_order",kind:"scalar",T:13},{no:20,name:"frames",kind:"scalar",T:13},{no:21,name:"frame_rate",kind:"scalar",T:1},{no:22,name:"jitter_current",kind:"scalar",T:1},{no:23,name:"jitter_max",kind:"scalar",T:1},{no:24,name:"gap_histogram",kind:"map",K:5,V:{kind:"scalar",T:13}},{no:25,name:"nacks",kind:"scalar",T:13},{no:37,name:"nack_acks",kind:"scalar",T:13},{no:26,name:"nack_misses",kind:"scalar",T:13},{no:38,name:"nack_repeated",kind:"scalar",T:13},{no:27,name:"plis",kind:"scalar",T:13},{no:28,name:"last_pli",kind:"message",T:Ve},{no:29,name:"firs",kind:"scalar",T:13},{no:30,name:"last_fir",kind:"message",T:Ve},{no:31,name:"rtt_current",kind:"scalar",T:13},{no:32,name:"rtt_max",kind:"scalar",T:13},{no:33,name:"key_frames",kind:"scalar",T:13},{no:34,name:"last_key_frame",kind:"message",T:Ve},{no:35,name:"layer_lock_plis",kind:"scalar",T:13},{no:36,name:"last_layer_lock_pli",kind:"message",T:Ve},{no:44,name:"packet_drift",kind:"message",T:pt},{no:45,name:"report_drift",kind:"message",T:pt}]));class ft extends w{constructor(e){super(),this.unixMicro=M.zero,this.ticks=0,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new ft).fromBinary(e,t)}static fromJson(e,t){return(new ft).fromJson(e,t)}static fromJsonString(e,t){return(new ft).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(ft,e,t)}}ft.runtime=Ce,ft.typeName="livekit.TimedVersion",ft.fields=Ce.util.newFieldList((()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]));const vt=7e3,gt=[0,300,1200,2700,4800,vt,vt,vt,vt,vt];class yt{constructor(e){this._retryDelays=void 0!==e?[...e]:gt}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()}}function kt(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function bt(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.")}function Tt(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=bt(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,r){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,r,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var St,wt={exports:{}},Et="object"==typeof Reflect?Reflect:null,Ct=Et&&"function"==typeof Et.apply?Et.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};St=Et&&"function"==typeof Et.ownKeys?Et.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Pt=Number.isNaN||function(e){return e!=e};function Rt(){Rt.init.call(this)}wt.exports=Rt,wt.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,s),n(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}Ut(e,t,s,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&Ut(e,"error",t,i)}(e,r,{once:!0})}))},Rt.EventEmitter=Rt,Rt.prototype._events=void 0,Rt.prototype._eventsCount=0,Rt.prototype._maxListeners=void 0;var It=10;function Dt(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function _t(e){return void 0===e._maxListeners?Rt.defaultMaxListeners:e._maxListeners}function Lt(e,t,i,n){var r,s,o,a;if(Dt(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),o=s[t]),void 0===o)o=s[t]=i,++e._eventsCount;else if("function"==typeof o?o=s[t]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),(r=_t(e))>0&&o.length>r&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function Nt(){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 At(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=Nt.bind(n);return r.listener=i,n.wrapFn=r,r}function Ot(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]: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}(r):xt(r,r.length)}function Mt(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 xt(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function Ut(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 r(s){n.once&&e.removeEventListener(t,r),i(s)}))}}Object.defineProperty(Rt,"defaultMaxListeners",{enumerable:!0,get:function(){return It},set:function(e){if("number"!=typeof e||e<0||Pt(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");It=e}}),Rt.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},Rt.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Pt(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},Rt.prototype.getMaxListeners=function(){return _t(this)},Rt.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,r=this._events;if(void 0!==r)n=n&&void 0===r.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=r[e];if(void 0===a)return!1;if("function"==typeof a)Ct(a,this,t);else{var c=a.length,d=xt(a,c);for(i=0;i<c;++i)Ct(d[i],this,t)}return!0},Rt.prototype.addListener=function(e,t){return Lt(this,e,t,!1)},Rt.prototype.on=Rt.prototype.addListener,Rt.prototype.prependListener=function(e,t){return Lt(this,e,t,!0)},Rt.prototype.once=function(e,t){return Dt(t),this.on(e,At(this,e,t)),this},Rt.prototype.prependOnceListener=function(e,t){return Dt(t),this.prependListener(e,At(this,e,t)),this},Rt.prototype.removeListener=function(e,t){var i,n,r,s,o;if(Dt(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(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){o=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},Rt.prototype.off=Rt.prototype.removeListener,Rt.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 r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);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},Rt.prototype.listeners=function(e){return Ot(this,e,!0)},Rt.prototype.rawListeners=function(e){return Ot(this,e,!1)},Rt.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Mt.call(e,t)},Rt.prototype.listenerCount=Mt,Rt.prototype.eventNames=function(){return this._eventsCount>0?St(this._events):[]};var Bt=wt.exports;let Ft=!0,Jt=!0;function jt(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function Vt(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=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,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.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,s.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 qt(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Ft=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Kt(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Jt=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Wt(){if("object"==typeof window){if(Ft)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ht(e,t){Jt&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Gt(e){return"[object Object]"===Object.prototype.toString.call(e)}function zt(e){return Gt(e)?Object.keys(e).reduce((function(t,i){const n=Gt(e[i]),r=n?zt(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function Qt(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Qt(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Qt(e,e.get(t),i)}))})))}function Yt(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&Qt(e,i,r)}))})),r}const Xt=Wt;function Zt(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 r=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[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(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 s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),Xt("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return Xt("chrome: "+JSON.stringify(e)),r(e)},s=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){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(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(s(e))))))}}}function $t(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function ei(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 r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),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 r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Vt(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function ti(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 r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};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 ii(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(s(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(r(t)))},i])})).then(i,n)}}function ni(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=>Yt(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}),Vt(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Yt(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 ri(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 r=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]})),r.apply(this,arguments)}}function si(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ri(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 r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.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||{},r.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 r=this._streams[i.id];if(r)r.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=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=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],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(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 oi(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 ai(e,t){Vt(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var ci=Object.freeze({__proto__:null,fixNegotiationNeeded:ai,shimAddTrackRemoveTrack:si,shimAddTrackRemoveTrackWithNative:ri,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:ti,shimGetStats:ii,shimGetUserMedia:Zt,shimMediaStream:$t,shimOnTrack:ei,shimPeerConnection:oi,shimSenderReceiverGetStats:ni});function di(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Ht("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 ui(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 li(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,r,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,s)}}function hi(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 pi(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}),Vt(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function mi(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ht("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function fi(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function vi(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){if(!/^[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 gi(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 yi(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 ki(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 bi=Object.freeze({__proto__:null,shimAddTransceiver:vi,shimCreateAnswer:ki,shimCreateOffer:yi,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:gi,shimGetUserMedia:di,shimOnTrack:ui,shimPeerConnection:li,shimRTCDataChannel:fi,shimReceiverGetStats:pi,shimRemoveStream:mi,shimSenderGetStats:hi});function Ti(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),r=1;r<i;r++)n[r-1]=arguments[r];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 Si(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 wi(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Ei(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(Ci(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Ci(e){return e&&void 0!==e.video?Object.assign({},e,{video:zt(e.video)}):e}function Pi(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?(Ht("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 Ri(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 Ii(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 Di(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var _i=Object.freeze({__proto__:null,shimAudioContext:Di,shimCallbacksAPI:wi,shimConstraints:Ci,shimCreateOfferLegacy:Ii,shimGetUserMedia:Ei,shimLocalStreamsAPI:Ti,shimRTCIceServerUrls:Pi,shimRemoteStreamsAPI:Si,shimTrackEventTransceiver:Ri}),Li={exports:{}};!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 e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},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 e=0;e<n.length;e++)i=n[e].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],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.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],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),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 r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.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 r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[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]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substring(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=u}))),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 r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.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 r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[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 r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},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 r;const s=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" 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 e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?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 e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(Li);var Ni=Li.exports,Ai=n(Ni),Oi=t({__proto__:null,default:Ai},[Ni]);function Mi(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=Ai.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,Vt(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function xi(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Vt(e,"icecandidate",(e=>{if(e.candidate){const t=Ai.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function Ui(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=Ai.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Ai.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 r=Ai.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return i.apply(this,arguments)}}function Bi(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],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>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},Vt(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Fi(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 Ji(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 ji(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 Vi(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"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var qi,Ki,Wi,Hi,Gi=Object.freeze({__proto__:null,removeExtmapAllowMixed:Ji,shimAddIceCandidateNullOrEmpty:ji,shimConnectionState:Fi,shimMaxMessageSize:Ui,shimParameterlessSetLocalDescription:Vi,shimRTCIceCandidate:Mi,shimRTCIceCandidateRelayProtocol:xi,shimSendThrowTypeError:Bi});!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=Wt,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.mozGetUserMedia)t.browser="firefox",t.version=jt(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=jt(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=jt(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:Gi,extractVersion:jt,disableLog:qt,disableWarnings:Kt,sdp:Oi};switch(n.browser){case"chrome":if(!ci||!oi||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=ci,ji(e,n),Vi(e),Zt(e,n),$t(e),oi(e,n),ei(e),si(e,n),ti(e),ii(e),ni(e),ai(e,n),Mi(e),xi(e),Fi(e),Ui(e,n),Bi(e),Ji(e,n);break;case"firefox":if(!bi||!li||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=bi,ji(e,n),Vi(e),di(e,n),li(e,n),ui(e),mi(e),hi(e),pi(e),fi(e),vi(e),gi(e),yi(e),ki(e),Mi(e),Fi(e),Ui(e,n),Bi(e);break;case"safari":if(!_i||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=_i,ji(e,n),Vi(e),Pi(e),Ii(e),wi(e),Ti(e),Si(e),Ri(e),Ei(e),Di(e),Mi(e),xi(e),Ui(e,n),Bi(e),Ji(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window}),function(e){e[e.PUBLISHER=0]="PUBLISHER",e[e.SUBSCRIBER=1]="SUBSCRIBER"}(qi||(qi={})),Ce.util.setEnumType(qi,"livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PAUSED=1]="PAUSED"}(Ki||(Ki={})),Ce.util.setEnumType(Ki,"livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.TLS=2]="TLS"}(Wi||(Wi={})),Ce.util.setEnumType(Wi,"livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]);class zi extends w{constructor(e){super(),this.message={case:void 0},Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new zi).fromBinary(e,t)}static fromJson(e,t){return(new zi).fromJson(e,t)}static fromJsonString(e,t){return(new zi).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(zi,e,t)}}zi.runtime=Ce,zi.typeName="livekit.SignalRequest",zi.fields=Ce.util.newFieldList((()=>[{no:1,name:"offer",kind:"message",T:sn,oneof:"message"},{no:2,name:"answer",kind:"message",T:sn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Zi,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Xi,oneof:"message"},{no:5,name:"mute",kind:"message",T:$i,oneof:"message"},{no:6,name:"subscription",kind:"message",T:an,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:cn,oneof:"message"},{no:8,name:"leave",kind:"message",T:dn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:un,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:wn,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Cn,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Rn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:ln,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:In,oneof:"message"}]));class Qi extends w{constructor(e){super(),this.message={case:void 0},Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Qi).fromBinary(e,t)}static fromJson(e,t){return(new Qi).fromJson(e,t)}static fromJsonString(e,t){return(new Qi).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Qi,e,t)}}Qi.runtime=Ce,Qi.typeName="livekit.SignalResponse",Qi.fields=Ce.util.newFieldList((()=>[{no:1,name:"join",kind:"message",T:en,oneof:"message"},{no:2,name:"answer",kind:"message",T:sn,oneof:"message"},{no:3,name:"offer",kind:"message",T:sn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Zi,oneof:"message"},{no:5,name:"update",kind:"message",T:on,oneof:"message"},{no:6,name:"track_published",kind:"message",T:nn,oneof:"message"},{no:8,name:"leave",kind:"message",T:dn,oneof:"message"},{no:9,name:"mute",kind:"message",T:$i,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:pn,oneof:"message"},{no:11,name:"room_update",kind:"message",T:mn,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:vn,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:yn,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Tn,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:En,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:rn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:tn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Dn,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Nn,oneof:"message"}]));class Yi extends w{constructor(e){super(),this.codec="",this.cid="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Yi).fromBinary(e,t)}static fromJson(e,t){return(new Yi).fromJson(e,t)}static fromJsonString(e,t){return(new Yi).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Yi,e,t)}}Yi.runtime=Ce,Yi.typeName="livekit.SimulcastCodec",Yi.fields=Ce.util.newFieldList((()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]));class Xi extends w{constructor(e){super(),this.cid="",this.name="",this.type=Ae.AUDIO,this.width=0,this.height=0,this.muted=!1,this.disableDtx=!1,this.source=Oe.UNKNOWN,this.layers=[],this.simulcastCodecs=[],this.sid="",this.stereo=!1,this.disableRed=!1,this.encryption=Qe.NONE,this.stream="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Xi).fromBinary(e,t)}static fromJson(e,t){return(new Xi).fromJson(e,t)}static fromJsonString(e,t){return(new Xi).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Xi,e,t)}}Xi.runtime=Ce,Xi.typeName="livekit.AddTrackRequest",Xi.fields=Ce.util.newFieldList((()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:Ce.getEnumType(Ae)},{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:Ce.getEnumType(Oe)},{no:9,name:"layers",kind:"message",T:it,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Yi,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:Ce.getEnumType(Qe)},{no:15,name:"stream",kind:"scalar",T:9}]));class Zi extends w{constructor(e){super(),this.candidateInit="",this.target=qi.PUBLISHER,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Zi).fromBinary(e,t)}static fromJson(e,t){return(new Zi).fromJson(e,t)}static fromJsonString(e,t){return(new Zi).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Zi,e,t)}}Zi.runtime=Ce,Zi.typeName="livekit.TrickleRequest",Zi.fields=Ce.util.newFieldList((()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Ce.getEnumType(qi)}]));class $i extends w{constructor(e){super(),this.sid="",this.muted=!1,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new $i).fromBinary(e,t)}static fromJson(e,t){return(new $i).fromJson(e,t)}static fromJsonString(e,t){return(new $i).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals($i,e,t)}}$i.runtime=Ce,$i.typeName="livekit.MuteTrackRequest",$i.fields=Ce.util.newFieldList((()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]));class en extends w{constructor(e){super(),this.otherParticipants=[],this.serverVersion="",this.iceServers=[],this.subscriberPrimary=!1,this.alternativeUrl="",this.serverRegion="",this.pingTimeout=0,this.pingInterval=0,this.sifTrailer=new Uint8Array(0),Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new en).fromBinary(e,t)}static fromJson(e,t){return(new en).fromJson(e,t)}static fromJsonString(e,t){return(new en).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(en,e,t)}}en.runtime=Ce,en.typeName="livekit.JoinResponse",en.fields=Ce.util.newFieldList((()=>[{no:1,name:"room",kind:"message",T:qe},{no:2,name:"participant",kind:"message",T:Ge},{no:3,name:"other_participants",kind:"message",T:Ge,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:hn,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:ut},{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:ct},{no:13,name:"sif_trailer",kind:"scalar",T:12}]));class tn extends w{constructor(e){super(),this.iceServers=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new tn).fromBinary(e,t)}static fromJson(e,t){return(new tn).fromJson(e,t)}static fromJsonString(e,t){return(new tn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(tn,e,t)}}tn.runtime=Ce,tn.typeName="livekit.ReconnectResponse",tn.fields=Ce.util.newFieldList((()=>[{no:1,name:"ice_servers",kind:"message",T:hn,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ut}]));class nn extends w{constructor(e){super(),this.cid="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new nn).fromBinary(e,t)}static fromJson(e,t){return(new nn).fromJson(e,t)}static fromJsonString(e,t){return(new nn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(nn,e,t)}}nn.runtime=Ce,nn.typeName="livekit.TrackPublishedResponse",nn.fields=Ce.util.newFieldList((()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:tt}]));class rn extends w{constructor(e){super(),this.trackSid="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new rn).fromBinary(e,t)}static fromJson(e,t){return(new rn).fromJson(e,t)}static fromJsonString(e,t){return(new rn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(rn,e,t)}}rn.runtime=Ce,rn.typeName="livekit.TrackUnpublishedResponse",rn.fields=Ce.util.newFieldList((()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));class sn extends w{constructor(e){super(),this.type="",this.sdp="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new sn).fromBinary(e,t)}static fromJson(e,t){return(new sn).fromJson(e,t)}static fromJsonString(e,t){return(new sn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(sn,e,t)}}sn.runtime=Ce,sn.typeName="livekit.SessionDescription",sn.fields=Ce.util.newFieldList((()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]));class on extends w{constructor(e){super(),this.participants=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new on).fromBinary(e,t)}static fromJson(e,t){return(new on).fromJson(e,t)}static fromJsonString(e,t){return(new on).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(on,e,t)}}on.runtime=Ce,on.typeName="livekit.ParticipantUpdate",on.fields=Ce.util.newFieldList((()=>[{no:1,name:"participants",kind:"message",T:Ge,repeated:!0}]));class an extends w{constructor(e){super(),this.trackSids=[],this.subscribe=!1,this.participantTracks=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new an).fromBinary(e,t)}static fromJson(e,t){return(new an).fromJson(e,t)}static fromJsonString(e,t){return(new an).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(an,e,t)}}an.runtime=Ce,an.typeName="livekit.UpdateSubscription",an.fields=Ce.util.newFieldList((()=>[{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:at,repeated:!0}]));class cn extends w{constructor(t){super(),this.trackSids=[],this.disabled=!1,this.quality=e.VideoQuality.LOW,this.width=0,this.height=0,this.fps=0,this.priority=0,Ce.util.initPartial(t,this)}static fromBinary(e,t){return(new cn).fromBinary(e,t)}static fromJson(e,t){return(new cn).fromJson(e,t)}static fromJsonString(e,t){return(new cn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(cn,e,t)}}cn.runtime=Ce,cn.typeName="livekit.UpdateTrackSettings",cn.fields=Ce.util.newFieldList((()=>[{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:Ce.getEnumType(e.VideoQuality)},{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}]));class dn extends w{constructor(t){super(),this.canReconnect=!1,this.reason=e.DisconnectReason.UNKNOWN_REASON,Ce.util.initPartial(t,this)}static fromBinary(e,t){return(new dn).fromBinary(e,t)}static fromJson(e,t){return(new dn).fromJson(e,t)}static fromJsonString(e,t){return(new dn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(dn,e,t)}}dn.runtime=Ce,dn.typeName="livekit.LeaveRequest",dn.fields=Ce.util.newFieldList((()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Ce.getEnumType(e.DisconnectReason)}]));class un extends w{constructor(e){super(),this.trackSid="",this.layers=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new un).fromBinary(e,t)}static fromJson(e,t){return(new un).fromJson(e,t)}static fromJsonString(e,t){return(new un).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(un,e,t)}}un.runtime=Ce,un.typeName="livekit.UpdateVideoLayers",un.fields=Ce.util.newFieldList((()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:it,repeated:!0}]));class ln extends w{constructor(e){super(),this.metadata="",this.name="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new ln).fromBinary(e,t)}static fromJson(e,t){return(new ln).fromJson(e,t)}static fromJsonString(e,t){return(new ln).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(ln,e,t)}}ln.runtime=Ce,ln.typeName="livekit.UpdateParticipantMetadata",ln.fields=Ce.util.newFieldList((()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}]));class hn extends w{constructor(e){super(),this.urls=[],this.username="",this.credential="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new hn).fromBinary(e,t)}static fromJson(e,t){return(new hn).fromJson(e,t)}static fromJsonString(e,t){return(new hn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(hn,e,t)}}hn.runtime=Ce,hn.typeName="livekit.ICEServer",hn.fields=Ce.util.newFieldList((()=>[{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}]));class pn extends w{constructor(e){super(),this.speakers=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new pn).fromBinary(e,t)}static fromJson(e,t){return(new pn).fromJson(e,t)}static fromJsonString(e,t){return(new pn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(pn,e,t)}}pn.runtime=Ce,pn.typeName="livekit.SpeakersChanged",pn.fields=Ce.util.newFieldList((()=>[{no:1,name:"speakers",kind:"message",T:st,repeated:!0}]));class mn extends w{constructor(e){super(),Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new mn).fromBinary(e,t)}static fromJson(e,t){return(new mn).fromJson(e,t)}static fromJsonString(e,t){return(new mn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(mn,e,t)}}mn.runtime=Ce,mn.typeName="livekit.RoomUpdate",mn.fields=Ce.util.newFieldList((()=>[{no:1,name:"room",kind:"message",T:qe}]));class fn extends w{constructor(e){super(),this.participantSid="",this.quality=xe.POOR,this.score=0,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new fn).fromBinary(e,t)}static fromJson(e,t){return(new fn).fromJson(e,t)}static fromJsonString(e,t){return(new fn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(fn,e,t)}}fn.runtime=Ce,fn.typeName="livekit.ConnectionQualityInfo",fn.fields=Ce.util.newFieldList((()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Ce.getEnumType(xe)},{no:3,name:"score",kind:"scalar",T:2}]));class vn extends w{constructor(e){super(),this.updates=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new vn).fromBinary(e,t)}static fromJson(e,t){return(new vn).fromJson(e,t)}static fromJsonString(e,t){return(new vn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(vn,e,t)}}vn.runtime=Ce,vn.typeName="livekit.ConnectionQualityUpdate",vn.fields=Ce.util.newFieldList((()=>[{no:1,name:"updates",kind:"message",T:fn,repeated:!0}]));class gn extends w{constructor(e){super(),this.participantSid="",this.trackSid="",this.state=Ki.ACTIVE,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new gn).fromBinary(e,t)}static fromJson(e,t){return(new gn).fromJson(e,t)}static fromJsonString(e,t){return(new gn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(gn,e,t)}}gn.runtime=Ce,gn.typeName="livekit.StreamStateInfo",gn.fields=Ce.util.newFieldList((()=>[{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:Ce.getEnumType(Ki)}]));class yn extends w{constructor(e){super(),this.streamStates=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new yn).fromBinary(e,t)}static fromJson(e,t){return(new yn).fromJson(e,t)}static fromJsonString(e,t){return(new yn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(yn,e,t)}}yn.runtime=Ce,yn.typeName="livekit.StreamStateUpdate",yn.fields=Ce.util.newFieldList((()=>[{no:1,name:"stream_states",kind:"message",T:gn,repeated:!0}]));class kn extends w{constructor(t){super(),this.quality=e.VideoQuality.LOW,this.enabled=!1,Ce.util.initPartial(t,this)}static fromBinary(e,t){return(new kn).fromBinary(e,t)}static fromJson(e,t){return(new kn).fromJson(e,t)}static fromJsonString(e,t){return(new kn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(kn,e,t)}}kn.runtime=Ce,kn.typeName="livekit.SubscribedQuality",kn.fields=Ce.util.newFieldList((()=>[{no:1,name:"quality",kind:"enum",T:Ce.getEnumType(e.VideoQuality)},{no:2,name:"enabled",kind:"scalar",T:8}]));class bn extends w{constructor(e){super(),this.codec="",this.qualities=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new bn).fromBinary(e,t)}static fromJson(e,t){return(new bn).fromJson(e,t)}static fromJsonString(e,t){return(new bn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(bn,e,t)}}bn.runtime=Ce,bn.typeName="livekit.SubscribedCodec",bn.fields=Ce.util.newFieldList((()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:kn,repeated:!0}]));class Tn extends w{constructor(e){super(),this.trackSid="",this.subscribedQualities=[],this.subscribedCodecs=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Tn).fromBinary(e,t)}static fromJson(e,t){return(new Tn).fromJson(e,t)}static fromJsonString(e,t){return(new Tn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Tn,e,t)}}Tn.runtime=Ce,Tn.typeName="livekit.SubscribedQualityUpdate",Tn.fields=Ce.util.newFieldList((()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:kn,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:bn,repeated:!0}]));class Sn extends w{constructor(e){super(),this.participantSid="",this.allTracks=!1,this.trackSids=[],this.participantIdentity="",Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Sn).fromBinary(e,t)}static fromJson(e,t){return(new Sn).fromJson(e,t)}static fromJsonString(e,t){return(new Sn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Sn,e,t)}}Sn.runtime=Ce,Sn.typeName="livekit.TrackPermission",Sn.fields=Ce.util.newFieldList((()=>[{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}]));class wn extends w{constructor(e){super(),this.allParticipants=!1,this.trackPermissions=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new wn).fromBinary(e,t)}static fromJson(e,t){return(new wn).fromJson(e,t)}static fromJsonString(e,t){return(new wn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(wn,e,t)}}wn.runtime=Ce,wn.typeName="livekit.SubscriptionPermission",wn.fields=Ce.util.newFieldList((()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Sn,repeated:!0}]));class En extends w{constructor(e){super(),this.participantSid="",this.trackSid="",this.allowed=!1,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new En).fromBinary(e,t)}static fromJson(e,t){return(new En).fromJson(e,t)}static fromJsonString(e,t){return(new En).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(En,e,t)}}En.runtime=Ce,En.typeName="livekit.SubscriptionPermissionUpdate",En.fields=Ce.util.newFieldList((()=>[{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}]));class Cn extends w{constructor(e){super(),this.publishTracks=[],this.dataChannels=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Cn).fromBinary(e,t)}static fromJson(e,t){return(new Cn).fromJson(e,t)}static fromJsonString(e,t){return(new Cn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Cn,e,t)}}Cn.runtime=Ce,Cn.typeName="livekit.SyncState",Cn.fields=Ce.util.newFieldList((()=>[{no:1,name:"answer",kind:"message",T:sn},{no:2,name:"subscription",kind:"message",T:an},{no:3,name:"publish_tracks",kind:"message",T:nn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Pn,repeated:!0},{no:5,name:"offer",kind:"message",T:sn}]));class Pn extends w{constructor(e){super(),this.label="",this.id=0,this.target=qi.PUBLISHER,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Pn).fromBinary(e,t)}static fromJson(e,t){return(new Pn).fromJson(e,t)}static fromJsonString(e,t){return(new Pn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Pn,e,t)}}Pn.runtime=Ce,Pn.typeName="livekit.DataChannelInfo",Pn.fields=Ce.util.newFieldList((()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:Ce.getEnumType(qi)}]));class Rn extends w{constructor(e){super(),this.scenario={case:void 0},Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Rn).fromBinary(e,t)}static fromJson(e,t){return(new Rn).fromJson(e,t)}static fromJsonString(e,t){return(new Rn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Rn,e,t)}}Rn.runtime=Ce,Rn.typeName="livekit.SimulateScenario",Rn.fields=Ce.util.newFieldList((()=>[{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:Ce.getEnumType(Wi),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"}]));class In extends w{constructor(e){super(),this.timestamp=M.zero,this.rtt=M.zero,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new In).fromBinary(e,t)}static fromJson(e,t){return(new In).fromJson(e,t)}static fromJsonString(e,t){return(new In).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(In,e,t)}}In.runtime=Ce,In.typeName="livekit.Ping",In.fields=Ce.util.newFieldList((()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]));class Dn extends w{constructor(e){super(),this.lastPingTimestamp=M.zero,this.timestamp=M.zero,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Dn).fromBinary(e,t)}static fromJson(e,t){return(new Dn).fromJson(e,t)}static fromJsonString(e,t){return(new Dn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Dn,e,t)}}Dn.runtime=Ce,Dn.typeName="livekit.Pong",Dn.fields=Ce.util.newFieldList((()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]));class _n extends w{constructor(e){super(),this.regions=[],Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new _n).fromBinary(e,t)}static fromJson(e,t){return(new _n).fromJson(e,t)}static fromJsonString(e,t){return(new _n).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(_n,e,t)}}_n.runtime=Ce,_n.typeName="livekit.RegionSettings",_n.fields=Ce.util.newFieldList((()=>[{no:1,name:"regions",kind:"message",T:Ln,repeated:!0}]));class Ln extends w{constructor(e){super(),this.region="",this.url="",this.distance=M.zero,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Ln).fromBinary(e,t)}static fromJson(e,t){return(new Ln).fromJson(e,t)}static fromJsonString(e,t){return(new Ln).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Ln,e,t)}}Ln.runtime=Ce,Ln.typeName="livekit.RegionInfo",Ln.fields=Ce.util.newFieldList((()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]));class Nn extends w{constructor(e){super(),this.trackSid="",this.err=Je.SE_UNKNOWN,Ce.util.initPartial(e,this)}static fromBinary(e,t){return(new Nn).fromBinary(e,t)}static fromJson(e,t){return(new Nn).fromJson(e,t)}static fromJsonString(e,t){return(new Nn).fromJsonString(e,t)}static equals(e,t){return Ce.util.equals(Nn,e,t)}}Nn.runtime=Ce,Nn.typeName="livekit.SubscriptionResponse",Nn.fields=Ce.util.newFieldList((()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Ce.getEnumType(Je)}]));class An extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class On extends An{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class Mn extends An{constructor(e){super(21,null!=e?e:"device is unsupported")}}class xn extends An{constructor(e){super(20,null!=e?e:"track is invalid")}}class Un extends An{constructor(e){super(10,null!=e?e:"unsupported server")}}class Bn extends An{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class Fn extends An{constructor(e){super(13,null!=e?e:"unable to negotiate")}}e.MediaDeviceFailure=void 0,(Hi=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",Hi.NotFound="NotFound",Hi.DeviceInUse="DeviceInUse",Hi.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}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={}));class Jn{}Jn.setTimeout=function(){return setTimeout(...arguments)},Jn.setInterval=function(){return setInterval(...arguments)},Jn.clearTimeout=function(){return clearTimeout(...arguments)},Jn.clearInterval=function(){return clearInterval(...arguments)};const jn=/version\/(\d+(\.?_?\d+)+)/i;let Vn;function qn(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===Vn||t){const e=Kn.find((e=>{let{test:t}=e;return t.test(i)}));Vn=null==e?void 0:e.describe(i)}return Vn}const Kn=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Wn(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Wn(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Wn(jn,e),os:e.includes("mobile/")?"iOS":"macOS"})}];function Wn(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]||""}const Hn="1.14.2";class Gn{constructor(e,t,i,n,r){this.width=e,this.height=t,this.encoding={maxBitrate:i,maxFramerate:n,priority:r}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}const zn=["vp8","h264"],Qn=["vp8","h264","vp9","av1"];function Yn(e){return!!zn.find((t=>t===e))}var Xn;e.AudioPresets=void 0,(Xn=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},Xn.speech={maxBitrate:2e4},Xn.music={maxBitrate:32e3},Xn.musicStereo={maxBitrate:48e3},Xn.musicHighQuality={maxBitrate:64e3},Xn.musicHighQualityStereo={maxBitrate:96e3};const Zn={h90:new Gn(160,90,9e4,20),h180:new Gn(320,180,16e4,20),h216:new Gn(384,216,18e4,20),h360:new Gn(640,360,45e4,20),h540:new Gn(960,540,8e5,25),h720:new Gn(1280,720,17e5,30),h1080:new Gn(1920,1080,3e6,30),h1440:new Gn(2560,1440,5e6,30),h2160:new Gn(3840,2160,8e6,30)},$n={h120:new Gn(160,120,7e4,20),h180:new Gn(240,180,125e3,20),h240:new Gn(320,240,14e4,20),h360:new Gn(480,360,33e4,20),h480:new Gn(640,480,5e5,20),h540:new Gn(720,540,6e5,25),h720:new Gn(960,720,13e5,30),h1080:new Gn(1440,1080,23e5,30),h1440:new Gn(1920,1440,38e5,30)},er={h360fps3:new Gn(640,360,2e5,3,"medium"),h720fps5:new Gn(1280,720,4e5,5,"medium"),h720fps15:new Gn(1280,720,15e5,15,"medium"),h720fps30:new Gn(1280,720,2e6,30,"medium"),h1080fps15:new Gn(1920,1080,25e5,15,"medium"),h1080fps30:new Gn(1920,1080,4e6,30,"medium")};var tr,ir,nr,rr;e.RoomEvent=void 0,(tr=e.RoomEvent||(e.RoomEvent={})).Connected="connected",tr.Reconnecting="reconnecting",tr.Reconnected="reconnected",tr.Disconnected="disconnected",tr.ConnectionStateChanged="connectionStateChanged",tr.StateChanged="connectionStateChanged",tr.MediaDevicesChanged="mediaDevicesChanged",tr.ParticipantConnected="participantConnected",tr.ParticipantDisconnected="participantDisconnected",tr.TrackPublished="trackPublished",tr.TrackSubscribed="trackSubscribed",tr.TrackSubscriptionFailed="trackSubscriptionFailed",tr.TrackUnpublished="trackUnpublished",tr.TrackUnsubscribed="trackUnsubscribed",tr.TrackMuted="trackMuted",tr.TrackUnmuted="trackUnmuted",tr.LocalTrackPublished="localTrackPublished",tr.LocalTrackUnpublished="localTrackUnpublished",tr.LocalAudioSilenceDetected="localAudioSilenceDetected",tr.ActiveSpeakersChanged="activeSpeakersChanged",tr.ParticipantMetadataChanged="participantMetadataChanged",tr.ParticipantNameChanged="participantNameChanged",tr.RoomMetadataChanged="roomMetadataChanged",tr.DataReceived="dataReceived",tr.ConnectionQualityChanged="connectionQualityChanged",tr.TrackStreamStateChanged="trackStreamStateChanged",tr.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",tr.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",tr.AudioPlaybackStatusChanged="audioPlaybackChanged",tr.MediaDevicesError="mediaDevicesError",tr.ParticipantPermissionsChanged="participantPermissionsChanged",tr.SignalConnected="signalConnected",tr.RecordingStatusChanged="recordingStatusChanged",tr.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",tr.EncryptionError="encryptionError",tr.DCBufferStatusChanged="dcBufferStatusChanged",tr.ActiveDeviceChanged="activeDeviceChanged",e.ParticipantEvent=void 0,(ir=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",ir.TrackSubscribed="trackSubscribed",ir.TrackSubscriptionFailed="trackSubscriptionFailed",ir.TrackUnpublished="trackUnpublished",ir.TrackUnsubscribed="trackUnsubscribed",ir.TrackMuted="trackMuted",ir.TrackUnmuted="trackUnmuted",ir.LocalTrackPublished="localTrackPublished",ir.LocalTrackUnpublished="localTrackUnpublished",ir.ParticipantMetadataChanged="participantMetadataChanged",ir.ParticipantNameChanged="participantNameChanged",ir.DataReceived="dataReceived",ir.IsSpeakingChanged="isSpeakingChanged",ir.ConnectionQualityChanged="connectionQualityChanged",ir.TrackStreamStateChanged="trackStreamStateChanged",ir.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",ir.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",ir.MediaDevicesError="mediaDevicesError",ir.ParticipantPermissionsChanged="participantPermissionsChanged",ir.PCTrackAdded="pcTrackAdded",e.EngineEvent=void 0,(nr=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",nr.Connected="connected",nr.Disconnected="disconnected",nr.Resuming="resuming",nr.Resumed="resumed",nr.Restarting="restarting",nr.Restarted="restarted",nr.SignalResumed="signalResumed",nr.SignalRestarted="signalRestarted",nr.Closing="closing",nr.MediaTrackAdded="mediaTrackAdded",nr.ActiveSpeakersUpdate="activeSpeakersUpdate",nr.DataPacketReceived="dataPacketReceived",nr.RTPVideoMapUpdate="rtpVideoMapUpdate",nr.DCBufferStatusChanged="dcBufferStatusChanged",nr.ParticipantUpdate="participantUpdate",nr.RoomUpdate="roomUpdate",nr.SpeakersChanged="speakersChanged",nr.StreamStateChanged="streamStateChanged",nr.ConnectionQualityUpdate="connectionQualityUpdate",nr.SubscriptionError="subscriptionError",nr.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.TrackEvent=void 0,(rr=e.TrackEvent||(e.TrackEvent={})).Message="message",rr.Muted="muted",rr.Unmuted="unmuted",rr.Restarted="restarted",rr.Ended="ended",rr.Subscribed="subscribed",rr.Unsubscribed="unsubscribed",rr.UpdateSettings="updateSettings",rr.UpdateSubscription="updateSubscription",rr.AudioPlaybackStarted="audioPlaybackStarted",rr.AudioPlaybackFailed="audioPlaybackFailed",rr.AudioSilenceDetected="audioSilenceDetected",rr.VisibilityChanged="visibilityChanged",rr.VideoDimensionsChanged="videoDimensionsChanged",rr.ElementAttached="elementAttached",rr.ElementDetached="elementDetached",rr.UpstreamPaused="upstreamPaused",rr.UpstreamResumed="upstreamResumed",rr.SubscriptionPermissionChanged="subscriptionPermissionChanged",rr.SubscriptionStatusChanged="subscriptionStatusChanged",rr.SubscriptionFailed="subscriptionFailed";const sr=[];class or extends Bt.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=or.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=or.Source.Unknown}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let i="audio";this.kind===or.Kind.Video&&(i="video"),0===this.attachedElements.length&&or.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===i&&(sr.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&sr.splice(sr.indexOf(t),1)),t||(t=document.createElement(i))),this.attachedElements.includes(t)||this.attachedElements.push(t),ar(this.mediaStreamTrack,t);const n=t.srcObject.getTracks();return n.some((e=>"audio"===e.kind))&&t.play().then((()=>{this.emit(e.TrackEvent.AudioPlaybackStarted)})).catch((i=>{"NotAllowedError"===i.name?this.emit(e.TrackEvent.AudioPlaybackFailed,i):a.warn("could not playback audio",i),t&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===i.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){cr(this.mediaStreamTrack,t);const i=this.attachedElements.indexOf(t);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const i=[];return this.attachedElements.forEach((t=>{cr(this.mediaStreamTrack,t),i.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],i}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)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),sr.forEach((e=>{e.parentElement||(t=!1)})),t&&sr.push(e)}}handleAppVisibilityChanged(){return kt(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState}))}addAppVisibilityListener(){Rr()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Rr()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ar(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)),t.autoplay=!0,t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Cr()||Er())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function cr(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 dr(e,t,i){var n;const r=null!==(n=function(e){if(void 0!==e)return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}(e))&&void 0!==n?n:{};return!0===r.audio&&(r.audio={}),!0===r.video&&(r.video={}),r.audio&&ur(r.audio,t),r.video&&ur(r.video,i),r}function ur(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function lr(e){const t={};if(e.video)if("object"==typeof e.video){const i={},n=i,r=e.video;Object.keys(r).forEach((e=>{if("resolution"===e)ur(n,r.resolution);else n[e]=r[e]})),t.video=i}else t.video=e.video;else t.video=!1;return e.audio?"object"==typeof e.audio?t.audio=e.audio:t.audio=!0:t.audio=!1,t}function hr(){const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}function pr(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&(n="boolean"==typeof n?{}:n,n=Cr()?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}}function mr(e){const t=e.split("/")[1].toLowerCase();if(!Qn.includes(t))throw Error("Video codec not supported: ".concat(t));return t}!function(e){let t,i,n;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(i=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(n=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Ae.AUDIO;case t.Video:return Ae.VIDEO;default:return Ae.DATA}},e.kindFromProto=function(e){switch(e){case Ae.AUDIO:return t.Audio;case Ae.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return Oe.CAMERA;case i.Microphone:return Oe.MICROPHONE;case i.ScreenShare:return Oe.SCREEN_SHARE;case i.ScreenShareAudio:return Oe.SCREEN_SHARE_AUDIO;default:return Oe.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case Oe.CAMERA:return i.Camera;case Oe.MICROPHONE:return i.Microphone;case Oe.SCREEN_SHARE:return i.ScreenShare;case Oe.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Ki.ACTIVE:return n.Active;case Ki.PAUSED:return n.Paused;default:return n.Unknown}}}(or||(or={}));const fr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function vr(e){return kt(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}function gr(){return"addTransceiver"in RTCPeerConnection.prototype}function yr(){return"addTrack"in RTCPeerConnection.prototype}function kr(){if(!("getCapabilities"in RTCRtpSender))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}function br(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Er())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}function Tr(e){return"av1"===e||"vp9"===e}function Sr(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}const wr={Chrome:"100",Safari:"15",Firefox:"100"};function Er(){var e;return"Firefox"===(null===(e=qn())||void 0===e?void 0:e.name)}function Cr(){var e;return"Safari"===(null===(e=qn())||void 0===e?void 0:e.name)}function Pr(){return!!Rr()&&/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent)}function Rr(){return"undefined"!=typeof document}function Ir(){return"ReactNative"==navigator.product}function Dr(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function _r(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Lr(){if(!Ir())return;let e=_r();return e?e.platform:void 0}function Nr(){if(Rr())return window.devicePixelRatio;if(Ir()){let e=_r();if(e)return e.devicePixelRatio}return 1}function Ar(e,t){const i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){const t=parseInt(i[e],10),s=parseInt(n[e],10);if(t>s)return 1;if(t<s)return-1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function Or(e){for(const t of e)t.target.handleResize(t)}function Mr(e){for(const t of e)t.target.handleVisibilityChanged(t)}let xr=null;const Ur=()=>(xr||(xr=new ResizeObserver(Or)),xr);let Br=null;const Fr=()=>(Br||(Br=new IntersectionObserver(Mr,{root:null,rootMargin:"0px"})),Br);let Jr,jr;function Vr(){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 r=document.createElement("canvas");r.width=e,r.height=t;const s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}function qr(){if(!jr){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(),[jr]=n.stream.getAudioTracks(),!jr)throw Error("Could not get empty media stream audio track");jr.enabled=!1}return jr.clone()}class Kr{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>kt(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)}))}}class Wr{constructor(){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 Hr(e){if("string"==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 Gr(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}var zr;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(zr||(zr={}));class Qr{constructor(){this.pendingTasks=new Map,this.taskMutex=new Wr,this.nextTaskIndex=0}run(e){return kt(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:zr.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=zr.RUNNING,yield e()}finally{t.status=zr.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return kt(this,void 0,void 0,(function*(){return this.run((()=>kt(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const Yr=["syncState","trickle","offer","answer","simulate","leave"];class Xr{constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.rtt=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.isConnected=!1,this.isReconnecting=!1,this.useJSON=e,this.requestQueue=new Qr,this.queuedRequests=[],this.closingLock=new Wr}join(e,t,i,n){return kt(this,void 0,void 0,(function*(){this.isConnected=!1,this.options=i;return yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return kt(this,void 0,void 0,(function*(){if(!this.options)return void a.warn("attempted to reconnect without signal options being set, ignoring");this.isReconnecting=!0,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))}))}connect(e,t,i,n){this.connectOptions=i,e=(e=function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e)).replace(/\/$/,""),e+="/rtc";const r=function(e,t,i){var n;const r=new URLSearchParams;r.set("access_token",e),i.reconnect&&(r.set("reconnect","1"),i.sid&&r.set("sid",i.sid));r.set("auto_subscribe",i.autoSubscribe?"1":"0"),r.set("sdk",Ir()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);void 0!==i.publishOnly&&r.set("publish",i.publishOnly);i.adaptiveStream&&r.set("adaptive_stream","1");i.reconnectReason&&r.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&r.set("network",navigator.connection.type);return"?".concat(r.toString())}(t,function(){var e;const t=new dt({sdk:Ze.JS,protocol:10,version:Hn});return Ir()&&(t.os=null!==(e=Lr())&&void 0!==e?e:""),t}(),i);return new Promise(((t,s)=>kt(this,void 0,void 0,(function*(){const o=()=>kt(this,void 0,void 0,(function*(){this.close(),clearTimeout(c),s(new On("room connection has been cancelled (signal)"))})),c=setTimeout((()=>{this.close(),s(new On("room connection has timed out (signal)"))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&o(),null==n||n.addEventListener("abort",o),a.debug("connecting to ".concat(e+r)),this.ws&&(yield this.close()),this.ws=new WebSocket(e+r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(c)},this.ws.onerror=t=>kt(this,void 0,void 0,(function*(){if(this.isConnected)this.handleWSError(t);else{clearTimeout(c);try{const t=yield fetch("http".concat(e.substring(2),"/validate").concat(r));if(t.status.toFixed(0).startsWith("4")){const e=yield t.text();s(new On(e,0,t.status))}else s(new On("Internal error",2,t.status))}catch(e){s(new On("server was not reachable",1))}}})),this.ws.onmessage=e=>kt(this,void 0,void 0,(function*(){var r,c,d,u;let l;if("string"==typeof e.data){const t=JSON.parse(e.data);l=Qi.fromJson(t)}else{if(!(e.data instanceof ArrayBuffer))return void a.error("could not decode websocket message: ".concat(typeof e.data));l=Qi.fromBinary(new Uint8Array(e.data))}if(!this.isConnected){let e=!1;if("join"===(null===(r=l.message)||void 0===r?void 0:r.case)?(this.isConnected=!0,null==n||n.removeEventListener("abort",o),this.pingTimeoutDuration=l.message.value.pingTimeout,this.pingIntervalDuration=l.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(a.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.startPingInterval()),t(l.message.value)):i.reconnect?(this.isConnected=!0,null==n||n.removeEventListener("abort",o),this.startPingInterval(),"reconnect"===(null===(c=l.message)||void 0===c?void 0:c.case)?t(null===(d=l.message)||void 0===d?void 0:d.value):(t(),e=!0)):i.reconnect||s(new On("did not receive join response, got ".concat(null===(u=l.message)||void 0===u?void 0:u.case," instead"))),!e)return}this.signalLatency&&(yield vr(this.signalLatency)),this.handleSignalResponse(l)})),this.ws.onclose=e=>{a.warn("websocket closed",{ev:e}),this.handleOnClose(e.reason)}}))))}close(){return kt(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();try{if(this.isConnected=!1,this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const e=new Promise((e=>{this.ws?this.ws.onclose=()=>{e()}:e()}));this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([e,vr(250)])),this.ws=void 0}}finally{this.clearPingInterval(),e()}}))}sendOffer(e){a.debug("sending offer",e),this.sendRequest({case:"offer",value:$r(e)})}sendAnswer(e){return a.debug("sending answer"),this.sendRequest({case:"answer",value:$r(e)})}sendIceCandidate(e,t){return a.trace("sending ice candidate",e),this.sendRequest({case:"trickle",value:new Zi({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new $i({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return this.sendRequest({case:"updateMetadata",value:new ln({metadata:e,name:t})})}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 un({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new wn({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:M.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new In({timestamp:M.parse(Date.now()),rtt:M.parse(this.rtt)})})])}sendLeave(){return this.sendRequest({case:"leave",value:new dn({canReconnect:!1,reason:e.DisconnectReason.CLIENT_INITIATED})})}sendRequest(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return kt(this,void 0,void 0,(function*(){const i=!t&&!function(e){const t=Yr.indexOf(e.case)>=0;return a.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&this.isReconnecting)return void this.queuedRequests.push((()=>kt(this,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield vr(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN)return void a.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case));const n=new zi({message:e});try{this.useJSON?this.ws.send(n.toJsonString()):this.ws.send(n.toBinary())}catch(e){a.error("error sending signal message",{error:e})}}))}handleSignalResponse(e){var t,i;const n=e.message;if(null!=n)if("answer"===n.case){const e=Zr(n.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.case){const e=Zr(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?this.resetPingTimeout():"pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout()):a.debug("unsupported message",n);else a.debug("received unsupported message")}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}this.isReconnecting=!1}handleOnClose(e){return kt(this,void 0,void 0,(function*(){if(!this.isConnected)return;const t=this.onClose;yield this.close(),a.debug("websocket connection closed: ".concat(e)),t&&t(e)}))}handleWSError(e){a.error("websocket error",e)}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Jn.setTimeout((()=>{a.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):a.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&Jn.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(a.debug("start ping interval"),this.pingInterval=Jn.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):a.warn("ping interval duration not set")}clearPingInterval(){a.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&Jn.clearInterval(this.pingInterval)}}function Zr(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 $r(e){return new sn({sdp:e.sdp,type:e.type})}const es="AES-GCM",ts="lk_e2ee",is={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10};var ns,rs;function ss(){return as()||os()}function os(){return void 0!==window.RTCRtpScriptTransform}function as(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function cs(e){return kt(this,void 0,void 0,(function*(){let t=new TextEncoder;return yield crypto.subtle.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])}))}function ds(e){return kt(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function us(e,t){const i=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:i,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:i,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,(ns=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",ns.RatchetRequest="ratchetRequest",ns.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(rs=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",rs.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";class ls extends Bt.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.onKeyRatcheted=(e,t)=>{a.debug("key ratcheted event received",{material:e,keyIndex:t})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},is),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,i,n){const r={key:t,participantIdentity:i,keyIndex:n};this.keyInfoMap.set("".concat(null!=i?i:"shared","-").concat(null!=n?n:0),r),this.emit(e.KeyProviderEvent.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,i){this.emit(e.KeyProviderEvent.RatchetRequest,t,i)}}function hs(e,t,i){var n,r,s;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(r=i.callback)&&r,c=i.maxWait,d=Date.now(),u=[];function l(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),i=this;return new Promise((function(n,r){var c=o&&void 0===s;if(void 0!==s&&clearTimeout(s),s=setTimeout((function(){if(s=void 0,d=Date.now(),!o){var n=e.apply(i,t);a&&a(n),u.forEach((function(e){return(0,e.resolve)(n)})),u=[]}}),l()),c){var h=e.apply(i,t);return a&&a(h),n(h)}u.push({resolve:n,reject:r})}))};return h.cancel=function(e){void 0!==s&&clearTimeout(s),u.forEach((function(t){return(0,t.reject)(e)})),u=[]},h}const ps="default";class ms{static getInstance(){return void 0===this.instance&&(this.instance=new ms),this.instance}getDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i;return kt(this,void 0,void 0,(function*(){if((null===(i=ms.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){a.debug("awaiting getUserMedia promise");try{e?yield ms.userMediaPromiseMap.get(e):yield Promise.all(ms.userMediaPromiseMap.values())}catch(e){a.warn("error waiting for media permissons")}}let n=yield navigator.mediaDevices.enumerateDevices();if(t&&(!Cr()||!this.hasDeviceInUse(e))){if(0===n.length||n.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},i=yield navigator.mediaDevices.getUserMedia(t);n=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return e&&(n=n.filter((t=>t.kind===e))),n}))}normalizeDeviceId(e,t,i){return kt(this,void 0,void 0,(function*(){if(t!==ps)return t;const n=(yield this.getDevices(e)).find((e=>e.groupId===i&&e.deviceId!==ps));return null==n?void 0:n.deviceId}))}hasDeviceInUse(e){return e?ms.userMediaPromiseMap.has(e):ms.userMediaPromiseMap.size>0}}ms.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ms.userMediaPromiseMap=new Map;class fs extends or{get constraints(){return this._constraints}constructor(t,i,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,i),this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>a.debug("track mute bounce got cancelled by an unmute event"))),this.debouncedTrackMuteHandler=hs((()=>kt(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>kt(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(e.TrackEvent.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Wr,this.pauseUpstreamLock=new Wr,this.processorLock=new Wr,this.setMediaStreamTrack(t,!0),this._constraints=t.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==or.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}setMediaStreamTrack(e,t){return kt(this,void 0,void 0,(function*(){if(e===this._mediaStreamTrack&&!t)return;let i;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{cr(this._mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop()),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&&this.processorElement){if(a.debug("restarting processor"),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");ar(e,this.processorElement),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}this.sender&&(yield this.sender.replaceTrack(null!=i?i:e)),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{ar(null!=i?i:e,t)})))}))}waitForDimensions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;var t;return kt(this,void 0,void 0,(function*(){if(this.kind===or.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(t=qn())||void 0===t?void 0:t.os)&&(yield vr(10));const i=Date.now();for(;Date.now()-i<e;){const e=this.dimensions;if(e)return e;yield vr(50)}throw new xn("unable to get track dimensions after timeout")}))}getDeviceId(){return kt(this,void 0,void 0,(function*(){if(this.source===or.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),i=this.kind===or.Kind.Audio?"audioinput":"videoinput";return ms.getInstance().normalizeDeviceId(i,e,t)}))}mute(){return kt(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return kt(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return kt(this,void 0,void 0,(function*(){if(!this.sender)throw new xn("unable to replace an unpublished track");return a.debug("replace MediaStreamTrack"),yield this.setMediaStreamTrack(e),this.providedByUser=t,this.processor&&(yield this.stopProcessor()),this}))}restart(t){return kt(this,void 0,void 0,(function*(){t||(t=this._constraints),a.debug("restarting track with constraints",t);const i={audio:!1,video:!1};this.kind===or.Kind.Video?i.video=t:i.audio=t,this.attachedElements.forEach((e=>{cr(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const n=(yield navigator.mediaDevices.getUserMedia(i)).getTracks()[0];return n.addEventListener("ended",this.handleEnded),a.debug("re-acquired MediaStreamTrack"),yield this.setMediaStreamTrack(n),this._constraints=t,this.emit(e.TrackEvent.Restarted,this),this}))}setTrackMuted(t){a.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted")),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.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 kt(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Pr()&&(a.debug("visibility changed, is in Background: ".concat(this.isInBackground)),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(a.debug("track needs to be reacquired, restarting ".concat(this.source)),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;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 kt(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void a.warn("unable to pause upstream for an unpublished track");this._isUpstreamPaused=!0,this.emit(e.TrackEvent.UpstreamPaused,this);const t=qn();if("Safari"===(null==t?void 0:t.name)&&Ar(t.version,"12.0")<0)throw new Mn("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{t()}}))}resumeUpstream(){return kt(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void a.warn("unable to resume upstream for an unpublished track");this._isUpstreamPaused=!1,this.emit(e.TrackEvent.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{t()}}))}getRTCStatsReport(){var e;return kt(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i,n;return kt(this,void 0,void 0,(function*(){const r=yield this.processorLock.lock();try{if(a.debug("setting up processor"),this.processor&&(yield this.stopProcessor()),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement=null!==(i=this.processorElement)&&void 0!==i?i:document.createElement(this.kind),this.processorElement.muted=!0,ar(this._mediaStreamTrack,this.processorElement),this.processorElement.play().catch((e=>a.error("failed to play processor element",{error:e})));const r={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement};if(yield e.init(r),this.processor=e,this.processor.processedTrack){for(const e of this.attachedElements)e!==this.processorElement&&t&&(cr(this._mediaStreamTrack,e),ar(this.processor.processedTrack,e));yield null===(n=this.sender)||void 0===n?void 0:n.replaceTrack(this.processor.processedTrack)}}finally{r()}}))}getProcessor(){return this.processor}stopProcessor(){var e,t;return kt(this,void 0,void 0,(function*(){this.processor&&(a.debug("stopping processor"),null===(e=this.processor.processedTrack)||void 0===e||e.stop(),yield this.processor.destroy(),this.processor=void 0,null===(t=this.processorElement)||void 0===t||t.remove(),this.processorElement=void 0,yield this.restart())}))}}class vs extends Bt.EventEmitter{constructor(t){super(),this.onWorkerMessage=t=>{var i,n;const{kind:r,data:s}=t.data;switch(r){case"error":a.error(s.error.message),this.emit(e.EncryptionEvent.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const t=null===(n=this.room)||void 0===n?void 0:n.getParticipantByIdentity(s.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,s.enabled,t)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,s.material,s.keyIndex)}},this.onWorkerError=t=>{a.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1}setup(e){if(!ss())throw new Mn("tried to setup end-to-end encryption on an unsupported browser");if(a.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions()}};this.worker&&(a.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){a.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):a.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,i){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==Qe.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(i=>{i===e.ConnectionState.Connected&&t.participants.forEach((e=>{e.tracks.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==Qe.NONE,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,i)=>{var n;const r={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(r)})).on(e.RoomEvent.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(e.RoomEvent.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity),i.getKeys().forEach((e=>{this.postKey(e)}))})),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>kt(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),i.on(e.KeyProviderEvent.SetKey,(e=>this.postKey(e))).on(e.KeyProviderEvent.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 r;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(r=this.room)||void 0===r?void 0:r.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(s)}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?mr(i.mimeType):void 0)}}setupE2EESender(e,t){e instanceof fs&&t?this.handleSender(t,e.mediaStreamID,void 0):t||a.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return kt(this,void 0,void 0,(function*(){if(this.worker){if(os()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(ts in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let r=e.writableStream,s=e.readableStream;if(!r||!s){const t=e.createEncodedStreams();e.writableStream=t.writable,r=t.writable,e.readableStream=t.readable,s=t.readable}const o={kind:"decode",data:{readableStream:s,writableStream:r,trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(o,[s,r])}e[ts]=!0}}))}handleSender(e,t,i){var n;if(!(ts 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(os()){a.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{a.info("initialize encoded streams");const n=e.createEncodedStreams(),r={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(r,[n.readable,n.writable])}e[ts]=!0}}}var gs={},ys={exports:{}},ks=ys.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",t+=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":"",t+=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"]}]};Object.keys(ks).forEach((function(e){ks[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var bs=ys.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;!function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=bs,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(r))return i(c,o,r)}})),t.media=s,t};var s=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(s,{})},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),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},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}}))}))}}(gs);var Ts=bs,Ss=/%[sdv%]/g,ws=function(e){var t=1,i=arguments,n=i.length;return e.replace(Ss,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},Es=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var s=t.names[r];t.name?n.push(i[t.name][s]):n.push(i[t.names[r]])}else n.push(i[t.name]);return ws.apply(null,n)},Cs=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ps=["i","c","b","a"],Rs=gs,Is=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||Cs,n=t.innerOrder||Ps,r=[];return i.forEach((function(t){Ts[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push(Es(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(Es(t,i,e))}))}))})),e.media.forEach((function(e){r.push(Es("m",Ts.m[0],e)),n.forEach((function(t){Ts[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push(Es(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(Es(t,i,e))}))}))}))})),r.join("\r\n")+"\r\n"},Ds=Is,_s=Rs.parse;const Ls="negotiationStarted",Ns="negotiationComplete",As="rtpVideoPayloadTypes";class Os extends Bt.EventEmitter{get pc(){if(this._pc)return this._pc;throw new Bn("Expected peer connection to be available")}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=hs((e=>{this.emit(Ls);try{this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),100),this._pc="Chrome"===(null===(i=qn())||void 0===i?void 0:i.name)?new RTCPeerConnection(e,t):new RTCPeerConnection(e),this._pc.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},this._pc.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},this._pc.onconnectionstatechange=()=>{var e,t,i;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,null!==(i=null===(t=this._pc)||void 0===t?void 0:t.connectionState)&&void 0!==i?i:"closed")},this._pc.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this._pc.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)}}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return kt(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){var t;return kt(this,void 0,void 0,(function*(){let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],r=_s(null!==(t=e.sdp)&&void 0!==t?t:"");let s=0;return r.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(s=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===s&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===s&&(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=_s(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 r of e.fmtp)if(r.payload===i){r.config=r.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(r.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=Ds(n)}if(yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,this.createAndSendOffer();else if("answer"===e.type&&(this.emit(Ns),e.sdp)){_s(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(As,e.rtp)}))}}))}createAndSendOffer(e){var t;return kt(this,void 0,void 0,(function*(){if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(a.debug("restarting ICE"),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 a.warn("could not createOffer with closed peer connection");a.debug("starting to negotiate");const i=yield this.pc.createOffer(e),n=_s(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type?Ms(e,[],[]):"video"===e.type&&(!function(e){var t,i,n,r;const s=null===(i=null===(t=e.rtp[0])||void 0===t?void 0:t.codec)||void 0===i?void 0:i.toLowerCase();if(!Tr(s))return;let o=0;const a=null===(n=e.ext)||void 0===n?void 0:n.some((e=>e.uri===fr||(e.value>o&&(o=e.value),!1)));a||null===(r=e.ext)||void 0===r||r.push({value:o+1,uri:fr})}(e),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;let n=!1;for(const r of e.fmtp)if(r.payload===i){r.config.includes("x-google-start-bitrate")||(r.config+=";x-google-start-bitrate=".concat(.7*t.maxbr)),r.config.includes("x-google-max-bitrate")||(r.config+=";x-google-max-bitrate=".concat(t.maxbr)),n=!0;break}return n||e.fmtp.push({payload:i,config:"x-google-start-bitrate=".concat(.7*t.maxbr,";x-google-max-bitrate=").concat(t.maxbr)}),!0})))})),yield this.setMungedSDP(i,Ds(n)),this.onOffer(i)}))}createAndSetAnswer(){var e;return kt(this,void 0,void 0,(function*(){const t=yield this.pc.createAnswer(),i=_s(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{"audio"===e.type&&Ms(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Ds(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){return this.pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){return this.pc.setConfiguration(e)}canRemoveTrack(){return!!this.pc.removeTrack}removeTrack(e){return this.pc.removeTrack(e)}getConnectionState(){return this.pc.connectionState}getICEConnectionState(){return this.pc.iceConnectionState}getSignallingState(){return this.pc.signalingState}getTransceivers(){return this.pc.getTransceivers()}getSenders(){return this.pc.getSenders()}getLocalDescription(){return this.pc.localDescription}getRemoteDescription(){return this.pc.remoteDescription}getConnectedAddress(){var e;return kt(this,void 0,void 0,(function*(){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 r=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==r?n.get(r):void 0}))}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)}setMungedSDP(e,t,i){return kt(this,void 0,void 0,(function*(){if(t){const n=e.sdp;e.sdp=t;try{return a.debug("setting munged ".concat(i?"remote":"local"," description")),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(i){a.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:i,sdp:t}),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let n="unknown error";t instanceof Error?n=t.message:"string"==typeof t&&(n=t);const r={error:n,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(r.remoteSdp=this.pc.remoteDescription),a.error("unable to set ".concat(e.type),r),new Fn(n)}}))}}function Ms(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))))}const xs={audioBitrate:e.AudioPresets.music.maxBitrate,audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:er.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!1},Us={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},Bs={resolution:Zn.h720.resolution},Fs={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new yt,disconnectOnPageLeave:!0,expWebAudioMix:!1},Js={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},js="_lossy",Vs="_reliable",qs="leave-reconnect";var Ks;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(Ks||(Ks={}));class Ws extends Bt.EventEmitter{get isClosed(){return this._isClosed}constructor(t){super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Js.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ks.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.handleDataChannel=e=>{let{channel:t}=e;return kt(this,void 0,void 0,(function*(){if(t){if(t.label===Vs)this.reliableDCSub=t;else{if(t.label!==js)return;this.lossyDCSub=t}a.debug("on data channel ".concat(t.id,", ").concat(t.label)),t.onmessage=this.handleDataMessage}}))},this.handleDataMessage=t=>kt(this,void 0,void 0,(function*(){var i,n;const r=yield this.dataProcessLock.lock();try{let r;if(t.data instanceof ArrayBuffer)r=t.data;else{if(!(t.data instanceof Blob))return void a.error("unsupported data type",t.data);r=yield t.data.arrayBuffer()}const s=nt.fromBinary(new Uint8Array(r));"speaker"===(null===(i=s.value)||void 0===i?void 0:i.case)?this.emit(e.EngineEvent.ActiveSpeakersUpdate,s.value.value.speakers):"user"===(null===(n=s.value)||void 0===n?void 0:n.case)&&this.emit(e.EngineEvent.DataPacketReceived,s.value.value,s.kind)}finally{r()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;a.error("DataChannel error on ".concat(t,": ").concat(e.message),i)}else a.error("Unknown DataChannel error on ".concat(t),e)},this.handleBufferedAmountLow=t=>{const i=0===t.currentTarget.maxRetransmits?e.DataPacket_Kind.LOSSY:e.DataPacket_Kind.RELIABLE;this.updateAndEmitDCBufferStatus(i)},this.handleDisconnect=(t,i)=>{if(this._isClosed)return;a.warn("".concat(t," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const n=t=>{a.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),this.close()},r=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});null!==s?(t===qs&&(s=0),a.debug("reconnecting in ".concat(s,"ms")),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Jn.setTimeout((()=>this.attemptReconnect(i)),s)):n(r)},this.waitForRestarted=()=>new Promise(((t,i)=>{this.pcState===Ks.Connected&&t();const n=()=>{this.off(e.EngineEvent.Disconnected,r),t()},r=()=>{this.off(e.EngineEvent.Restarted,n),i()};this.once(e.EngineEvent.Restarted,n),this.once(e.EngineEvent.Disconnected,r)})),this.updateAndEmitDCBufferStatus=t=>{const i=this.isBufferStatusLow(t);void 0!==i&&i!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,i),this.emit(e.EngineEvent.DCBufferStatusChanged,i,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.isReconnecting&&(this.clearReconnectTimeout(),this.attemptReconnect(Fe.RR_SIGNAL_DISCONNECTED))},this.client=new Xr,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Wr,this.dataProcessLock=new Wr,this.dcBufferStatus=new Map([[e.DataPacket_Kind.LOSSY,!0],[e.DataPacket_Kind.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(e.EngineEvent.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(e.EngineEvent.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(e.EngineEvent.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(e.EngineEvent.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(e.EngineEvent.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(e.EngineEvent.StreamStateChanged,t)}join(e,t,i,n){return kt(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 r=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.publisher||this.configure(r),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=r.clientConfiguration,r}catch(r){if(r instanceof On&&1===r.reason&&(a.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts)),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw r}}))}close(){return kt(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return kt(this,void 0,void 0,(function*(){this.publisher&&"closed"!==this.publisher.getSignallingState()&&this.publisher.getSenders().forEach((e=>{var t,i;try{(null===(t=this.publisher)||void 0===t?void 0:t.canRemoveTrack())&&(null===(i=this.publisher)||void 0===i||i.removeTrack(e))}catch(e){a.warn("could not removeTrack",{error:e})}})),this.publisher&&(this.publisher.close(),this.publisher=void 0),this.subscriber&&(this.subscriber.close(),this.subscriber=void 0),this.hasPublished=!1,this.primaryTransport=void 0;const e=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0}))}cleanupClient(){return kt(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new xn("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 On("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){var t;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 null===(t=this.publisher)||void 0===t||t.removeTrack(e),!0}catch(e){a.warn("failed to remove track",{error:e,method:"removeTrack"})}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 kt(this,void 0,void 0,(function*(){if(void 0!==this.primaryTransport)return this.primaryTransport.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(t){var i,n;if(this.publisher||this.subscriber)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const r=this.makeRTCConfiguration(t);(null===(n=this.signalOpts)||void 0===n?void 0:n.e2eeEnabled)&&(a.debug("E2EE - setting up transports with insertable streams"),r.encodedInsertableStreams=!0);this.publisher=new Os(r,{optional:[{googDscp:!0}]}),this.subscriber=new Os(r),this.emit(e.EngineEvent.TransportsCreated,this.publisher,this.subscriber),this.publisher.onIceCandidate=e=>{a.trace("adding ICE candidate for peer",e),this.client.sendIceCandidate(e,qi.PUBLISHER)},this.subscriber.onIceCandidate=e=>{this.client.sendIceCandidate(e,qi.SUBSCRIBER)},this.publisher.onOffer=e=>{this.client.sendOffer(e)};let s=this.publisher,o=this.subscriber,c=t.subscriberPrimary;c&&(s=this.subscriber,o=this.publisher,this.subscriber.onDataChannel=this.handleDataChannel),this.primaryTransport=s,s.onConnectionStateChange=i=>kt(this,void 0,void 0,(function*(){if(a.debug("primary PC state changed ".concat(i)),"connected"===i){const i=this.pcState===Ks.New;this.pcState=Ks.Connected,i&&this.emit(e.EngineEvent.Connected,t)}else"failed"===i&&this.pcState===Ks.Connected&&(this.pcState=Ks.Disconnected,this.handleDisconnect("primary peerconnection",c?Fe.RR_SUBSCRIBER_FAILED:Fe.RR_PUBLISHER_FAILED))})),o.onConnectionStateChange=e=>kt(this,void 0,void 0,(function*(){a.debug("secondary PC state changed ".concat(e)),"failed"===e&&this.handleDisconnect("secondary peerconnection",c?Fe.RR_PUBLISHER_FAILED:Fe.RR_SUBSCRIBER_FAILED)})),this.subscriber.onTrack=t=>{this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},this.createDataChannels()}setupSignalClientCallbacks(){this.client.onAnswer=e=>kt(this,void 0,void 0,(function*(){this.publisher&&(a.debug("received server answer",{RTCSdpType:e.type,signalingState:this.publisher.getSignallingState().toString()}),yield this.publisher.setRemoteDescription(e))})),this.client.onTrickle=(e,t)=>{this.publisher&&this.subscriber&&(a.trace("got ICE candidate from peer",{candidate:e,target:t}),t===qi.PUBLISHER?this.publisher.addIceCandidate(e):this.subscriber.addIceCandidate(e))},this.client.onOffer=e=>kt(this,void 0,void 0,(function*(){if(!this.subscriber)return;a.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.getSignallingState().toString()}),yield this.subscriber.setRemoteDescription(e);const t=yield this.subscriber.createAndSetAnswer();this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{if(a.debug("received trackPublishedResponse",e),!this.pendingTrackResolvers[e.cid])return void a.error("missing track resolver for ".concat(e.cid));const{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onClose=()=>{this.handleDisconnect("signal",Fe.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{(null==t?void 0:t.canReconnect)?(this.fullReconnectOnNext=!0,this.primaryTransport=void 0,this.handleDisconnect(qs)):(this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close()),a.trace("leave request",{leave:t})}}makeRTCConfiguration(e){const t=Object.assign({},this.rtcConfig);if(e.iceServers&&!t.iceServers){const i=[];e.iceServers.forEach((e=>{const t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),i.push(t)})),t.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ue.ENABLED&&(t.iceTransportPolicy="relay"),t.sdpSemantics="unified-plan",t.continualGatheringPolicy="gather_continually",t}createDataChannels(){this.publisher&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.publisher.createDataChannel(js,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.createDataChannel(Vs,{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)}setPreferredCodec(e,t,i){if(!("getCapabilities"in RTCRtpSender))return;const n=RTCRtpSender.getCapabilities(t);if(!n)return;a.debug("get capabilities",n);const r=[],s=[],o=[];n.codecs.forEach((e=>{const t=e.mimeType.toLowerCase();if("audio/opus"===t)return void r.push(e);t==="video/".concat(i)?"h264"!==i||e.sdpFmtpLine&&e.sdpFmtpLine.includes("profile-level-id=42e01f")?r.push(e):s.push(e):o.push(e)})),function(e){if(!Rr())return!1;if(!("setCodecPreferences"in e))return!1;const t=qn();if(!(null==t?void 0:t.name)||!t.version)return!1;const i=wr[t.name];return!!i&&Ar(t.version,i)>=0}(e)&&e.setCodecPreferences(r.concat(s,o))}createSender(e,t,i){return kt(this,void 0,void 0,(function*(){if(gr()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(yr()){a.warn("using add-track fallback");return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new Bn("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return kt(this,void 0,void 0,(function*(){if(gr())return this.createSimulcastTransceiverSender(e,t,i,n);if(yr())return a.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new Bn("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return kt(this,void 0,void 0,(function*(){if(!this.publisher)throw new Bn("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream);const r={direction:"sendonly",streams:n};i&&(r.sendEncodings=i);const s=yield this.publisher.addTransceiver(e.mediaStreamTrack,r);return e.kind===or.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(s,e.kind,t.videoCodec),e.codec=t.videoCodec),s.sender}))}createSimulcastTransceiverSender(e,t,i,n){return kt(this,void 0,void 0,(function*(){if(!this.publisher)throw new Bn("publisher is closed");const r={direction:"sendonly"};n&&(r.sendEncodings=n);const s=yield this.publisher.addTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return this.setPreferredCodec(s,e.kind,i.videoCodec),e.setSimulcastTrackSender(i.videoCodec,s.sender),s.sender}))}createRTCRtpSender(e){return kt(this,void 0,void 0,(function*(){if(!this.publisher)throw new Bn("publisher is closed");return this.publisher.addTrack(e)}))}attemptReconnect(t){var i,n,r;return kt(this,void 0,void 0,(function*(){if(!this._isClosed&&!this.attemptingReconnect){(null===(i=this.clientConfiguration)||void 0===i?void 0:i.resumeConnection)!==Ue.DISABLED&&"closed"!==(null!==(r=null===(n=this.primaryTransport)||void 0===n?void 0:n.getSignallingState())&&void 0!==r?r:"closed")||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let i=!0;t instanceof Bn?(a.debug("received unrecoverable error",{error:t}),i=!1):t instanceof Hs||(this.fullReconnectOnNext=!0),i?this.handleDisconnect("reconnect",Fe.RR_UNKNOWN):(a.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){a.warn("encountered error in reconnect policy",{error:e})}return null}restartConnection(t){var i,n,r;return kt(this,void 0,void 0,(function*(){try{if(!this.url||!this.token)throw new Bn("could not reconnect, url or token not saved");let n;a.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Restarting),this.client.isConnected&&(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw a.warn("attempted connection restart, without signal options present"),new Hs;n=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof On&&0===e.reason)throw new Bn("could not reconnect, token might be expired");throw new Hs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,n),yield this.waitForPCReconnected(),null===(i=this.regionUrlProvider)||void 0===i||i.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(r=this.regionUrlProvider)||void 0===r||r.resetAttempts(),e}}))}resumeConnection(t){var i;return kt(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new Bn("could not reconnect, url or token not saved");if(!this.publisher||!this.subscriber)throw new Bn("publisher and subscriber connections unset");a.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks();const e=yield this.client.reconnect(this.url,this.token,this.participantSid,t);if(e){const t=this.makeRTCConfiguration(e);this.publisher.setConfiguration(t),this.subscriber.setConfiguration(t)}}catch(e){let t="";if(e instanceof Error&&(t=e.message),e instanceof On&&0===e.reason)throw new Bn("could not reconnect, token might be expired");throw new Hs(t)}if(this.emit(e.EngineEvent.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.subscriber.restartingIce=!0,this.hasPublished&&(yield this.publisher.createAndSendOffer({iceRestart:!0})),yield this.waitForPCReconnected(),this.client.setReconnected(),"open"===(null===(i=this.reliableDC)||void 0===i?void 0:i.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(t,i){return kt(this,void 0,void 0,(function*(){if(this.pcState!==Ks.Connected){if(this.pcState!==Ks.New)throw new Bn("Expected peer connection to be new on initial connection");return new Promise(((n,r)=>{const s=()=>{a.warn("closing engine"),Jn.clearTimeout(c),r(new On("room connection has been cancelled",3))};(null==i?void 0:i.signal.aborted)&&s(),null==i||i.signal.addEventListener("abort",s);const o=()=>{Jn.clearTimeout(c),null==i||i.signal.removeEventListener("abort",s),n()},c=Jn.setTimeout((()=>{this.off(e.EngineEvent.Connected,o),r(new On("could not establish pc connection"))}),null!=t?t:this.peerConnectionTimeout);this.once(e.EngineEvent.Connected,o)}))}}))}waitForPCReconnected(){var e,t;return kt(this,void 0,void 0,(function*(){const i=Date.now();let n=i;for(this.pcState=Ks.Reconnecting,a.debug("waiting for peer connection to reconnect");n-i<this.peerConnectionTimeout&&void 0!==this.primaryTransport;){if(n-i>2e3&&"connected"===(null===(e=this.primaryTransport)||void 0===e?void 0:e.getConnectionState())&&(!this.hasPublished||"connected"===(null===(t=this.publisher)||void 0===t?void 0:t.getConnectionState()))&&(this.pcState=Ks.Connected),this.pcState===Ks.Connected)return;yield vr(100),n=Date.now()}throw new On("could not establish PC connection")}))}sendDataPacket(e,t){return kt(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)}))}ensureDataTransportConnected(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;var i,n,r;return kt(this,void 0,void 0,(function*(){const s=t?this.subscriber:this.publisher,o=t?"Subscriber":"Publisher";if(!s)throw new On("".concat(o," connection not set"));t||(null===(i=this.publisher)||void 0===i?void 0:i.isICEConnected)||"checking"===(null===(n=this.publisher)||void 0===n?void 0:n.getICEConnectionState())||this.negotiate();const a=this.dataChannelForKind(e,t);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+this.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(r=this.dataChannelForKind(e,t))||void 0===r?void 0:r.readyState))return;yield vr(50)}throw new On("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()))}))}ensurePublisherConnected(e){return kt(this,void 0,void 0,(function*(){yield this.ensureDataTransportConnected(e,!1)}))}verifyTransport(){if(!this.primaryTransport)return!1;if("closed"===this.primaryTransport.getConnectionState()||"failed"===this.primaryTransport.getConnectionState())return!1;if(this.hasPublished&&this.subscriberPrimary){if(!this.publisher)return!1;if("closed"===this.publisher.getConnectionState()||"failed"===this.publisher.getConnectionState())return!1}return!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return new Promise(((t,i)=>{if(!this.publisher)return void i(new Fn("publisher is not defined"));this.hasPublished=!0;const n=()=>{a.debug("engine disconnected while negotiation was ongoing"),s(),t()};this.isClosed&&i("cannot negotiate on closed engine"),this.on(e.EngineEvent.Closing,n);const r=setTimeout((()=>{i("negotiation timed out"),this.handleDisconnect("negotiation",Fe.RR_SIGNAL_DISCONNECTED)}),this.peerConnectionTimeout),s=()=>{clearTimeout(r),this.off(e.EngineEvent.Closing,n)};this.publisher.once(Ls,(()=>{var e;null===(e=this.publisher)||void 0===e||e.once(Ns,(()=>{s(),t()}))})),this.publisher.once(As,(t=>{const i=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();var n;n=t,Qn.includes(n)&&i.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,i)})),this.publisher.negotiate((e=>{s(),i(e),e instanceof Fn&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Fe.RR_UNKNOWN)}))}))}dataChannelForKind(t,i){if(i){if(t===e.DataPacket_Kind.LOSSY)return this.lossyDCSub;if(t===e.DataPacket_Kind.RELIABLE)return this.reliableDCSub}else{if(t===e.DataPacket_Kind.LOSSY)return this.lossyDC;if(t===e.DataPacket_Kind.RELIABLE)return this.reliableDC}}failNext(){this.shouldFailNext=!0}clearReconnectTimeout(){this.reconnectTimeout&&Jn.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Rr()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Rr()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Hs extends Error{}class Gs{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 Dr(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return kt(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),a.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return kt(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 On("Could not fetch region settings: ".concat(t.statusText),401===t.status?0:void 0,t.status)}))}}const zs=2e3;function Qs(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 Ys extends fs{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,or.Kind.Audio,t,i),this.stopOnMute=!1,this.monitorSender=()=>kt(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void a.error("could not get audio sender stats",{error:e})}e&&this.prevStats&&(this._currentBitrate=Qs(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.checkForSilence()}setDeviceId(e){return kt(this,void 0,void 0,(function*(){return this._constraints.deviceId===e||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Hr(e)===this.mediaStreamTrack.getSettings().deviceId)}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return kt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source===or.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(a.debug("stopping mic track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return kt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Hr(this._constraints.deviceId);return this.source!==or.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(a.debug("reacquiring mic track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return kt(this,void 0,void 0,(function*(){let t;if(e){const i=lr({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 kt(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){Rr()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),zs)))}setProcessor(e){var t;return kt(this,void 0,void 0,(function*(){const i=yield this.processorLock.lock();try{if(!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");if(this.processor&&(yield this.stopProcessor()),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};a.debug("setting up audio processor ".concat(e.name)),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))}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){var e;return kt(this,void 0,void 0,(function*(){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 kt(this,void 0,void 0,(function*(){const t=yield function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return kt(this,void 0,void 0,(function*(){const i=hr();if(i){const n=i.createAnalyser();n.fftSize=2048;const r=n.frequencyBinCount,s=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield vr(t),n.getByteTimeDomainData(s);const o=s.some((e=>128!==e&&0!==e));return i.close(),!o}return!1}))}(this);return t&&(this.isMuted||a.warn("silence detected on local audio track"),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}function Xs(e,t){switch(e.kind){case"audio":return new Ys(e,t,!1);case"video":return new lo(e,t,!1);default:throw new xn("unsupported track type: ".concat(e.kind))}}const Zs=Object.values(Zn),$s=Object.values($n),eo=Object.values(er),to=[Zn.h180,Zn.h360],io=[$n.h180,$n.h360],no=e=>[{scaleResolutionDownBy:2,fps:3}].map((t=>{var i;return new Gn(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/t.fps)))),t.fps,e.encoding.priority)})),ro=["q","h","f"];function so(e,t,i,n){var r,s;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const c=null==n?void 0:n.simulcast,d=null==n?void 0:n.scalabilityMode,u=null==n?void 0:n.videoCodec;if(!o&&!c&&!d||!t||!i)return[{}];o||(o=function(e,t,i,n){const r=function(e,t,i){if(e)return eo;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return Zs;return $s}(e,t,i);let{encoding:s}=r[0];const o=Math.max(t,i);for(let e=0;e<r.length;e+=1){const t=r[e];if(s=t.encoding,t.width>=o)break}if(n)switch(n){case"av1":s=Object.assign({},s),s.maxBitrate=.7*s.maxBitrate;break;case"vp9":s=Object.assign({},s),s.maxBitrate=.85*s.maxBitrate}return s}(e,t,i,u),a.debug("using video encoding",o));const l=new Gn(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(d&&Tr(u)){a.debug("using svc with scalabilityMode ".concat(d));const e=new uo(d),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));for(let i=0;i<e.spatial;i+=1)t.push({rid:ro[2-i],maxBitrate:o.maxBitrate/Math.pow(3,i),maxFramerate:l.encoding.maxFramerate});return t[0].scalabilityMode=d,a.debug("encodings",t),t}if(!c)return[o];let h,p=[];if(p=e?null!==(r=co(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==r?r:oo(e,l):null!==(s=co(null==n?void 0:n.videoSimulcastLayers))&&void 0!==s?s:oo(e,l),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return ao(t,i,[e,h,l]);if(n>=480)return ao(t,i,[e,l])}return ao(t,i,[l])}function oo(e,t){if(e)return no(t);const{width:i,height:n}=t,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?to:io}function ao(e,t,i){const n=[];if(i.forEach(((i,r)=>{if(r>=ro.length)return;const s=Math.min(e,t),o={rid:ro[r],scaleResolutionDownBy:Math.max(1,s/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate};i.encoding.maxFramerate&&(o.maxFramerate=i.encoding.maxFramerate);const a=Er()||0===r;i.encoding.priority&&a&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),n.push(o)})),Ir()&&"ios"===Lr()){let e;n.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;n.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,a.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),a.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return n}function co(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 uo{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 lo extends fs{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,or.Kind.Video,t,i),this.simulcastCodecs=new Map,this.monitorSender=()=>kt(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void a.error("could not get audio sender stats",{error:e})}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const r=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=Qs(t,r)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Wr}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Rr())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()}),zs))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});var t,i,n,r,s;return kt(this,void 0,void 0,(function*(){yield e.pauseUpstream.call(this);try{for(var o,a=!0,c=Tt(this.simulcastCodecs.values());o=yield c.next(),!(t=o.done);a=!0){r=o.value,a=!1;const e=r;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(null)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});var t,i,n,r,s;return kt(this,void 0,void 0,(function*(){yield e.resumeUpstream.call(this);try{for(var o,a=!0,c=Tt(this.simulcastCodecs.values());o=yield c.next(),!(t=o.done);a=!0){r=o.value,a=!1;const e=r;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(e.mediaStreamTrack)}}catch(e){i={error:e}}finally{try{a||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 kt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==or.Source.Camera||this.isUserProvided||(a.debug("stopping camera track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return kt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==or.Source.Camera||this.isUserProvided||(a.debug("reacquiring camera track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){var e;return kt(this,void 0,void 0,(function*(){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 r={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,framesSent:e.framesSent,timestamp:e.timestamp,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges},s=i.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.roundTripTime),t.push(r)}})),t}))}setPublishingQuality(t){const i=[];for(let n=e.VideoQuality.LOW;n<=e.VideoQuality.HIGH;n+=1)i.push(new kn({quality:n,enabled:n<=t}));a.debug("setting publishing quality. max quality ".concat(t)),this.setPublishingLayers(i)}setDeviceId(e){return kt(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Hr(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||Hr(e)===this._mediaStreamTrack.getSettings().deviceId)}))}restartTrack(e){var t,i,n,r;return kt(this,void 0,void 0,(function*(){let s;if(e){const t=lr({video:e});"boolean"!=typeof t.video&&(s=t.video)}yield this.restart(s);try{for(var o,a=!0,c=Tt(this.simulcastCodecs.values());o=yield c.next(),!(t=o.done);a=!0){r=o.value,a=!1;const e=r;e.sender&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}setProcessor(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});var n,r,s,o,a,c;return kt(this,void 0,void 0,(function*(){if(yield i.setProcessor.call(this,e,t),null===(a=this.processor)||void 0===a?void 0:a.processedTrack)try{for(var d,u=!0,l=Tt(this.simulcastCodecs.values());d=yield l.next(),!(n=d.done);u=!0){o=d.value,u=!1;const e=o;yield null===(c=e.sender)||void 0===c?void 0:c.replaceTrack(this.processor.processedTrack)}}catch(e){r={error:e}}finally{try{u||n||!(s=l.return)||(yield s.call(l))}finally{if(r)throw r.error}}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))throw new Error("".concat(e," already added"));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){var t,i,n,r,s,o,c;return kt(this,void 0,void 0,(function*(){if(a.debug("setting publishing codecs",{codecs:e,currentCodec:this.codec}),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=Tt(e);n=yield i.next(),!(r=n.done);t=!0){c=n.value,t=!1;const e=c;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(a.debug("try setPublishingCodec for ".concat(e.codec),t),t&&t.sender)t.encodings&&(a.debug("try setPublishingLayersForSender ".concat(e.codec)),yield ho(t.sender,t.encodings,e.qualities,this.senderLock));else for(const t of e.qualities)if(t.enabled){d.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(e){s={error:e}}finally{try{t||r||!(o=i.return)||(yield o.call(i))}finally{if(s)throw s.error}}return d}))}setPublishingLayers(e){return kt(this,void 0,void 0,(function*(){a.debug("setting publishing layers",e),this.sender&&this.encodings&&(yield ho(this.sender,this.encodings,e,this.senderLock))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return kt(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Pr()&&this.isInBackground&&this.source===or.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function ho(e,t,i,n){return kt(this,void 0,void 0,(function*(){const r=yield n.lock();a.debug("setPublishingLayersForSender",{sender:e,qualities:i,senderEncodings:t});try{const n=e.getParameters(),{encodings:r}=n;if(!r)return;if(r.length!==t.length)return void a.warn("cannot set publishing layers, encodings mismatch");let s=!1;!1&&r[0].scalabilityMode||r.forEach(((e,n)=>{var r;let o=null!==(r=e.rid)&&void 0!==r?r:"";""===o&&(o="q");const c=po(o),d=i.find((e=>e.quality===c));d&&e.active!==d.enabled&&(s=!0,e.active=d.enabled,a.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled")),Er()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),s&&(n.encodings=r,a.debug("setting encodings",n.encodings),yield e.setParameters(n))}finally{r()}}))}function po(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function mo(t,i,n,r){if(!n)return[new it({quality:e.VideoQuality.HIGH,width:t,height:i,bitrate:0,ssrc:0})];if(r){const r=n[0].scalabilityMode,s=new uo(r),o=[];for(let r=0;r<s.spatial;r+=1)o.push(new it({quality:e.VideoQuality.HIGH-r,width:Math.ceil(t/Math.pow(2,r)),height:Math.ceil(i/Math.pow(2,r)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(3,r)):0,ssrc:0}));return o}return n.map((e=>{var n,r,s;const o=null!==(n=e.scaleResolutionDownBy)&&void 0!==n?n:1;let a=po(null!==(r=e.rid)&&void 0!==r?r:"");return new it({quality:a,width:Math.ceil(t/o),height:Math.ceil(i/o),bitrate:null!==(s=e.maxBitrate)&&void 0!==s?s:0,ssrc:0})}))}class fo extends or{constructor(e,t,i,n){super(e,i),this.sid=t,this.receiver=n}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const i=n=>{n.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",i),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",i)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){var e;return kt(this,void 0,void 0,(function*(){if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),zs))}}class vo extends fo{constructor(e,t,i,n,r){super(e,t,or.Kind.Audio,i),this.monitorReceiver=()=>kt(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=Qs(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.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;Ir()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ir())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return kt(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Sr(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.elementVolume&&(e.volume=this.elementVolume),this.sinkId&&Sr(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(a.debug("using audio context mapping"),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),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(t,i){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(i.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{n.connect(e),n=e})),this.gainNode=t.createGain(),n.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}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 kt(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",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 go extends fo{constructor(e,t,i,n){super(e,t,or.Kind.Video,i),this.elementInfos=[],this.monitorReceiver=()=>kt(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=Qs(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=hs((()=>{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?cr(this._mediaStreamTrack,t):ar(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 yo(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()):a.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void a.warn("stopObservingElementInfo ignored");const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.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 e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return kt(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:"video",framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation})})),e}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return kt(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var t,i;const n=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),r=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),o=this.elementInfos.some((e=>e.visible))&&!r||s;this.lastVisible!==o&&(!o&&Date.now()-n<100?Jn.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(e.TrackEvent.VisibilityChanged,o,this)))}updateDimensions(){var t,i;let n=0,r=0;const s=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*s,i=e.height()*s;t+i>n+r&&(n=t,r=i)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===n&&(null===(i=this.lastDimensions)||void 0===i?void 0:i.height)===r||(this.lastDimensions={width:n,height:r},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return Nr();if(!t){return Nr()>2?2:1}return t}}class yo{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.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e;this.isPiP=!0,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=!1,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:ko(e),this.isPiP=Rr()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=ko(this.element),this.isPiP=document.pictureInPictureElement===this.element,this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Fr().observe(this.element),Ur().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=Fr())||void 0===e||e.unobserve(this.element),null===(t=Ur())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function ko(e){let t=e.offsetTop,i=e.offsetLeft;const n=e.offsetWidth,r=e.offsetHeight,{hidden:s}=e,{opacity:o,display:a}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+r>window.pageYOffset&&i+n>window.pageXOffset&&!s&&(""===o||parseFloat(o)>0)&&"none"!==a}class bo extends Bt.EventEmitter{constructor(t,i,n){super(),this.metadataMuted=!1,this.encryption=Qe.NONE,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.setMaxListeners(100),this.kind=t,this.trackSid=i,this.trackName=n,this.source=or.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==Qe.NONE}get audioTrack(){if(this.track instanceof Ys||this.track instanceof vo)return this.track}get videoTrack(){if(this.track instanceof lo||this.track instanceof go)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=or.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===or.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,a.debug("update publication info",{info:e})}}!function(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(bo||(bo={}));class To extends bo{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,i,n){super(t,i.sid,i.name),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.updateInfo(i),this.setTrack(n)}setTrack(t){this.track&&this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),super.setTrack(t),t&&t.on(e.TrackEvent.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){var e;return kt(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){var e;return kt(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){var e;return kt(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){var e;return kt(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}}e.ConnectionQuality=void 0,function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Unknown="unknown"}(e.ConnectionQuality||(e.ConnectionQuality={}));class So extends Bt.EventEmitter{get isEncrypted(){return this.tracks.size>0&&Array.from(this.tracks.values()).every((e=>e.isEncrypted))}constructor(t,i,n,r){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.setMaxListeners(100),this.sid=t,this.identity=i,this.name=n,this.metadata=r,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){for(const[,t]of this.tracks)if(t.source===e)return t}getTrackByName(e){for(const[,t]of this.tracks)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrack(or.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrack(or.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrack(or.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),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,a.trace("update participant info",{info:e}),!0)}_setMetadata(t){const i=this.metadata!==t,n=this.metadata;this.metadata=t,i&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,n)}_setName(t){const i=this.name!==t;this.name=t,i&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}setPermissions(t){var i,n,r,s,o;const a=this.permissions,c=t.canPublish!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublish)||t.canSubscribe!==(null===(n=this.permissions)||void 0===n?void 0:n.canSubscribe)||t.canPublishData!==(null===(r=this.permissions)||void 0===r?void 0:r.canPublishData)||t.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||t.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}));return this.permissions=t,c&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,a),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const i=this._connectionQuality;this._connectionQuality=function(t){switch(t){case xe.EXCELLENT:return e.ConnectionQuality.Excellent;case xe.GOOD:return e.ConnectionQuality.Good;case xe.POOR:return e.ConnectionQuality.Poor;default:return e.ConnectionQuality.Unknown}}(t),i!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach((t=>(t.track instanceof vo||t.track instanceof Ys)&&t.track.setAudioContext(e)))}addTrackPublication(t){t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const i=t;switch(i.track&&(i.track.sid=t.trackSid),this.tracks.set(t.trackSid,t),t.kind){case or.Kind.Audio:this.audioTracks.set(t.trackSid,t);break;case or.Kind.Video:this.videoTracks.set(t.trackSid,t)}}}class wo extends bo{constructor(t,i,n){super(t,i.sid,i.name),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=e.VideoQuality.HIGH,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},this.handleVisibilityChange=e=>{a.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),{trackSid:this.trackSid}),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{a.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),{trackSid:this.trackSid}),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(i)}setSubscribed(t){const i=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const r=new an({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new at({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(i),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return!1===this.subscribed?bo.SubscriptionStatus.Unsubscribed:super.isSubscribed?bo.SubscriptionStatus.Subscribed:bo.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?bo.PermissionStatus.Allowed:bo.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}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||(this.track instanceof go&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof go&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(t){const i=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==t&&(r&&(r.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),r.off(e.TrackEvent.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,r)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(i))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const i=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):i!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const i=this.subscriptionStatus;t!==i&&this.emit(e.TrackEvent.SubscriptionStatusChanged,i,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return this.kind===or.Kind.Video&&this.isAdaptiveStream?(a.warn("adaptive stream is enabled, cannot change video track settings",{trackSid:this.trackSid}),!1):!!this.isDesired||(a.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof go&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new cn({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(t.width=Math.ceil(this.videoDimensions.width),t.height=Math.ceil(this.videoDimensions.height)):void 0!==this.currentVideoQuality?t.quality=this.currentVideoQuality:t.quality=e.VideoQuality.HIGH,this.emit(e.TrackEvent.UpdateSettings,t)}}class Eo extends So{static fromParticipantInfo(e,t){return new Eo(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,i,n,r){super(t,i||"",n,r),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{a.debug("send update settings",e),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,i)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,i)})),t.on(e.TrackEvent.Subscribed,(i=>{this.emit(e.ParticipantEvent.TrackSubscribed,i,t)})),t.on(e.TrackEvent.Unsubscribed,(i=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,i,t)})),t.on(e.TrackEvent.SubscriptionFailed,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,i)}))}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:or.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrack(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:or.Source.Microphone;const t=this.getTrack(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,i,n,r,s,o){let c=this.getTrackPublication(i);if(c||i.startsWith("TR")||this.tracks.forEach((e=>{c||t.kind!==e.kind.toString()||(c=e)})),!c)return 0===o?(a.error("could not find published track",{participant:this.sid,trackSid:i}),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i)):(void 0===o&&(o=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,i,n,r,s,o-1)}),150));if("ended"===t.readyState)return a.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:i}),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i);let d;return d="video"===t.kind?new go(t,i,r,s):new vo(t,i,r,this.audioContext,this.audioOutput),d.source=c.source,d.isMuted=c.isMuted,d.setMediaStream(n),d.start(),c.setTrack(d),this.volumeMap.has(c.source)&&d instanceof vo&&d.setVolume(this.volumeMap.get(c.source)),c}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const i=new Map,n=new Map;return t.tracks.forEach((e=>{var r;let s=this.getTrackPublication(e.sid);if(s)s.updateInfo(e);else{const i=or.kindFromProto(e.type);if(!i)return;s=new wo(i,e,null===(r=this.signalClient.connectOptions)||void 0===r?void 0:r.autoSubscribe),s.updateInfo(e),n.set(e.sid,s);const o=Array.from(this.tracks.values()).find((e=>e.source===(null==s?void 0:s.source)));o&&s.source!==or.Source.Unknown&&a.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),{oldTrack:o,newTrack:s,participant:this,participantInfo:t}),this.addTrackPublication(s)}i.set(e.sid,s)})),this.tracks.forEach((e=>{i.has(e.trackSid)||(a.trace("detected removed track on remote participant, unpublishing",{publication:e,participantSid:this.sid}),this.unpublishTrack(e.trackSid,!0))})),n.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,i){const n=this.tracks.get(t);if(!n)return;const{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.tracks.delete(t),n.kind){case or.Kind.Audio:this.audioTracks.delete(t);break;case or.Kind.Video:this.videoTracks.delete(t)}i&&this.emit(e.ParticipantEvent.TrackUnpublished,n)}setAudioOutput(e){return kt(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTracks.forEach((i=>{var n;i.track instanceof vo&&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 a.trace("participant event",{participant:this.sid,event:e,args:i}),super.emit(e,...i)}}class Co extends So{constructor(e,t,i,n){super(e,t),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Qe.NONE,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Kr)},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=>a.warn(e))),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.updateTrackSubscriptionPermissions=()=>{a.debug("updating track subscription permissions",{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 Sn({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):a.error("could not update mute status for unpublished track",e)},this.onTrackUpstreamPaused=e=>{a.debug("upstream paused"),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{a.debug("upstream resumed"),this.onTrackMuted(e,e.isMuted)},this.handleSubscribedQualityUpdate=e=>kt(this,void 0,void 0,(function*(){var t,i,n,r,s,o;if(!(null===(s=this.roomOptions)||void 0===s?void 0:s.dynacast))return;const c=this.videoTracks.get(e.trackSid);if(c)if(e.subscribedCodecs.length>0){if(!c.videoTrack)return;const s=yield c.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var d,u=!0,l=Tt(s);!(t=(d=yield l.next()).done);u=!0){r=d.value,u=!1;const e=r;Yn(e)&&(a.debug("publish ".concat(e," for ").concat(c.videoTrack.sid)),yield this.publishAdditionalCodecForTrack(c.videoTrack,e,c.options))}}catch(e){i={error:e}}finally{try{u||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(o=c.videoTrack)||void 0===o?void 0:o.setPublishingLayers(e.subscribedQualities));else a.warn("received subscribed quality update for unknown track",{method:"handleSubscribedQualityUpdate",sid:e.trackSid})})),this.handleLocalTrackUnpublished=e=>{const t=this.tracks.get(e.trackSid);t?this.unpublishTrack(t.track):a.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:e.trackSid})},this.handleTrackEnded=e=>kt(this,void 0,void 0,(function*(){if(e.source===or.Source.ScreenShare||e.source===or.Source.ScreenShareAudio)a.debug("unpublishing local track due to TrackEnded",{track:e.sid}),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(e instanceof Ys||e instanceof lo)try{if(Rr())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===or.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw a.warn("user has revoked access to ".concat(e.source)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(a.debug("track ended, attempting to use a different device"),yield e.restartTrack())}catch(t){a.warn("could not restart track, muting instead"),yield e.mute()}})),this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Qe.NONE}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setupEngine(t){this.engine=t,this.engine.client.onRemoteMuteChanged=(e,t)=>{const i=this.tracks.get(e);i&&i.track&&(t?i.mute():i.unmute())},this.engine.client.onSubscribedQualityUpdate=this.handleSubscribedQualityUpdate,this.engine.client.onLocalTrackUnpublished=this.handleLocalTrackUnpublished,this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.SignalRestarted,this.handleReconnected).on(e.EngineEvent.SignalResumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.Disconnected,this.handleDisconnected)}setMetadata(e){var t;this.engine.client.sendUpdateLocalMetadata(e,null!==(t=this.name)&&void 0!==t?t:"")}setName(e){var t;this.engine.client.sendUpdateLocalMetadata(null!==(t=this.metadata)&&void 0!==t?t:"",e)}setCameraEnabled(e,t,i){return this.setTrackEnabled(or.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(or.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(or.Source.ScreenShare,e,t,i)}setPermissions(t){const i=this.permissions,n=super.setPermissions(t);return n&&i&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,i),n}setE2EEEnabled(e){return kt(this,void 0,void 0,(function*(){this.encryptionType=e?Qe.GCM:Qe.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,i,n,r){var s,o;return kt(this,void 0,void 0,(function*(){a.debug("setTrackEnabled",{source:t,enabled:i});let c=this.getTrack(t);if(i)if(c)yield c.unmute();else{let i;if(this.pendingPublishing.has(t))return void a.info("skipping duplicate published source",{source:t});this.pendingPublishing.add(t);try{switch(t){case or.Source.Camera:i=yield this.createTracks({video:null===(s=n)||void 0===s||s});break;case or.Source.Microphone:i=yield this.createTracks({audio:null===(o=n)||void 0===o||o});break;case or.Source.ScreenShare:i=yield this.createScreenTracks(Object.assign({},n));break;default:throw new xn(t)}const e=[];for(const t of i)a.info("publishing track",{localTrack:t}),e.push(this.publishTrack(t,r));const d=yield Promise.all(e);[c]=d}catch(t){throw null==i||i.forEach((e=>{e.stop()})),t instanceof Error&&!(t instanceof xn)&&this.emit(e.ParticipantEvent.MediaDevicesError,t),t}finally{this.pendingPublishing.delete(t)}}else if(c&&c.track)if(t===or.Source.ScreenShare){c=yield this.unpublishTrack(c.track);const e=this.getTrack(or.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield c.mute();return c}))}enableCameraAndMicrophone(){return kt(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(or.Source.Camera)&&!this.pendingPublishing.has(or.Source.Microphone)){this.pendingPublishing.add(or.Source.Camera),this.pendingPublishing.add(or.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(or.Source.Camera),this.pendingPublishing.delete(or.Source.Microphone)}}}))}createTracks(e){var t,i;return kt(this,void 0,void 0,(function*(){const n=lr(dr(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults));let r;try{r=yield navigator.mediaDevices.getUserMedia(n)}catch(e){throw e instanceof Error&&(n.audio&&(this.microphoneError=e),n.video&&(this.cameraError=e)),e}return n.audio&&(this.microphoneError=void 0),n.video&&(this.cameraError=void 0),r.getTracks().map((t=>{const i="audio"===t.kind;let s;i?e.audio:e.video;const o=i?n.audio:n.video;"boolean"!=typeof o&&(s=o);const a=Xs(t,s);return a.kind===or.Kind.Video?a.source=or.Source.Camera:a.kind===or.Kind.Audio&&(a.source=or.Source.Microphone),a.mediaStream=r,a}))}))}createScreenTracks(e){return kt(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Mn("getDisplayMedia not supported");const t=pr(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new xn("no video track found");const r=new lo(n[0],void 0,!1);r.source=or.Source.ScreenShare;const s=[r];if(i.getAudioTracks().length>0){const e=new Ys(i.getAudioTracks()[0],void 0,!1,this.audioContext);e.source=or.Source.ScreenShareAudio,s.push(e)}return s}))}publishTrack(e,t){var i,n,r,s;return kt(this,void 0,void 0,(function*(){let o,c;if(yield null===(i=this.reconnectFuture)||void 0===i?void 0:i.promise,e instanceof fs&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)o=e.getConstraints();else{let t;switch(o=e.constraints,e.source){case or.Source.Microphone:t="audioinput";break;case or.Source.Camera:t="videoinput"}t&&this.activeDeviceMap.has(t)&&(o=Object.assign(Object.assign({},o),{deviceId:this.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Ys(e,o,!0,this.audioContext);break;case"video":e=new lo(e,o,!0);break;default:throw new xn("unsupported MediaStreamTrack kind ".concat(e.kind))}if(e instanceof Ys&&e.setAudioContext(this.audioContext),this.tracks.forEach((t=>{t.track&&t.track===e&&(c=t)})),c)return a.warn("track has already been published, skipping"),c;const d="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(n=null==t?void 0:t.forceStereo)&&void 0!==n?n:d;u&&(t||(t={}),void 0===t.dtx&&a.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),void 0===t.red&&a.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(r=t.dtx)&&void 0!==r||(t.dtx=!1),null!==(s=t.red)&&void 0!==s||(t.red=!1));const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);Cr()&&this.roomOptions.e2ee&&(a.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari"),l.simulcast=!1),l.source&&(e.source=l.source);const h=this.publish(e,l,u);this.pendingPublishPromises.set(e,h);try{return yield h}catch(e){throw e}finally{this.pendingPublishPromises.delete(e)}}))}publish(t,i,n){var r,s,o,c,d,u,l,h,p,m,f,v,g;return kt(this,void 0,void 0,(function*(){const y=Array.from(this.tracks.values()).find((e=>t instanceof fs&&e.source===t.source));if(y&&t.source!==or.Source.Unknown)try{throw Error("publishing a second track with the same source: ".concat(t.source))}catch(e){e instanceof Error&&a.warn(e.message,{oldTrack:y,newTrack:t,trace:e.stack})}i.stopMicTrackOnMute&&t instanceof Ys&&(t.stopOnMute=!0),t.source===or.Source.ScreenShare&&Er()&&(i.simulcast=!1),"av1"!==i.videoCodec||kr()||(i.videoCodec=void 0),"vp9"!==i.videoCodec||br()||(i.videoCodec=void 0),void 0===i.videoCodec&&(i.videoCodec="vp8");const k=i.videoCodec;t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed);const b=new Xi({cid:t.mediaStreamTrack.id,name:i.name,type:or.kindToProto(t.kind),muted:t.isMuted,source:or.sourceToProto(t.source),disableDtx:!(null===(r=i.dtx)||void 0===r||r),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(null===(s=i.red)||void 0===s||s),stream:null==i?void 0:i.stream});let T;if(t.kind===or.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(t){const i=null!==(c=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==c?c:Zn.h720.resolution;e={width:i.width,height:i.height},a.error("could not determine track dimensions, using defaults",e)}b.width=e.width,b.height=e.height,t instanceof lo&&(Tr(k)&&(t.source===or.Source.ScreenShare&&"vp9"===k&&(i.scalabilityMode="L1T3"),i.scalabilityMode=null!==(d=i.scalabilityMode)&&void 0!==d?d:"L3T3_KEY"),b.simulcastCodecs=[new Yi({codec:k,cid:t.mediaStreamTrack.id})],i.backupCodec&&k!==i.backupCodec.codec&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),b.simulcastCodecs.push(new Yi({codec:i.backupCodec.codec,cid:""})))),T=so(t.source===or.Source.ScreenShare,b.width,b.height,i),b.layers=mo(b.width,b.height,T,Tr(i.videoCodec))}else t.kind===or.Kind.Audio&&(T=[{maxBitrate:null!==(l=null===(u=i.audioPreset)||void 0===u?void 0:u.maxBitrate)&&void 0!==l?l:i.audioBitrate,priority:null!==(p=null===(h=i.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==p?p:"high",networkPriority:null!==(f=null===(m=i.audioPreset)||void 0===m?void 0:m.priority)&&void 0!==f?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Bn("cannot publish track when not connected");const S=yield this.engine.addTrack(b);let w;if(S.codecs.forEach((e=>{void 0===w&&(w=e.mimeType)})),w&&t.kind===or.Kind.Video){const e=mr(w);e!==k&&(a.debug("falling back to server selected codec",{codec:e}),i.videoCodec=e,T=so(t.source===or.Source.ScreenShare,b.width,b.height,i))}const E=new To(t.kind,S,t);if(E.options=i,t.sid=S.sid,!this.engine.publisher)throw new Bn("publisher is closed");if(a.debug("publishing ".concat(t.kind," with encodings"),{encodings:T,trackInfo:S}),t.sender=yield this.engine.createSender(t,i,T),T)if(Er()&&t.kind===or.Kind.Audio){let e;for(const i of this.engine.publisher.getTransceivers())if(i.sender===t.sender){e=i;break}e&&this.engine.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(v=T[0])||void 0===v?void 0:v.maxBitrate)?T[0].maxBitrate/1e3:0})}else t.codec&&Tr(t.codec)&&(null===(g=T[0])||void 0===g?void 0:g.maxBitrate)&&this.engine.publisher.setTrackCodecBitrate({cid:b.cid,codec:t.codec,maxbr:T[0].maxBitrate/1e3});return yield this.engine.negotiate(),t instanceof lo?t.startMonitor(this.engine.client):t instanceof Ys&&t.startMonitor(),this.addTrackPublication(E),this.emit(e.ParticipantEvent.LocalTrackPublished,E),E}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){var n;return kt(this,void 0,void 0,(function*(){let r;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(r=t)})),!r)throw new xn("track is not published");if(!(e instanceof lo))throw new xn("track is not a video track");const s=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,r,s,o;if(!i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&a.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const c=e.mediaStreamTrack.getSettings(),d=null!==(n=c.width)&&void 0!==n?n:null===(r=e.dimensions)||void 0===r?void 0:r.width,u=null!==(s=c.height)&&void 0!==s?s:null===(o=e.dimensions)||void 0===o?void 0:o.height;return so(e.source===or.Source.ScreenShare,d,u,i)}(e,t,s);if(!o)return void a.info("backup codec has been disabled, ignoring request to add additional codec for track");const c=e.addSimulcastTrack(t,o),d=new Xi({cid:c.mediaStreamTrack.id,type:or.kindToProto(e.kind),muted:e.isMuted,source:or.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=mo(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new Bn("cannot publish track when not connected");const u=yield this.engine.addTrack(d);yield this.engine.createSimulcastSender(e,c,s,o),yield this.engine.negotiate(),a.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:u})}))}unpublishTrack(t,i){var n,r;return kt(this,void 0,void 0,(function*(){const s=this.getPublicationForTrack(t);if(a.debug("unpublishing track",{track:t,method:"unpublishTrack"}),!s||!s.track)return void a.warn("track was not unpublished because no publication was found",{track:t,method:"unpublishTrack"});(t=s.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),void 0===i&&(i=null===(r=null===(n=this.roomOptions)||void 0===n?void 0:n.stopLocalTrackOnUnpublish)||void 0===r||r),i&&t.stop();let o=!1;const c=t.sender;if(t.sender=void 0,this.engine.publisher&&"closed"!==this.engine.publisher.getConnectionState()&&c)try{for(const e of this.engine.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),t instanceof lo){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(o=!0),e.sender=void 0);t.simulcastCodecs.clear()}}catch(e){a.warn("failed to unpublish track",{error:e,method:"unpublishTrack"})}switch(this.tracks.delete(s.trackSid),s.kind){case or.Kind.Audio:this.audioTracks.delete(s.trackSid);break;case or.Kind.Video:this.videoTracks.delete(s.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return kt(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof To))}))}republishAllTracks(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return kt(this,void 0,void 0,(function*(){const i=[];this.tracks.forEach((t=>{t.track&&(e&&(t.options=Object.assign(Object.assign({},t.options),e)),i.push(t))})),yield Promise.all(i.map((e=>kt(this,void 0,void 0,(function*(){const i=e.track;yield this.unpublishTrack(i,!1),t&&!i.isMuted&&(i instanceof Ys||i instanceof lo)&&!i.isUserProvided&&(a.debug("restarting existing track",{track:e.trackSid}),yield i.restartTrack()),yield this.publishTrack(i,e.options)})))))}))}publishData(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return kt(this,void 0,void 0,(function*(){const n=Array.isArray(i)?i:null==i?void 0:i.destination,r=[],s=Array.isArray(i)?void 0:i.topic;void 0!==n&&n.forEach((e=>{e instanceof Eo?r.push(e.sid):r.push(e)}));const o=new nt({kind:t,value:{case:"user",value:new ot({participantSid:this.sid,payload:e,destinationSids:r,topic:s})}});yield this.engine.sendDataPacket(o,t)}))}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isConnected&&this.updateTrackSubscriptionPermissions()}updateInfo(e){return e.sid===this.sid&&(!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.tracks.get(e.sid);if(n){const r=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;r!==e.muted&&(a.debug("updating server mute state after reconcile",{sid:e.sid,muted:r}),this.engine.client.sendMuteTrack(e.sid,r))}})),!0))}getPublicationForTrack(e){let t;return this.tracks.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(n instanceof Ys||n instanceof lo)&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}publishedTracksInfo(){const e=[];return this.tracks.forEach((t=>{void 0!==t.track&&e.push(new nn({cid:t.track.mediaStreamID,track:t.trackInfo}))})),e}dataChannelsInfo(){const t=[],i=(e,i)=>{void 0!==(null==e?void 0:e.id)&&null!==e.id&&t.push(new Pn({label:e.label,id:e.id,target:i}))};return i(this.engine.dataChannelForKind(e.DataPacket_Kind.LOSSY),qi.PUBLISHER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.RELIABLE),qi.PUBLISHER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.LOSSY,!0),qi.SUBSCRIBER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.RELIABLE,!0),qi.SUBSCRIBER),t}}var Po;e.ConnectionState=void 0,(Po=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Po.Connecting="connecting",Po.Connected="connected",Po.Reconnecting="reconnecting";const Ro=e.ConnectionState;class Io extends Bt.EventEmitter{constructor(t){var i,n;super(),i=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.connect=(t,i,n)=>kt(this,void 0,void 0,(function*(){var r;const s=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return a.info("already connected to room ".concat(this.name)),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.getServerUrl().toString())!==t&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Dr(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Gs(t,i):this.regionUrlProvider.updateToken(i),this.regionUrlProvider.fetchRegionSettings().catch((e=>{a.warn("could not fetch region settings",{error:e})})));const o=(e,r,c)=>kt(this,void 0,void 0,(function*(){var d;this.abortController&&this.abortController.abort();const u=new AbortController;this.abortController=u,null==s||s();try{yield this.attemptConnection(null!=c?c:t,i,n,u),this.abortController=void 0,e()}catch(t){if(this.regionUrlProvider&&t instanceof On&&3!==t.reason&&0!==t.reason){let i=null;try{i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(d=this.abortController)||void 0===d?void 0:d.signal)}catch(e){if(e instanceof On&&(401===e.status||3===e.reason))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void r(e)}i?(a.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i)),yield o(e,r,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),r(t))}else this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),r(t)}})),c=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Kr(((e,t)=>{o(e,t,c)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,r,s)=>kt(this,void 0,void 0,(function*(){const o=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,publishOnly:n.publishOnly,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},s.signal);let c=o.serverInfo;if(c||(c={version:o.serverVersion,region:o.serverRegion}),a.debug("connected to Livekit Server ".concat(Object.entries(c).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", "))),!o.serverVersion)throw new Un("unknown server version");return"0.15.1"===o.serverVersion&&this.options.dynacast&&(a.debug("disabling dynacast due to server version"),r.dynacast=!1),o})),this.applyJoinResponse=e=>{const t=e.participant;this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room),this.options.e2ee&&this.e2eeManager&&this.e2eeManager.setSifTrailer(e.sifTrailer)},this.attemptConnection=(t,i,n,r)=>kt(this,void 0,void 0,(function*(){var s,o;this.state===e.ConnectionState.Reconnecting?(a.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Js),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(t,i,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=new On("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof On&&(t.reason=e.reason,t.status=e.status),a.debug("error trying to establish signal connection",{error:e}),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new On("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}Rr()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Rr()&&(document.addEventListener("freeze",this.onPageLeave),null===(o=navigator.mediaDevices)||void 0===o||o.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return kt(i,void 0,void 0,(function*(){var i,n,r,s;const o=yield this.disconnectLock.lock();try{if(this.state===e.ConnectionState.Disconnected)return void a.debug("already disconnected");a.info("disconnect from room",{identity:this.localParticipant.identity}),this.state!==e.ConnectionState.Connecting&&this.state!==e.ConnectionState.Reconnecting||(a.warn("abort connection attempt"),null===(i=this.abortController)||void 0===i||i.abort(),null===(r=null===(n=this.connectFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,new On("Client initiated disconnect")),this.connectFuture=void 0),(null===(s=this.engine)||void 0===s?void 0:s.client.isConnected)&&(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(t,e.DisconnectReason.CLIENT_INITIATED),this.engine=void 0}finally{o()}}))},this.onPageLeave=()=>kt(this,void 0,void 0,(function*(){yield this.disconnect()})),this.handleRestarting=()=>{this.clearConnectionReconcile();for(const e of this.participants.values())this.handleParticipantDisconnected(e.sid,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=t=>kt(this,void 0,void 0,(function*(){a.debug("signal reconnected to server",{region:t.serverRegion}),this.cachedParticipantSids=[],this.applyJoinResponse(t);try{const e=[];this.localParticipant.tracks.forEach((t=>{t.track&&e.push(t)})),yield Promise.all(e.map((e=>kt(this,void 0,void 0,(function*(){const t=e.track;this.localParticipant.unpublishTrack(t,!1),t.isMuted||((t instanceof Ys||t instanceof lo)&&t.source!==or.Source.ScreenShare&&t.source!==or.Source.ScreenShareAudio&&!t.isUserProvided&&(a.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),a.debug("publishing new track",{track:e.trackSid}),yield this.localParticipant.publishTrack(t,e.options))})))))}catch(e){a.error("error trying to re-publish tracks after reconnection",{error:e})}try{yield this.engine.waitForRestarted(),a.debug("fully reconnected to server",{region:t.serverRegion})}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.participants.forEach((t=>{this.emit(e.RoomEvent.ParticipantConnected,t)}))})),this.handleParticipantUpdates=e=>{e.forEach((e=>{if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);const t=this.identityToSid.get(e.identity);t&&t!==e.sid&&this.handleParticipantDisconnected(t,this.participants.get(t));let i=this.participants.get(e.sid);const n=!i;e.state===ze.DISCONNECTED?this.handleParticipantDisconnected(e.sid,i):(i=this.getOrCreateParticipant(e.sid,e),n||i.updateInfo(e))}))},this.handleActiveSpeakersUpdate=t=>{const i=[],n={};t.forEach((e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),i.push(this.localParticipant);else{const t=this.participants.get(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),i.push(t))}})),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.participants.forEach((e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleSpeakersChanged=t=>{const i=new Map;this.activeSpeakers.forEach((e=>{i.set(e.sid,e)})),t.forEach((e=>{let t=this.participants.get(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?i.set(e.sid,t):i.delete(e.sid))}));const n=Array.from(i.values());n.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const i=this.participants.get(t.participantSid);if(!i)return;const n=i.getTrackPublication(t.trackSid);n&&n.track&&(n.track.streamState=or.streamStateFromProto(t.state),i.emit(e.ParticipantEvent.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,n,n.track.streamState,i))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.participants.get(e.participantSid);if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.participants.values()).find((t=>t.tracks.has(e.trackSid)));if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(t,i)=>{const n=this.participants.get(t.participantSid);this.emit(e.RoomEvent.DataReceived,t.payload,n,i,t.topic),null==n||n.emit(e.ParticipantEvent.DataReceived,t.payload,i)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{a.warn("could not playback audio",t),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>kt(this,void 0,void 0,(function*(){this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const i=this.roomInfo;this.roomInfo=t,i&&i.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==i?void 0:i.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.participants.get(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onLocalTrackPublished=t=>kt(this,void 0,void 0,(function*(){var i;if(this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),t.track instanceof Ys){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const n=yield null===(i=t.track)||void 0===i?void 0:i.getDeviceId(),r=(s=t.source)===or.Source.Microphone?"audioinput":s===or.Source.Camera?"videoinput":void 0;var s;r&&n&&n!==this.localParticipant.activeDeviceMap.get(r)&&(this.localParticipant.activeDeviceMap.set(r,n),this.emit(e.RoomEvent.ActiveDeviceChanged,r,n))})),this.onLocalTrackUnpublished=t=>{this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=t=>{this.emit(e.RoomEvent.MediaDevicesError,t)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.setMaxListeners(100),this.participants=new Map,this.cachedParticipantSids=[],this.identityToSid=new Map,this.options=Object.assign(Object.assign({},Fs),t),this.options.audioCaptureDefaults=Object.assign(Object.assign({},Us),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Bs),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},xs),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Wr,this.localParticipant=new Co("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Hr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Hr(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",Hr(this.options.audioOutput.deviceId)),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return kt(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 t;this.options.e2ee&&(this.e2eeManager=new vs(this.options.e2ee),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,i)=>{i instanceof Co&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,i)})),this.e2eeManager.on(e.EncryptionEvent.EncryptionError,(t=>this.emit(e.RoomEvent.EncryptionError,t))),null===(t=this.e2eeManager)||void 0===t||t.setup(this))}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}get sid(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.sid)&&void 0!==t?t:""}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 Ws(this.options),this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting),this.cachedParticipantSids=Array.from(this.participants.keys())})).on(e.EngineEvent.Resumed,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.updateSubscriptions();Array.from(this.participants.values()).filter((e=>!this.cachedParticipantSids.includes(e.sid))).forEach((t=>this.emit(e.RoomEvent.ParticipantConnected,t))),this.cachedParticipantSids=[]})).on(e.EngineEvent.SignalResumed,(()=>{this.state===e.ConnectionState.Reconnecting&&this.sendSyncState()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.DCBufferStatusChanged,((t,i)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,i)})),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 ms.getInstance().getDevices(e,t)}prepareConnection(t,i){return kt(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){a.debug("prepareConnection to ".concat(t));try{if(Dr(new URL(t))&&i){this.regionUrlProvider=new Gs(t,i);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=n,yield fetch(Gr(n),{method:"HEAD"}),a.debug("prepared connection to ".concat(n)))}else yield fetch(Gr(t),{method:"HEAD"})}catch(e){a.warn("could not prepare connection",{error:e})}}}))}getParticipantByIdentity(e){if(this.localParticipant.identity===e)return this.localParticipant;const t=this.identityToSid.get(e);return t?this.participants.get(t):void 0}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(t,i){return kt(this,void 0,void 0,(function*(){let n,r=()=>{};switch(t){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":n=new Rn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new Rn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new Rn({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new Rn({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":n=new Rn({scenario:{case:"switchCandidateProtocol",value:"force-tls"===t?2:1}}),r=()=>kt(this,void 0,void 0,(function*(){const t=this.engine.client.onLeave;t&&t(new dn({reason:e.DisconnectReason.CLIENT_INITIATED,canReconnect:!0}))}));break;case"subscriber-bandwidth":if(void 0===i||"number"!=typeof i)throw new Error("subscriber-bandwidth requires a number as argument");n=new Rn({scenario:{case:"subscriberBandwidth",value:BigInt(i)}})}n&&(this.engine.client.sendSimulateScenario(n),r())}))}startAudio(){return kt(this,void 0,void 0,(function*(){const t=[],i=qn();if(i&&"iOS"===i.os){const i="livekit-dummy-audio-el";let n=document.getElementById(i);if(!n){n=document.createElement("audio"),n.id=i,n.autoplay=!0,n.hidden=!0;const t=qr();t.enabled=!0;const r=new MediaStream([t]);n.srcObject=r,document.addEventListener("visibilitychange",(()=>{n&&(n.srcObject=document.hidden?null:r)})),document.body.append(n),this.once(e.RoomEvent.Disconnected,(()=>{null==n||n.remove()}))}t.push(n)}this.participants.forEach((e=>{e.audioTracks.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}))}get canPlaybackAudio(){return this.audioEnabled}getActiveAudioOutputDevice(){var e,t;return null!==(t=null===(e=this.options.audioOutput)||void 0===e?void 0:e.deviceId)&&void 0!==t?t:""}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,i){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var r,s,o;return kt(this,void 0,void 0,(function*(){let a=!1,c=!0;const d=n?{exact:i}:i;if("audioinput"===t){const e=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=d,a=e!==d;const t=Array.from(this.localParticipant.audioTracks.values()).filter((e=>e.source===or.Source.Microphone));try{c=(yield Promise.all(t.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(d)})))).every((e=>!0===e))}catch(t){throw this.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===t){const e=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=d,a=e!==d;const t=Array.from(this.localParticipant.videoTracks.values()).filter((e=>e.source===or.Source.Camera));try{c=(yield Promise.all(t.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(d)})))).every((e=>!0===e))}catch(t){throw this.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===t){if(!Sr()&&!this.options.expWebAudioMix||this.options.expWebAudioMix&&this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");null!==(r=(o=this.options).audioOutput)&&void 0!==r||(o.audioOutput={});const e=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=i,a=e!==d;try{this.options.expWebAudioMix?null===(s=this.audioContext)||void 0===s||s.setSinkId(i):yield Promise.all(Array.from(this.participants.values()).map((e=>e.setAudioOutput({deviceId:i}))))}catch(t){throw this.options.audioOutput.deviceId=e,t}}return a&&c&&(this.localParticipant.activeDeviceMap.set(t,i),this.emit(e.RoomEvent.ActiveDeviceChanged,t,i)),c}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.participants.clear(),this.maybeCreateEngine()}onTrackAdded(t,i,n){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const r=()=>{this.onTrackAdded(t,i,n),s()},s=()=>{this.off(e.RoomEvent.Reconnected,r),this.off(e.RoomEvent.Connected,r),this.off(e.RoomEvent.Disconnected,s)};return this.once(e.RoomEvent.Reconnected,r),this.once(e.RoomEvent.Connected,r),void this.once(e.RoomEvent.Disconnected,s)}if(this.state===e.ConnectionState.Disconnected)return void a.warn("skipping incoming track after Room disconnected");const r=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(i.id),s=r[0];let o=r[1],c=t.id;if(o&&o.startsWith("TR")&&(c=o),s===this.localParticipant.sid)return void a.warn("tried to create RemoteParticipant for local participant");const d=this.participants.get(s);if(!d)return void a.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s));let u;this.options.adaptiveStream&&(u="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),d.addSubscribedMediaTrack(t,c,i,n,u)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.state!==e.ConnectionState.Disconnected){this.regionUrl=void 0;try{this.participants.forEach((e=>{e.tracks.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.tracks.forEach((e=>{var i,n;e.track&&this.localParticipant.unpublishTrack(e.track,t),t&&(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop())})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.tracks.clear(),this.localParticipant.videoTracks.clear(),this.localParticipant.audioTracks.clear(),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.expWebAudioMix&&(this.audioContext.close(),this.audioContext=void 0),Rr()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=navigator.mediaDevices)||void 0===n||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,i)}}}handleParticipantDisconnected(t,i){this.participants.delete(t),i&&(this.identityToSid.delete(i.identity),i.tracks.forEach((e=>{i.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,i))}acquireAudioContext(){var t,i;return kt(this,void 0,void 0,(function*(){if("boolean"!=typeof this.options.expWebAudioMix&&this.options.expWebAudioMix.audioContext?this.audioContext=this.options.expWebAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(t=hr())&&void 0!==t?t:void 0),this.audioContext&&"suspended"===this.audioContext.state)try{yield this.audioContext.resume()}catch(e){a.warn(e)}this.options.expWebAudioMix&&this.participants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext);const n="running"===(null===(i=this.audioContext)||void 0===i?void 0:i.state);n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,n))}))}createParticipant(e,t){let i;return i=t?Eo.fromParticipantInfo(this.engine.client,t):new Eo(this.engine.client,e,"",void 0,void 0),this.options.expWebAudioMix&&i.setAudioContext(this.audioContext),i}getOrCreateParticipant(t,i){if(this.participants.has(t))return this.participants.get(t);const n=this.createParticipant(t,i);return this.participants.set(t,n),this.identityToSid.set(i.identity,i.sid),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,n),n.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,n)})).on(e.ParticipantEvent.TrackSubscribed,((t,i)=>{t.kind===or.Kind.Audio&&(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(e.RoomEvent.TrackSubscribed,t,i,n)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,n)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,i)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,(t=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,n)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,n)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,n)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,n)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,n)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,n)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,i)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,i,n)})),i&&n.updateInfo(i),n}sendSyncState(){var e,t,i,n;const r=null===(e=this.engine.subscriber)||void 0===e?void 0:e.getLocalDescription(),s=null===(t=this.engine.subscriber)||void 0===t?void 0:t.getRemoteDescription();if(!r)return;const o=null===(n=null===(i=this.connOptions)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=new Array;this.participants.forEach((e=>{e.tracks.forEach((e=>{e.isDesired!==o&&a.push(e.trackSid)}))})),this.engine.client.sendSyncState(new Cn({answer:$r({sdp:r.sdp,type:r.type}),offer:s?$r({sdp:s.sdp,type:s.type}):void 0,subscription:new an({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:this.localParticipant.publishedTracksInfo(),dataChannels:this.localParticipant.dataChannelsInfo()}))}updateSubscriptions(){for(const e of this.participants.values())for(const t of e.videoTracks.values())t.isSubscribed&&t instanceof wo&&t.emitTrackUpdate()}registerConnectionReconcile(){this.clearConnectionReconcile();let t=0;this.connectionReconcileInterval=Jn.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?t=0:(t++,a.warn("detected connection state mismatch",{numFailures:t}),t>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e.DisconnectReason.STATE_MISMATCH)))}),2e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Jn.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitWhenConnected(t){if(this.state===e.ConnectionState.Connected){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this.emit(t,...n)}return!1}simulateParticipants(t){var i,n;return kt(this,void 0,void 0,(function*(){const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new qe({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:M.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Ge({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected),r.video){const t=new To(or.Kind.Video,new tt({source:Oe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ae.AUDIO,name:"video-dummy"}),new lo(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Vr(null!==(i=160*s.aspectRatios[0])&&void 0!==i?i:1,160,!0,!0)));this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(r.audio){const t=new To(or.Kind.Audio,new tt({source:Oe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ae.AUDIO}),new Ys(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:qr()));this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<s.count-1;e+=1){let t=new Ge({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:ze.ACTIVE,tracks:[],joinedAt:M.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=Vr(null!==(n=160*s.aspectRatios[e%s.aspectRatios.length])&&void 0!==n?n:1,160,!1,!0),o=new tt({source:Oe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Ae.AUDIO});i.addSubscribedMediaTrack(r,o.sid,new MediaStream([r])),t.tracks=[...t.tracks,o]}if(s.audio){const e=qr(),n=new tt({source:Oe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Ae.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e])),t.tracks=[...t.tracks,n]}i.updateInfo(t)}}))}emit(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return t!==e.RoomEvent.ActiveSpeakersChanged&&a.debug("room event ".concat(t),{event:t,args:n}),super.emit(t,...n)}}var Do;!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(Do||(Do={}));class _o extends Bt.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=Do.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Io(i.roomOptions),this.connectOptions=i.connectOptions,i.errorsAsWarnings&&(this.errorsAsWarnings=i.errorsAsWarnings)}run(e){return kt(this,void 0,void 0,(function*(){if(this.status!==Do.IDLE)throw Error("check is running already");this.setStatus(Do.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==Do.SKIPPED&&this.setStatus(this.isSuccess()?Do.SUCCESS:Do.FAILED),e&&e(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(){return kt(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(yield this.room.connect(this.url,this.token)),this.room}))}disconnect(){return kt(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(Do.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function Lo(e){var t,i;return kt(this,void 0,void 0,(function*(){null!=e||(e={}),null!==(t=e.audio)&&void 0!==t||(e.audio=!0),null!==(i=e.video)&&void 0!==i||(e.video=!0);const n=lr(dr(e,Us,Bs)),r=navigator.mediaDevices.getUserMedia(n);e.audio&&(ms.userMediaPromiseMap.set("audioinput",r),r.catch((()=>ms.userMediaPromiseMap.delete("audioinput")))),e.video&&(ms.userMediaPromiseMap.set("videoinput",r),r.catch((()=>ms.userMediaPromiseMap.delete("videoinput"))));const s=yield r;return s.getTracks().map((t=>{const i="audio"===t.kind;let r;i?e.audio:e.video;const o=i?n.audio:n.video;"boolean"!=typeof o&&(r=o),r?r.deviceId=t.getSettings().deviceId:r={deviceId:t.getSettings().deviceId};const a=Xs(t,r);return a.kind===or.Kind.Video?a.source=or.Source.Camera:a.kind===or.Kind.Audio&&(a.source=or.Source.Microphone),a.mediaStream=s,a}))}))}function No(e){return kt(this,void 0,void 0,(function*(){return(yield Lo({audio:!1,video:e}))[0]}))}function Ao(e){return kt(this,void 0,void 0,(function*(){return(yield Lo({audio:e,video:!1}))[0]}))}class Oo extends _o{get description(){return"Can publish audio"}perform(){var e;return kt(this,void 0,void 0,(function*(){const t=yield this.connect(),i=yield Ao();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let r=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"audio"===e.mediaType&&(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))}))}}class Mo extends _o{get description(){return"Can publish video"}perform(){var e;return kt(this,void 0,void 0,(function*(){const t=yield this.connect(),i=yield No();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let r=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"video"===e.mediaType&&(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))}))}}class xo extends _o{get description(){return"Resuming connection after interruption"}perform(){var t;return kt(this,void 0,void 0,(function*(){const i=yield this.connect();let n,r=!1,s=!1;const o=new Promise((e=>{setTimeout(e,5e3),n=e}));i.on(e.RoomEvent.Reconnecting,(()=>{r=!0})).on(e.RoomEvent.Reconnected,(()=>{s=!0,n(!0)})),null===(t=i.engine.client.ws)||void 0===t||t.close();const a=i.engine.client.onClose;if(a&&a(""),yield o,!r)throw new Error("Did not attempt to reconnect");if(!s||i.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class Uo extends _o{get description(){return"Can connect via TURN"}perform(){var e,t;return kt(this,void 0,void 0,(function*(){const i=new Xr,n=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,s=!1,o=!1;for(let e of n.iceServers)for(let t of e.urls)t.startsWith("turn:")?(s=!0,o=!0):t.startsWith("turns:")&&(s=!0,o=!0,r=!0),t.startsWith("stun:")&&(o=!0);o?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class Bo extends _o{get description(){return"Establishing WebRTC connection"}perform(){return kt(this,void 0,void 0,(function*(){let t=!1,i=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{const e=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(n,r)=>{if(n.candidate){const e=new RTCIceCandidate(n);let r="".concat(e.protocol," ").concat(e.address,":").concat(e.port," ").concat(e.type);e.address&&(!function(e){const t=e.split(".");if(4===t.length){if("10"===t[0])return!0;if("192"===t[0]&&"168"===t[1])return!0;if("172"===t[0]){const e=parseInt(t[1],10);if(e>=16&&e<=31)return!0}}return!1}(e.address)?"tcp"===e.protocol&&"passive"===e.tcpType?(t=!0,r+=" (passive)"):"udp"===e.protocol&&(i=!0):r+=" (private)"),this.appendMessage(r)}e&&e(n,r)},this.room.engine.subscriber&&(this.room.engine.subscriber.onIceCandidateError=e=>{e instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(e.errorCode," ").concat(e.errorText," ").concat(e.url))})}));try{yield this.connect(),a.info("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}t||this.appendWarning("Server is not configured for ICE/TCP"),i||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class Fo extends _o{get description(){return"Connecting to signal connection via WebSocket"}perform(){var e,t,i;return kt(this,void 0,void 0,(function*(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let n=new Xr;const r=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),(null===(e=r.serverInfo)||void 0===e?void 0:e.edition)===Xe.Cloud&&(null===(t=r.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(i=r.serverInfo)||void 0===i?void 0:i.region)),yield n.close()}))}}class Jo extends Bt.EventEmitter{constructor(e,t){super(),this.checkResults=new Map,this.url=e,this.token=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Do.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((e=>e.status!==Do.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return kt(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token),n=e=>{this.updateCheck(t,e)};i.on("update",n);const r=yield i.run();return i.off("update",n),r}))}checkWebsocket(){return kt(this,void 0,void 0,(function*(){return this.createAndRunCheck(Fo)}))}checkWebRTC(){return kt(this,void 0,void 0,(function*(){return this.createAndRunCheck(Bo)}))}checkTURN(){return kt(this,void 0,void 0,(function*(){return this.createAndRunCheck(Uo)}))}checkReconnect(){return kt(this,void 0,void 0,(function*(){return this.createAndRunCheck(xo)}))}checkPublishAudio(){return kt(this,void 0,void 0,(function*(){return this.createAndRunCheck(Oo)}))}checkPublishVideo(){return kt(this,void 0,void 0,(function*(){return this.createAndRunCheck(Mo)}))}}const jo=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),Vo=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function qo(e){var t;const i=e.trim().toLowerCase();if(""!==i)return jo.has(i)?jo.get(i):null===(t=Array.from(Vo.entries()).find((e=>{let[t]=e;return i.includes(t)})))||void 0===t?void 0:t[1]}e.BaseKeyProvider=ls,e.ConnectionCheck=Jo,e.ConnectionError=On,e.CriticalTimers=Jn,e.DefaultReconnectPolicy=yt,e.DeviceUnsupportedError=Mn,e.ExternalE2EEKeyProvider=class extends ls{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(Object.assign(Object.assign({},e),{sharedKey:!0,ratchetWindowSize:0,failureTolerance:-1}))}setKey(e){return kt(this,void 0,void 0,(function*(){const t="string"==typeof e?yield cs(e):yield ds(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=An,e.LocalAudioTrack=Ys,e.LocalParticipant=Co,e.LocalTrack=fs,e.LocalTrackPublication=To,e.LocalVideoTrack=lo,e.NegotiationError=Fn,e.Participant=So,e.PublishDataError=class extends An{constructor(e){super(13,null!=e?e:"unable to publish data")}},e.RemoteAudioTrack=vo,e.RemoteParticipant=Eo,e.RemoteTrack=fo,e.RemoteTrackPublication=wo,e.RemoteVideoTrack=go,e.Room=Io,e.RoomState=Ro,e.ScreenSharePresets=er,e.Track=or,e.TrackInvalidError=xn,e.TrackPublication=bo,e.UnexpectedConnectionState=Bn,e.UnsupportedServer=Un,e.VideoPreset=Gn,e.VideoPresets=Zn,e.VideoPresets43=$n,e.attachToElement=ar,e.createAudioAnalyser=function(e,t){const i=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=hr();if(!n)throw new Error("Audio Context not supported on this browser");const r=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,s=n.createMediaStreamSource(new MediaStream([r])),o=n.createAnalyser();o.minDecibels=i.minDecibels,o.maxDecibels=i.maxDecibels,o.fftSize=i.fftSize,o.smoothingTimeConstant=i.smoothingTimeConstant,s.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:o,cleanup:()=>kt(this,void 0,void 0,(function*(){yield n.close(),i.cloneTrack&&r.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=ds,e.createKeyMaterialFromString=cs,e.createLocalAudioTrack=Ao,e.createLocalScreenTracks=function(e){return kt(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=er.h1080fps15.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new Mn("getDisplayMedia not supported");const t=pr(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new xn("no video track found");const r=new lo(n[0],void 0,!1);r.source=or.Source.ScreenShare;const s=[r];if(i.getAudioTracks().length>0){const e=new Ys(i.getAudioTracks()[0],void 0,!1);e.source=or.Source.ScreenShareAudio,s.push(e)}return s}))},e.createLocalTracks=Lo,e.createLocalVideoTrack=No,e.deriveKeys=function(e,t){return kt(this,void 0,void 0,(function*(){const i=us(e.algorithm.name,t),n=yield crypto.subtle.deriveKey(i,e,{name:es,length:128},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:n}}))},e.detachTrack=cr,e.facingModeFromDeviceLabel=qo,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;const n=e instanceof fs?e.mediaStreamTrack:e,r=n.getSettings();let s={facingMode:null!==(i=t.defaultFacingMode)&&void 0!==i?i:"user",confidence:"low"};if("facingMode"in r){const e=r.facingMode;a.debug("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(s={facingMode:e,confidence:"high"})}if(["low","medium"].includes(s.confidence)){a.debug("Try to get facing mode from device label: (".concat(n.label,")"));const e=qo(n.label);void 0!==e&&(s=e)}return s},e.getEmptyAudioStreamTrack=qr,e.getEmptyVideoStreamTrack=function(){return Jr||(Jr=Vr()),Jr.clone()},e.importKey=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:es},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return kt(this,void 0,void 0,(function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===i?["deriveBits","deriveKey"]:["encrypt","decrypt"])}))},e.isBackupCodec=Yn,e.isBrowserSupported=function(){return gr()||yr()},e.isE2EESupported=ss,e.isInsertableStreamSupported=as,e.isScriptTransformSupported=os,e.isVideoFrame=function(e){return"type"in e},e.needsRbspUnescaping=function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1},e.parseRbsp=function(e){const t=[];for(var i=e.length,n=0;n<e.length;)i-n>=3&&!e[n]&&!e[n+1]&&3==e[n+2]?(t.push(e[n++]),t.push(e[n++]),n++):t.push(e[n++]);return new Uint8Array(t)},e.protocolVersion=10,e.ratchet=function(e,t){return kt(this,void 0,void 0,(function*(){const i=us(e.algorithm.name,t);return crypto.subtle.deriveBits(i,e,256)}))},e.setLogExtension=function(t){const i=a.methodFactory;a.methodFactory=(n,r,s)=>{const o=i(n,r,s),a=e.LogLevel[n],c=a>=r&&a<e.LogLevel.silent;return(e,i)=>{i?o(e,i):o(e),c&&t(a,e,i)}},a.setLevel(a.getLevel())},e.setLogLevel=function(e,t){t&&o.getLogger(t).setLevel(e);for(const t of Object.values(o.getLoggers()))t.setLevel(e)},e.supportsAV1=kr,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsDynacast=function(){return gr()},e.supportsVP9=br,e.version=Hn,e.videoCodecs=Qn,e.writeRbsp=function(e){const t=[];for(var i=0,n=0;n<e.length;++n){var r=e[n];r<=3&&i>=2&&(t.push(3),i=0),t.push(r),0==r?++i:i=0}return new Uint8Array(t)}}));
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(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 i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r={exports:{}};!function(e){var t,n;t=i,n=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"];function r(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(t,i){for(var r=0;r<n.length;r++){var s=n[r];this[s]=r<t?e:this.methodFactory(s,t,i)}this.log=this.debug}function a(e,i,n){return function(){typeof console!==t&&(o.call(this,i,n),this[e].apply(this,arguments))}}function c(n,o,c){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?s:void 0!==console[n]?r(console,n):void 0!==console.log?r(console,"log"):e)}(n)||a.apply(this,arguments)}function d(e,i,r){var s,a=this;i=null==i?"WARN":i;var d="loglevel";function u(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=i.indexOf(encodeURIComponent(d)+"=");-1!==n&&(e=/^([^;]+)/.exec(i.slice(n))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=r||c,a.getLevel=function(){return s},a.setLevel=function(i,r){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(s=i,!1!==r&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+i+";"}catch(e){}}}(i),o.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,u()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var l=u();null==l&&(l=i),a.setLevel(l,!1)}var u=new d,l={};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=l[e];return t||(t=l[e]=new d(e,u.getLevel(),u.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=h),u},u.getLoggers=function(){return l},u.default=u,u},e.exports?e.exports=n():t.log=n()}(r);var s,o=r.exports;e.LogLevel=void 0,(s=e.LogLevel||(e.LogLevel={}))[s.trace=0]="trace",s[s.debug=1]="debug",s[s.info=2]="info",s[s.warn=3]="warn",s[s.error=4]="error",s[s.silent=5]="silent";const a=o.getLogger("livekit");function c(e,t){if(!e)throw new Error(t)}a.setDefaultLevel(e.LogLevel.info),o.getLogger("lk-e2ee");const d=34028234663852886e22,u=-34028234663852886e22,l=4294967295,h=2147483647,p=-2147483648;function m(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>h||e<p)throw new Error("invalid int 32: "+e)}function f(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>l||e<0)throw new Error("invalid uint 32: "+e)}function v(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>d||e<u))throw new Error("invalid float 32: "+e)}const g=Symbol("@bufbuild/protobuf/enum-type");function y(e){const t=e[g];return c(t,"missing enum type on enum object"),t}function k(e,t,i,n){e[g]=b(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function b(e,t,i){const n=Object.create(null),r=Object.create(null),s=[];for(const e of t){const t=S(e);s.push(t),n[e.name]=t,r[e.no]=t}return{typeName:e,values:s,findName:e=>n[e],findNumber:e=>r[e]}}function T(e,t,i){const n={};for(const e of t){const t=S(e);n[t.localName]=t.no,n[t.no]=t.localName}return k(n,e,t),n}function S(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class w{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,r=n.makeReadOptions(t);return n.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}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}}var E,C;function P(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,0==(128&n))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,0==(128&i))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,0==(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function R(e,t,i){for(let n=0;n<28;n+=7){const r=e>>>n,s=!(r>>>7==0&&0==t),o=255&(s?128|r:r);if(i.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,r=!(t>>3==0);if(i.push(255&(r?128|n:n)),r){for(let e=3;e<31;e+=7){const n=t>>>e,r=!(n>>>7==0),s=255&(r?128|n:n);if(i.push(s),!r)return}i.push(t>>>31&1)}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(E||(E={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(C||(C={}));const I=4294967296;function D(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,r=0;function s(t,s){const o=Number(e.slice(t,s));r*=i,n=n*i+o,n>=I&&(r+=n/I|0,n%=I)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?N(n,r):L(n,r)}function _(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(I*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let r=(16777215&e)+6777216*i+6710656*n,s=i+8147497*n,o=2*n;const a=1e7;return r>=a&&(s+=Math.floor(r/a),r%=a),s>=a&&(o+=Math.floor(s/a),s%=a),o.toString()+A(s)+A(r)}function L(e,t){return{lo:0|e,hi:0|t}}function N(e,t){return t=~t,e?e=1+~e:t+=1,L(e,t)}const A=e=>{const t=String(e);return"0000000".slice(t.length)+t};function O(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 M(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const x=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"),r=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>r||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=>c(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>c(/^[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),D(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),D(e)),dec:(e,t)=>function(e,t){let i=L(e,t);const n=2147483648&i.hi;n&&(i=N(i.lo,i.hi));const r=_(i.lo,i.hi);return n?"-"+r:r}(e,t),uDec:(e,t)=>_(e,t)}}();var U;!function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(U||(U={}));class B{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw 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(f(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return m(e),O(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){v(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){f(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){m(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return m(e),O(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=x.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=x.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=x.enc(e);return R(t.lo,t.hi,this.buf),this}sint64(e){let t=x.enc(e),i=t.hi>>31;return R(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=x.uEnc(e);return R(t.lo,t.hi,this.buf),this}}class F{constructor(e,t){this.varint64=P,this.uint32=M,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){let t=this.pos;switch(e){case U.Varint:for(;128&this.buf[this.pos++];);break;case U.Bit64:this.pos+=4;case U.Bit32:this.pos+=4;break;case U.LengthDelimited:let t=this.uint32();this.pos+=t;break;case U.StartGroup:let i;for(;(i=this.tag()[1])!==U.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return x.dec(...this.varint64())}uint64(){return x.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,x.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 x.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return x.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 J(e,t){return t instanceof w||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}function j(e,t,i){if(t===i)return!0;if(e==E.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 E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return t==i}return!1}function V(e,t){switch(e){case E.BOOL:return!1;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return 0==t?x.zero:"0";case E.DOUBLE:case E.FLOAT:return 0;case E.BYTES:return new Uint8Array(0);case E.STRING:return"";default:return 0}}function q(e,t){const i=void 0===t;let n=U.Varint,r=0===t;switch(e){case E.STRING:r=i||!t.length,n=U.LengthDelimited;break;case E.BOOL:r=!1===t;break;case E.DOUBLE:n=U.Bit64;break;case E.FLOAT:n=U.Bit32;break;case E.INT64:case E.UINT64:r=i||0==t;break;case E.FIXED64:r=i||0==t,n=U.Bit64;break;case E.BYTES:r=i||!t.byteLength,n=U.LengthDelimited;break;case E.FIXED32:case E.SFIXED32:n=U.Bit32;break;case E.SFIXED64:r=i||0==t,n=U.Bit64;break;case E.SINT64:r=i||0==t}return[n,E[e].toLowerCase(),i||r]}E.DOUBLE,E.FLOAT,E.INT64,E.UINT64,E.INT32,E.UINT32,E.BOOL,E.STRING,E.BYTES;const K=Symbol("@bufbuild/protobuf/unknown-fields"),W={readUnknownFields:!0,readerFactory:e=>new F(e)},G={writeUnknownFields:!0,writerFactory:()=>new B};function H(e){return e?Object.assign(Object.assign({},W),e):W}function z(e){return e?Object.assign(Object.assign({},G),e):G}function Q(e,t,i){return t.getType().runtime.bin.readMessage(t,e,e.uint32(),i),t}function Y(e,t,i){const n=t.uint32(),r=t.pos+n;let s,o;for(;t.pos<r;){let[n]=t.tag();switch(n){case 1:s=Z(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=Z(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=Q(t,new e.V.T,i)}}}if(void 0===s){let t=V(e.K,C.BIGINT);s=e.K==E.BOOL?t.toString():t}if("string"!=typeof s&&"number"!=typeof s&&(s=s.toString()),void 0===o)switch(e.V.kind){case"scalar":o=V(e.V.T,C.BIGINT);break;case"enum":o=0;break;case"message":o=new e.V.T}return[s,o]}function X(e,t){const i=Z(e,t);return"bigint"==typeof i?i.toString():i}function Z(e,t){switch(t){case E.STRING:return e.string();case E.BOOL:return e.bool();case E.DOUBLE:return e.double();case E.FLOAT:return e.float();case E.INT32:return e.int32();case E.INT64:return e.int64();case E.UINT64:return e.uint64();case E.FIXED64:return e.fixed64();case E.BYTES:return e.bytes();case E.FIXED32:return e.fixed32();case E.SFIXED32:return e.sfixed32();case E.SFIXED64:return e.sfixed64();case E.SINT64:return e.sint64();case E.UINT32:return e.uint32();case E.SINT32:return e.sint32()}}function $(e,t,i,n,r){e.tag(i.no,U.LengthDelimited),e.fork();let s=n;switch(i.K){case E.INT32:case E.FIXED32:case E.UINT32:case E.SFIXED32:case E.SINT32:s=Number.parseInt(n);break;case E.BOOL:c("true"==n||"false"==n),s="true"==n}switch(te(e,i.K,1,s,!0),i.V.kind){case"scalar":te(e,i.V.T,2,r,!0);break;case"enum":te(e,E.INT32,2,r,!0);break;case"message":ee(e,t,i.V.T,2,r)}e.join()}function ee(e,t,i,n,r){if(void 0!==r){const s=J(i,r);e.tag(n,U.LengthDelimited).bytes(s.toBinary(t))}}function te(e,t,i,n,r){let[s,o,a]=q(t,n);a&&!r||e.tag(i,s)[o](n)}function ie(e,t,i,n){if(!n.length)return;e.tag(i,U.LengthDelimited).fork();let[,r]=q(t);for(let t=0;t<n.length;t++)e[r](n[t]);e.join()}let ne="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),re=[];for(let e=0;e<ne.length;e++)re[ne[e].charCodeAt(0)]=e;re["-".charCodeAt(0)]=ne.indexOf("+"),re["_".charCodeAt(0)]=ne.indexOf("/");const se={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),r=0,s=0,o=0;for(let t=0;t<e.length;t++){if(i=re[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=i,s=1;break;case 1:n[r++]=o<<2|(48&i)>>4,o=i,s=2;break;case 2:n[r++]=(15&o)<<4|(60&i)>>2,o=i,s=3;break;case 3:n[r++]=(3&o)<<6|i,s=0}}if(1==s)throw Error("invalid base64 string.");return n.subarray(0,r)},enc(e){let t,i="",n=0,r=0;for(let s=0;s<e.length;s++)switch(t=e[s],n){case 0:i+=ne[t>>2],r=(3&t)<<4,n=1;break;case 1:i+=ne[r|t>>4],r=(15&t)<<2,n=2;break;case 2:i+=ne[r|t>>6],i+=ne[63&t],n=0}return n&&(i+=ne[r],i+="=",1==n&&(i+="=")),i}},oe={ignoreUnknownFields:!1},ae={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ce(e){return e?Object.assign(Object.assign({},oe),e):oe}function de(e){return e?Object.assign(Object.assign({},ae),e):ae}function ue(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 le(e,t,i){switch(e){case E.DOUBLE:case E.FLOAT:if(null===t)return 0;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==E.FLOAT&&v(n),n;case E.INT32:case E.FIXED32:case E.SFIXED32:case E.SINT32:case E.UINT32:if(null===t)return 0;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==E.UINT32?f(r):m(r),r;case E.INT64:case E.SFIXED64:case E.SINT64:if(null===t)return x.zero;if("number"!=typeof t&&"string"!=typeof t)break;const s=x.parse(t);return i?s.toString():s;case E.FIXED64:case E.UINT64:if(null===t)return x.zero;if("number"!=typeof t&&"string"!=typeof t)break;const o=x.uParse(t);return i?o.toString():o;case E.BOOL:if(null===t)return!1;if("boolean"!=typeof t)break;return t;case E.STRING:if(null===t)return"";if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case E.BYTES:if(null===t||""===t)return new Uint8Array(0);if("string"!=typeof t)break;return se.dec(t)}throw new Error}function he(e,t,i){if(null===t)return 0;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(n||i)return null==n?void 0:n.no}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(ue(t)))}function pe(e,t,i,n){var r;if(void 0===t)return t;if(0===t&&!i)return;if(n)return t;if("google.protobuf.NullValue"==e.typeName)return null;const s=e.findNumber(t);return null!==(r=null==s?void 0:s.name)&&void 0!==r?r:t}function me(e,t,i){if(void 0!==t)switch(e){case E.INT32:case E.SFIXED32:case E.SINT32:case E.FIXED32:case E.UINT32:return c("number"==typeof t),0!=t||i?t:void 0;case E.FLOAT:case E.DOUBLE:return c("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":0!==t||i?t:void 0;case E.STRING:return c("string"==typeof t),t.length>0||i?t:void 0;case E.BOOL:return c("boolean"==typeof t),t||i?t:void 0;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return c("bigint"==typeof t||"string"==typeof t||"number"==typeof t),i||0!=t?t.toString(10):void 0;case E.BYTES:return c(t instanceof Uint8Array),i||t.byteLength>0?se.enc(t):void 0}}function fe(e){if(void 0===e)return e;if(e instanceof w)return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function ve(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class ge{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 ye(e,t){const i=be(e);return t?i:Ce(Ee(i))}const ke=be;function be(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let r=e.charAt(n);switch(r){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(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),i.push(r)}}return i.join("")}const Te=new Set(["constructor","toString","toJSON","valueOf"]),Se=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),we=e=>"".concat(e,"$"),Ee=e=>Se.has(e)?we(e):e,Ce=e=>Te.has(e)?we(e):e;class Pe{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=ye(e,!1)}addField(e){c(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 Re=(Ie="proto3",De=function(e){const t=e(pe,me);return{makeReadOptions:ce,makeWriteOptions:de,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(this.debug(t)));n=null!=n?n:new e;const r={};for(const[s,o]of Object.entries(t)){const t=e.fields.findJsonName(s);if(!t){if(!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(s,'" is unknown'));continue}let a=t.localName,c=n;if(t.oneof){if(null===o&&"scalar"==t.kind)continue;const i=r[t.oneof.localName];if(i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(s,'"'));r[t.oneof.localName]=s,c=c[t.oneof.localName]={case:a},a="value"}if(t.repeated){if(null===o)continue;if(!Array.isArray(o))throw new Error("cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(o)));const n=c[a];for(const r of o){if(null===r)throw new Error("cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(r)));let s;switch(t.kind){case"message":s=t.T.fromJson(r,i);break;case"enum":if(s=he(t.T,r,i.ignoreUnknownFields),void 0===s)continue;break;case"scalar":try{s=le(t.T,r,t.L)}catch(i){let n="cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(r));throw i instanceof Error&&i.message.length>0&&(n+=": ".concat(i.message)),new Error(n)}}n.push(s)}}else if("map"==t.kind){if(null===o)continue;if(Array.isArray(o)||"object"!=typeof o)throw new Error("cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(o)));const n=c[a];for(const[r,s]of Object.entries(o)){if(null===s)throw new Error("cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: map value null"));let a;switch(t.V.kind){case"message":a=t.V.T.fromJson(s,i);break;case"enum":if(a=he(t.V.T,s,i.ignoreUnknownFields),void 0===a)continue;break;case"scalar":try{a=le(t.V.T,s,C.BIGINT)}catch(i){let n="cannot decode map value for field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(o));throw i instanceof Error&&i.message.length>0&&(n+=": ".concat(i.message)),new Error(n)}}try{n[le(t.K,t.K==E.BOOL?"true"==r||"false"!=r&&r:r,C.BIGINT).toString()]=a}catch(i){let n="cannot decode map key for field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(o));throw i instanceof Error&&i.message.length>0&&(n+=": ".concat(i.message)),new Error(n)}}}else switch(t.kind){case"message":const n=t.T;if(null===o&&"google.protobuf.Value"!=n.typeName){if(t.oneof)throw new Error("cannot decode field ".concat(e.typeName,".").concat(t.name,' from JSON: null is invalid for oneof field "').concat(s,'"'));continue}c[a]instanceof w?c[a].fromJson(o,i):(c[a]=n.fromJson(o,i),n.fieldWrapper&&!t.oneof&&(c[a]=n.fieldWrapper.unwrapField(c[a])));break;case"enum":const r=he(t.T,o,i.ignoreUnknownFields);void 0!==r&&(c[a]=r);break;case"scalar":try{c[a]=le(t.T,o,t.L)}catch(i){let n="cannot decode field ".concat(e.typeName,".").concat(t.name," from JSON: ").concat(this.debug(o));throw i instanceof Error&&i.message.length>0&&(n+=": ".concat(i.message)),new Error(n)}}}return n},writeMessage(e,i){const n=e.getType(),r={};let s;try{for(const o of n.fields.byMember()){let n;if("oneof"==o.kind){const r=e[o.localName];if(void 0===r.value)continue;if(s=o.findField(r.case),!s)throw"oneof case not found: "+r.case;n=t(s,r.value,i)}else s=o,n=t(s,e[s.localName],i);void 0!==n&&(r[i.useProtoFieldName?s.name:s.jsonName]=n)}}catch(e){const t=s?"cannot encode field ".concat(n.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=e instanceof Error?e.message:String(e);throw new Error(t+(i.length>0?": ".concat(i):""))}return r},readScalar:le,writeScalar:me,debug:ue}}(((e,t)=>function(i,n,r){if("map"==i.kind){const s={};switch(i.V.kind){case"scalar":for(const[e,r]of Object.entries(n)){const n=t(i.V.T,r,!0);c(void 0!==n),s[e.toString()]=n}break;case"message":for(const[e,t]of Object.entries(n))s[e.toString()]=t.toJson(r);break;case"enum":const o=i.V.T;for(const[t,i]of Object.entries(n)){c(void 0===i||"number"==typeof i);const n=e(o,i,!0,r.enumAsInteger);c(void 0!==n),s[t.toString()]=n}}return r.emitDefaultValues||Object.keys(s).length>0?s:void 0}if(i.repeated){const s=[];switch(i.kind){case"scalar":for(let e=0;e<n.length;e++)s.push(t(i.T,n[e],!0));break;case"enum":for(let t=0;t<n.length;t++)s.push(e(i.T,n[t],!0,r.enumAsInteger));break;case"message":for(let e=0;e<n.length;e++)s.push(J(i.T,n[e]).toJson(r))}return r.emitDefaultValues||s.length>0?s:void 0}switch(i.kind){case"scalar":return t(i.T,n,!!i.oneof||i.opt||r.emitDefaultValues);case"enum":return e(i.T,n,!!i.oneof||i.opt||r.emitDefaultValues,r.enumAsInteger);case"message":return void 0!==n?J(i.T,n).toJson(r):void 0}})),_e=Object.assign(Object.assign({},{makeReadOptions:H,makeWriteOptions:z,listUnknownFields(e){var t;return null!==(t=e[K])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[K]},writeUnknownFields(e,t){const i=e[K];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const r=e;Array.isArray(r[K])||(r[K]=[]),r[K].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n){const r=e.getType(),s=void 0===i?t.len:t.pos+i;for(;t.pos<s;){const[i,s]=t.tag(),o=r.fields.find(i);if(!o){const r=t.skip(s);n.readUnknownFields&&this.onUnknownField(e,i,s,r);continue}let a=e,c=o.repeated,d=o.localName;switch(o.oneof&&(a=a[o.oneof.localName],a.case!=d&&delete a.value,a.case=d,d="value"),o.kind){case"scalar":case"enum":const e="enum"==o.kind?E.INT32:o.T;let i=Z;if("scalar"==o.kind&&o.L>0&&(i=X),c){let n=a[d];if(s==U.LengthDelimited&&e!=E.STRING&&e!=E.BYTES){let r=t.uint32()+t.pos;for(;t.pos<r;)n.push(i(t,e))}else n.push(i(t,e))}else a[d]=i(t,e);break;case"message":const r=o.T;c?a[d].push(Q(t,new r,n)):a[d]instanceof w?Q(t,a[d],n):(a[d]=Q(t,new r,n),!r.fieldWrapper||o.oneof||o.repeated||(a[d]=r.fieldWrapper.unwrapField(a[d])));break;case"map":let[u,l]=Y(o,t,n);a[d][u]=l}}}}),{writeMessage(e,t,i){const n=e.getType();for(const r of n.fields.byNumber()){let n,s=r.repeated,o=r.localName;if(r.oneof){const t=e[r.oneof.localName];if(t.case!==o)continue;n=t.value}else n=e[o];switch(r.kind){case"scalar":case"enum":let e="enum"==r.kind?E.INT32:r.T;if(s)if(r.packed)ie(t,e,r.no,n);else for(const i of n)te(t,e,r.no,i,!0);else void 0!==n&&te(t,e,r.no,n,!!r.oneof||r.opt);break;case"message":if(s)for(const e of n)ee(t,i,r.T,r.no,e);else ee(t,i,r.T,r.no,n);break;case"map":for(const[e,s]of Object.entries(n))$(t,i,r,e,s)}}return i.writeUnknownFields&&this.writeUnknownFields(e,t),t}}),Le=Object.assign(Object.assign({},{setEnumType:k,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,r=t,s=e;if(void 0!==s[i])switch(n.kind){case"oneof":const e=s[i].case;if(void 0===e)continue;const t=n.findField(e);let o=s[i].value;!t||"message"!=t.kind||o instanceof t.T?t&&"scalar"===t.kind&&t.T===E.BYTES&&(o=ve(o)):o=new t.T(o),r[i]={case:e,value:o};break;case"scalar":case"enum":let a=s[i];n.T===E.BYTES&&(a=n.repeated?a.map(ve):ve(a)),r[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===E.BYTES)for(const[e,t]of Object.entries(s[i]))r[i][e]=ve(t);else Object.assign(r[i],s[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(s[i])){let n=s[i][t];e.fieldWrapper||(n=new e(n)),r[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)r[i]=s[i].map((e=>e instanceof c?e:new c(e)));else if(void 0!==s[i]){const e=s[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?r[i]=ve(e):r[i]=e:r[i]=e instanceof c?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],r=i[e.localName];if(e.repeated){if(n.length!==r.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,r[i])));case"scalar":return n.every(((t,i)=>j(e.T,t,r[i])));case"enum":return n.every(((e,t)=>j(E.INT32,e,r[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(n,r);case"enum":return j(E.INT32,n,r);case"scalar":return j(e.T,n,r);case"oneof":if(n.case!==r.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,r.value);case"enum":return j(E.INT32,n.value,r.value);case"scalar":return j(t.T,n.value,r.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const i=Object.keys(n).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return i.every((e=>t.equals(n[e],r[e])));case"enum":return i.every((e=>j(E.INT32,n[e],r[e])));case"scalar":const s=e.V.T;return i.every((e=>j(s,n[e],r[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const i of t.fields.byMember()){const t=e[i.localName];let r;if(i.repeated)r=t.map(fe);else if("map"==i.kind){r=n[i.localName];for(const[e,i]of Object.entries(t))r[e]=fe(i)}else r="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:fe(t.value)}:{case:void 0}:fe(t);n[i.localName]=r}return i}}),{newFieldList:e=>new ge(e,qe),initFields(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]=V(t.T,t.L)}}}}),{syntax:Ie,json:De,bin:_e,util:Le,makeMessageType(e,t,i){return function(e,t,i,n){var r;const s=null!==(r=null==n?void 0:n.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),o={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(o.prototype,new w),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:T,makeEnumType:b,getEnumType:y});var Ie,De,_e,Le,Ne,Ae,Oe,Me,xe,Ue,Be,Fe,Je,je,Ve;function qe(e){var t,i,n,r;const s=[];let o;for(const a of"function"==typeof e?e():e){const e=a;if(e.localName=ye(a.name,void 0!==a.oneof),e.jsonName=null!==(t=a.jsonName)&&void 0!==t?t:ke(a.name),e.repeated=null!==(i=a.repeated)&&void 0!==i&&i,"scalar"==a.kind&&(e.L=null!==(n=a.L)&&void 0!==n?n:C.BIGINT),e.packed=null!==(r=a.packed)&&void 0!==r?r:"enum"==a.kind||"scalar"==a.kind&&a.T!=E.BYTES&&a.T!=E.STRING,void 0!==a.oneof){const t="string"==typeof a.oneof?a.oneof:a.oneof.name;o&&o.name==t||(o=new Pe(t)),e.oneof=o,o.addField(e)}s.push(e)}return s}class Ke extends w{constructor(e){super(),this.seconds=x.zero,this.nanos=0,Re.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Re.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=x.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 Ke.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ke({seconds:x.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new Ke).fromBinary(e,t)}static fromJson(e,t){return(new Ke).fromJson(e,t)}static fromJsonString(e,t){return(new Ke).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Ke,e,t)}}Ke.runtime=Re,Ke.typeName="google.protobuf.Timestamp",Ke.fields=Re.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}])),function(e){e[e.DEFAULT_AC=0]="DEFAULT_AC",e[e.OPUS=1]="OPUS",e[e.AAC=2]="AAC"}(Ne||(Ne={})),Re.util.setEnumType(Ne,"livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"}]),function(e){e[e.DEFAULT_VC=0]="DEFAULT_VC",e[e.H264_BASELINE=1]="H264_BASELINE",e[e.H264_MAIN=2]="H264_MAIN",e[e.H264_HIGH=3]="H264_HIGH",e[e.VP8=4]="VP8"}(Ae||(Ae={})),Re.util.setEnumType(Ae,"livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),function(e){e[e.IC_DEFAULT=0]="IC_DEFAULT",e[e.IC_JPEG=1]="IC_JPEG"}(Oe||(Oe={})),Re.util.setEnumType(Oe,"livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO",e[e.DATA=2]="DATA"}(Me||(Me={})),Re.util.setEnumType(Me,"livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.CAMERA=1]="CAMERA",e[e.MICROPHONE=2]="MICROPHONE",e[e.SCREEN_SHARE=3]="SCREEN_SHARE",e[e.SCREEN_SHARE_AUDIO=4]="SCREEN_SHARE_AUDIO"}(xe||(xe={})),Re.util.setEnumType(xe,"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"}]),e.VideoQuality=void 0,(Ue=e.VideoQuality||(e.VideoQuality={}))[Ue.LOW=0]="LOW",Ue[Ue.MEDIUM=1]="MEDIUM",Ue[Ue.HIGH=2]="HIGH",Ue[Ue.OFF=3]="OFF",Re.util.setEnumType(e.VideoQuality,"livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),function(e){e[e.POOR=0]="POOR",e[e.GOOD=1]="GOOD",e[e.EXCELLENT=2]="EXCELLENT"}(Be||(Be={})),Re.util.setEnumType(Be,"livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"}]),function(e){e[e.UNSET=0]="UNSET",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(Fe||(Fe={})),Re.util.setEnumType(Fe,"livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),e.DisconnectReason=void 0,(Je=e.DisconnectReason||(e.DisconnectReason={}))[Je.UNKNOWN_REASON=0]="UNKNOWN_REASON",Je[Je.CLIENT_INITIATED=1]="CLIENT_INITIATED",Je[Je.DUPLICATE_IDENTITY=2]="DUPLICATE_IDENTITY",Je[Je.SERVER_SHUTDOWN=3]="SERVER_SHUTDOWN",Je[Je.PARTICIPANT_REMOVED=4]="PARTICIPANT_REMOVED",Je[Je.ROOM_DELETED=5]="ROOM_DELETED",Je[Je.STATE_MISMATCH=6]="STATE_MISMATCH",Je[Je.JOIN_FAILURE=7]="JOIN_FAILURE",Re.util.setEnumType(e.DisconnectReason,"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"}]),function(e){e[e.RR_UNKNOWN=0]="RR_UNKNOWN",e[e.RR_SIGNAL_DISCONNECTED=1]="RR_SIGNAL_DISCONNECTED",e[e.RR_PUBLISHER_FAILED=2]="RR_PUBLISHER_FAILED",e[e.RR_SUBSCRIBER_FAILED=3]="RR_SUBSCRIBER_FAILED",e[e.RR_SWITCH_CANDIDATE=4]="RR_SWITCH_CANDIDATE"}(je||(je={})),Re.util.setEnumType(je,"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"}]),function(e){e[e.SE_UNKNOWN=0]="SE_UNKNOWN",e[e.SE_CODEC_UNSUPPORTED=1]="SE_CODEC_UNSUPPORTED",e[e.SE_TRACK_NOTFOUND=2]="SE_TRACK_NOTFOUND"}(Ve||(Ve={})),Re.util.setEnumType(Ve,"livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]);let We=class e extends w{constructor(e){super(),this.sid="",this.name="",this.emptyTimeout=0,this.maxParticipants=0,this.creationTime=x.zero,this.turnPassword="",this.enabledCodecs=[],this.metadata="",this.numParticipants=0,this.numPublishers=0,this.activeRecording=!1,Re.util.initPartial(e,this)}static fromBinary(t,i){return(new e).fromBinary(t,i)}static fromJson(t,i){return(new e).fromJson(t,i)}static fromJsonString(t,i){return(new e).fromJsonString(t,i)}static equals(t,i){return Re.util.equals(e,t,i)}};We.runtime=Re,We.typeName="livekit.Room",We.fields=Re.util.newFieldList((()=>[{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:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Ge,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}]));class Ge extends w{constructor(e){super(),this.mime="",this.fmtpLine="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Ge).fromBinary(e,t)}static fromJson(e,t){return(new Ge).fromJson(e,t)}static fromJsonString(e,t){return(new Ge).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Ge,e,t)}}Ge.runtime=Re,Ge.typeName="livekit.Codec",Ge.fields=Re.util.newFieldList((()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]));class He extends w{constructor(e){super(),this.enabled=!1,this.min=0,this.max=0,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new He).fromBinary(e,t)}static fromJson(e,t){return(new He).fromJson(e,t)}static fromJsonString(e,t){return(new He).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(He,e,t)}}He.runtime=Re,He.typeName="livekit.PlayoutDelay",He.fields=Re.util.newFieldList((()=>[{no:1,name:"enabled",kind:"scalar",T:8},{no:2,name:"min",kind:"scalar",T:13},{no:3,name:"max",kind:"scalar",T:13}]));class ze extends w{constructor(e){super(),this.canSubscribe=!1,this.canPublish=!1,this.canPublishData=!1,this.canPublishSources=[],this.hidden=!1,this.recorder=!1,this.canUpdateMetadata=!1,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new ze).fromBinary(e,t)}static fromJson(e,t){return(new ze).fromJson(e,t)}static fromJsonString(e,t){return(new ze).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(ze,e,t)}}ze.runtime=Re,ze.typeName="livekit.ParticipantPermission",ze.fields=Re.util.newFieldList((()=>[{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:Re.getEnumType(xe),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}]));class Qe extends w{constructor(e){super(),this.sid="",this.identity="",this.state=Ye.JOINING,this.tracks=[],this.metadata="",this.joinedAt=x.zero,this.name="",this.version=0,this.region="",this.isPublisher=!1,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Qe).fromBinary(e,t)}static fromJson(e,t){return(new Qe).fromJson(e,t)}static fromJsonString(e,t){return(new Qe).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Qe,e,t)}}var Ye,Xe,Ze,$e,et;Qe.runtime=Re,Qe.typeName="livekit.ParticipantInfo",Qe.fields=Re.util.newFieldList((()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:Re.getEnumType(Ye)},{no:4,name:"tracks",kind:"message",T:nt,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",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:ze},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8}])),function(e){e[e.JOINING=0]="JOINING",e[e.JOINED=1]="JOINED",e[e.ACTIVE=2]="ACTIVE",e[e.DISCONNECTED=3]="DISCONNECTED"}(Ye||(Ye={})),Re.util.setEnumType(Ye,"livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]);class tt extends w{constructor(e){super(),Re.util.initPartial(e,this)}static fromBinary(e,t){return(new tt).fromBinary(e,t)}static fromJson(e,t){return(new tt).fromJson(e,t)}static fromJsonString(e,t){return(new tt).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(tt,e,t)}}tt.runtime=Re,tt.typeName="livekit.Encryption",tt.fields=Re.util.newFieldList((()=>[])),function(e){e[e.NONE=0]="NONE",e[e.GCM=1]="GCM",e[e.CUSTOM=2]="CUSTOM"}(Xe||(Xe={})),Re.util.setEnumType(Xe,"livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]);class it extends w{constructor(e){super(),this.mimeType="",this.mid="",this.cid="",this.layers=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new it).fromBinary(e,t)}static fromJson(e,t){return(new it).fromJson(e,t)}static fromJsonString(e,t){return(new it).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(it,e,t)}}it.runtime=Re,it.typeName="livekit.SimulcastCodecInfo",it.fields=Re.util.newFieldList((()=>[{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:rt,repeated:!0}]));class nt extends w{constructor(e){super(),this.sid="",this.type=Me.AUDIO,this.name="",this.muted=!1,this.width=0,this.height=0,this.simulcast=!1,this.disableDtx=!1,this.source=xe.UNKNOWN,this.layers=[],this.mimeType="",this.mid="",this.codecs=[],this.stereo=!1,this.disableRed=!1,this.encryption=Xe.NONE,this.stream="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new nt).fromBinary(e,t)}static fromJson(e,t){return(new nt).fromJson(e,t)}static fromJsonString(e,t){return(new nt).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(nt,e,t)}}nt.runtime=Re,nt.typeName="livekit.TrackInfo",nt.fields=Re.util.newFieldList((()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Re.getEnumType(Me)},{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:Re.getEnumType(xe)},{no:10,name:"layers",kind:"message",T:rt,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:it,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:Re.getEnumType(Xe)},{no:17,name:"stream",kind:"scalar",T:9}]));class rt extends w{constructor(t){super(),this.quality=e.VideoQuality.LOW,this.width=0,this.height=0,this.bitrate=0,this.ssrc=0,Re.util.initPartial(t,this)}static fromBinary(e,t){return(new rt).fromBinary(e,t)}static fromJson(e,t){return(new rt).fromJson(e,t)}static fromJsonString(e,t){return(new rt).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(rt,e,t)}}rt.runtime=Re,rt.typeName="livekit.VideoLayer",rt.fields=Re.util.newFieldList((()=>[{no:1,name:"quality",kind:"enum",T:Re.getEnumType(e.VideoQuality)},{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}]));class st extends w{constructor(t){super(),this.kind=e.DataPacket_Kind.RELIABLE,this.value={case:void 0},Re.util.initPartial(t,this)}static fromBinary(e,t){return(new st).fromBinary(e,t)}static fromJson(e,t){return(new st).fromJson(e,t)}static fromJsonString(e,t){return(new st).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(st,e,t)}}st.runtime=Re,st.typeName="livekit.DataPacket",st.fields=Re.util.newFieldList((()=>[{no:1,name:"kind",kind:"enum",T:Re.getEnumType(e.DataPacket_Kind)},{no:2,name:"user",kind:"message",T:ct,oneof:"value"},{no:3,name:"speaker",kind:"message",T:ot,oneof:"value"}])),e.DataPacket_Kind=void 0,(Ze=e.DataPacket_Kind||(e.DataPacket_Kind={}))[Ze.RELIABLE=0]="RELIABLE",Ze[Ze.LOSSY=1]="LOSSY",Re.util.setEnumType(e.DataPacket_Kind,"livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]);class ot extends w{constructor(e){super(),this.speakers=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new ot).fromBinary(e,t)}static fromJson(e,t){return(new ot).fromJson(e,t)}static fromJsonString(e,t){return(new ot).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(ot,e,t)}}ot.runtime=Re,ot.typeName="livekit.ActiveSpeakerUpdate",ot.fields=Re.util.newFieldList((()=>[{no:1,name:"speakers",kind:"message",T:at,repeated:!0}]));class at extends w{constructor(e){super(),this.sid="",this.level=0,this.active=!1,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new at).fromBinary(e,t)}static fromJson(e,t){return(new at).fromJson(e,t)}static fromJsonString(e,t){return(new at).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(at,e,t)}}at.runtime=Re,at.typeName="livekit.SpeakerInfo",at.fields=Re.util.newFieldList((()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]));class ct extends w{constructor(e){super(),this.participantSid="",this.participantIdentity="",this.payload=new Uint8Array(0),this.destinationSids=[],this.destinationIdentities=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new ct).fromBinary(e,t)}static fromJson(e,t){return(new ct).fromJson(e,t)}static fromJsonString(e,t){return(new ct).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(ct,e,t)}}ct.runtime=Re,ct.typeName="livekit.UserPacket",ct.fields=Re.util.newFieldList((()=>[{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}]));class dt extends w{constructor(e){super(),this.participantSid="",this.trackSids=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new dt).fromBinary(e,t)}static fromJson(e,t){return(new dt).fromJson(e,t)}static fromJsonString(e,t){return(new dt).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(dt,e,t)}}dt.runtime=Re,dt.typeName="livekit.ParticipantTracks",dt.fields=Re.util.newFieldList((()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]));class ut extends w{constructor(e){super(),this.edition=$e.Standard,this.version="",this.protocol=0,this.region="",this.nodeId="",this.debugInfo="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new ut).fromBinary(e,t)}static fromJson(e,t){return(new ut).fromJson(e,t)}static fromJsonString(e,t){return(new ut).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(ut,e,t)}}ut.runtime=Re,ut.typeName="livekit.ServerInfo",ut.fields=Re.util.newFieldList((()=>[{no:1,name:"edition",kind:"enum",T:Re.getEnumType($e)},{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}])),function(e){e[e.Standard=0]="Standard",e[e.Cloud=1]="Cloud"}($e||($e={})),Re.util.setEnumType($e,"livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]);class lt extends w{constructor(e){super(),this.sdk=et.UNKNOWN,this.version="",this.protocol=0,this.os="",this.osVersion="",this.deviceModel="",this.browser="",this.browserVersion="",this.address="",this.network="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new lt).fromBinary(e,t)}static fromJson(e,t){return(new lt).fromJson(e,t)}static fromJsonString(e,t){return(new lt).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(lt,e,t)}}lt.runtime=Re,lt.typeName="livekit.ClientInfo",lt.fields=Re.util.newFieldList((()=>[{no:1,name:"sdk",kind:"enum",T:Re.getEnumType(et)},{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}])),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.JS=1]="JS",e[e.SWIFT=2]="SWIFT",e[e.ANDROID=3]="ANDROID",e[e.FLUTTER=4]="FLUTTER",e[e.GO=5]="GO",e[e.UNITY=6]="UNITY",e[e.REACT_NATIVE=7]="REACT_NATIVE",e[e.RUST=8]="RUST",e[e.PYTHON=9]="PYTHON",e[e.CPP=10]="CPP"}(et||(et={})),Re.util.setEnumType(et,"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"}]);class ht extends w{constructor(e){super(),this.resumeConnection=Fe.UNSET,this.forceRelay=Fe.UNSET,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new ht).fromBinary(e,t)}static fromJson(e,t){return(new ht).fromJson(e,t)}static fromJsonString(e,t){return(new ht).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(ht,e,t)}}ht.runtime=Re,ht.typeName="livekit.ClientConfiguration",ht.fields=Re.util.newFieldList((()=>[{no:1,name:"video",kind:"message",T:pt},{no:2,name:"screen",kind:"message",T:pt},{no:3,name:"resume_connection",kind:"enum",T:Re.getEnumType(Fe)},{no:4,name:"disabled_codecs",kind:"message",T:mt},{no:5,name:"force_relay",kind:"enum",T:Re.getEnumType(Fe)}]));class pt extends w{constructor(e){super(),this.hardwareEncoder=Fe.UNSET,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new pt).fromBinary(e,t)}static fromJson(e,t){return(new pt).fromJson(e,t)}static fromJsonString(e,t){return(new pt).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(pt,e,t)}}pt.runtime=Re,pt.typeName="livekit.VideoConfiguration",pt.fields=Re.util.newFieldList((()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Re.getEnumType(Fe)}]));class mt extends w{constructor(e){super(),this.codecs=[],this.publish=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new mt).fromBinary(e,t)}static fromJson(e,t){return(new mt).fromJson(e,t)}static fromJsonString(e,t){return(new mt).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(mt,e,t)}}mt.runtime=Re,mt.typeName="livekit.DisabledCodecs",mt.fields=Re.util.newFieldList((()=>[{no:1,name:"codecs",kind:"message",T:Ge,repeated:!0},{no:2,name:"publish",kind:"message",T:Ge,repeated:!0}]));class ft extends w{constructor(e){super(),this.duration=0,this.startTimestamp=x.zero,this.endTimestamp=x.zero,this.rtpClockTicks=x.zero,this.driftSamples=x.zero,this.driftMs=0,this.clockRate=0,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new ft).fromBinary(e,t)}static fromJson(e,t){return(new ft).fromJson(e,t)}static fromJsonString(e,t){return(new ft).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(ft,e,t)}}ft.runtime=Re,ft.typeName="livekit.RTPDrift",ft.fields=Re.util.newFieldList((()=>[{no:1,name:"start_time",kind:"message",T:Ke},{no:2,name:"end_time",kind:"message",T:Ke},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"start_timestamp",kind:"scalar",T:4},{no:5,name:"end_timestamp",kind:"scalar",T:4},{no:6,name:"rtp_clock_ticks",kind:"scalar",T:4},{no:7,name:"drift_samples",kind:"scalar",T:3},{no:8,name:"drift_ms",kind:"scalar",T:1},{no:9,name:"clock_rate",kind:"scalar",T:1}]));class vt extends w{constructor(e){super(),this.duration=0,this.packets=0,this.packetRate=0,this.bytes=x.zero,this.headerBytes=x.zero,this.bitrate=0,this.packetsLost=0,this.packetLossRate=0,this.packetLossPercentage=0,this.packetsDuplicate=0,this.packetDuplicateRate=0,this.bytesDuplicate=x.zero,this.headerBytesDuplicate=x.zero,this.bitrateDuplicate=0,this.packetsPadding=0,this.packetPaddingRate=0,this.bytesPadding=x.zero,this.headerBytesPadding=x.zero,this.bitratePadding=0,this.packetsOutOfOrder=0,this.frames=0,this.frameRate=0,this.jitterCurrent=0,this.jitterMax=0,this.gapHistogram={},this.nacks=0,this.nackAcks=0,this.nackMisses=0,this.nackRepeated=0,this.plis=0,this.firs=0,this.rttCurrent=0,this.rttMax=0,this.keyFrames=0,this.layerLockPlis=0,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new vt).fromBinary(e,t)}static fromJson(e,t){return(new vt).fromJson(e,t)}static fromJsonString(e,t){return(new vt).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(vt,e,t)}}vt.runtime=Re,vt.typeName="livekit.RTPStats",vt.fields=Re.util.newFieldList((()=>[{no:1,name:"start_time",kind:"message",T:Ke},{no:2,name:"end_time",kind:"message",T:Ke},{no:3,name:"duration",kind:"scalar",T:1},{no:4,name:"packets",kind:"scalar",T:13},{no:5,name:"packet_rate",kind:"scalar",T:1},{no:6,name:"bytes",kind:"scalar",T:4},{no:39,name:"header_bytes",kind:"scalar",T:4},{no:7,name:"bitrate",kind:"scalar",T:1},{no:8,name:"packets_lost",kind:"scalar",T:13},{no:9,name:"packet_loss_rate",kind:"scalar",T:1},{no:10,name:"packet_loss_percentage",kind:"scalar",T:2},{no:11,name:"packets_duplicate",kind:"scalar",T:13},{no:12,name:"packet_duplicate_rate",kind:"scalar",T:1},{no:13,name:"bytes_duplicate",kind:"scalar",T:4},{no:40,name:"header_bytes_duplicate",kind:"scalar",T:4},{no:14,name:"bitrate_duplicate",kind:"scalar",T:1},{no:15,name:"packets_padding",kind:"scalar",T:13},{no:16,name:"packet_padding_rate",kind:"scalar",T:1},{no:17,name:"bytes_padding",kind:"scalar",T:4},{no:41,name:"header_bytes_padding",kind:"scalar",T:4},{no:18,name:"bitrate_padding",kind:"scalar",T:1},{no:19,name:"packets_out_of_order",kind:"scalar",T:13},{no:20,name:"frames",kind:"scalar",T:13},{no:21,name:"frame_rate",kind:"scalar",T:1},{no:22,name:"jitter_current",kind:"scalar",T:1},{no:23,name:"jitter_max",kind:"scalar",T:1},{no:24,name:"gap_histogram",kind:"map",K:5,V:{kind:"scalar",T:13}},{no:25,name:"nacks",kind:"scalar",T:13},{no:37,name:"nack_acks",kind:"scalar",T:13},{no:26,name:"nack_misses",kind:"scalar",T:13},{no:38,name:"nack_repeated",kind:"scalar",T:13},{no:27,name:"plis",kind:"scalar",T:13},{no:28,name:"last_pli",kind:"message",T:Ke},{no:29,name:"firs",kind:"scalar",T:13},{no:30,name:"last_fir",kind:"message",T:Ke},{no:31,name:"rtt_current",kind:"scalar",T:13},{no:32,name:"rtt_max",kind:"scalar",T:13},{no:33,name:"key_frames",kind:"scalar",T:13},{no:34,name:"last_key_frame",kind:"message",T:Ke},{no:35,name:"layer_lock_plis",kind:"scalar",T:13},{no:36,name:"last_layer_lock_pli",kind:"message",T:Ke},{no:44,name:"packet_drift",kind:"message",T:ft},{no:45,name:"report_drift",kind:"message",T:ft}]));class gt extends w{constructor(e){super(),this.unixMicro=x.zero,this.ticks=0,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new gt).fromBinary(e,t)}static fromJson(e,t){return(new gt).fromJson(e,t)}static fromJsonString(e,t){return(new gt).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(gt,e,t)}}gt.runtime=Re,gt.typeName="livekit.TimedVersion",gt.fields=Re.util.newFieldList((()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]));const yt=7e3,kt=[0,300,1200,2700,4800,yt,yt,yt,yt,yt];class bt{constructor(e){this._retryDelays=void 0!==e?[...e]:kt}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()}}function Tt(e,t,i,n){return new(i||(i=Promise))((function(r,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function St(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.")}function wt(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=St(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,r){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,r,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var Et,Ct={exports:{}},Pt="object"==typeof Reflect?Reflect:null,Rt=Pt&&"function"==typeof Pt.apply?Pt.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};Et=Pt&&"function"==typeof Pt.ownKeys?Pt.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var It=Number.isNaN||function(e){return e!=e};function Dt(){Dt.init.call(this)}Ct.exports=Dt,Ct.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,s),n(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}Ft(e,t,s,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&Ft(e,"error",t,i)}(e,r,{once:!0})}))},Dt.EventEmitter=Dt,Dt.prototype._events=void 0,Dt.prototype._eventsCount=0,Dt.prototype._maxListeners=void 0;var _t=10;function Lt(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Nt(e){return void 0===e._maxListeners?Dt.defaultMaxListeners:e._maxListeners}function At(e,t,i,n){var r,s,o,a;if(Lt(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),o=s[t]),void 0===o)o=s[t]=i,++e._eventsCount;else if("function"==typeof o?o=s[t]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),(r=Nt(e))>0&&o.length>r&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,console&&console.warn&&console.warn(a)}return e}function Ot(){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 Mt(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=Ot.bind(n);return r.listener=i,n.wrapFn=r,r}function xt(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]: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}(r):Bt(r,r.length)}function Ut(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 Bt(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function Ft(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 r(s){n.once&&e.removeEventListener(t,r),i(s)}))}}Object.defineProperty(Dt,"defaultMaxListeners",{enumerable:!0,get:function(){return _t},set:function(e){if("number"!=typeof e||e<0||It(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");_t=e}}),Dt.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},Dt.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||It(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},Dt.prototype.getMaxListeners=function(){return Nt(this)},Dt.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,r=this._events;if(void 0!==r)n=n&&void 0===r.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=r[e];if(void 0===a)return!1;if("function"==typeof a)Rt(a,this,t);else{var c=a.length,d=Bt(a,c);for(i=0;i<c;++i)Rt(d[i],this,t)}return!0},Dt.prototype.addListener=function(e,t){return At(this,e,t,!1)},Dt.prototype.on=Dt.prototype.addListener,Dt.prototype.prependListener=function(e,t){return At(this,e,t,!0)},Dt.prototype.once=function(e,t){return Lt(t),this.on(e,Mt(this,e,t)),this},Dt.prototype.prependOnceListener=function(e,t){return Lt(t),this.prependListener(e,Mt(this,e,t)),this},Dt.prototype.removeListener=function(e,t){var i,n,r,s,o;if(Lt(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(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){o=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},Dt.prototype.off=Dt.prototype.removeListener,Dt.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 r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);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},Dt.prototype.listeners=function(e){return xt(this,e,!0)},Dt.prototype.rawListeners=function(e){return xt(this,e,!1)},Dt.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Ut.call(e,t)},Dt.prototype.listenerCount=Ut,Dt.prototype.eventNames=function(){return this._eventsCount>0?Et(this._events):[]};var Jt=Ct.exports;let jt=!0,Vt=!0;function qt(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function Kt(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=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,s),r.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.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,s.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 Wt(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(jt=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Gt(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Vt=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Ht(){if("object"==typeof window){if(jt)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function zt(e,t){Vt&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Qt(e){return"[object Object]"===Object.prototype.toString.call(e)}function Yt(e){return Qt(e)?Object.keys(e).reduce((function(t,i){const n=Qt(e[i]),r=n?Yt(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r})}),{}):e}function Xt(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Xt(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Xt(e,e.get(t),i)}))})))}function Zt(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&Xt(e,i,r)}))})),r}const $t=Ht;function ei(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 r=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[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(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 s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),$t("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return $t("chrome: "+JSON.stringify(e)),r(e)},s=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){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(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(s(e))))))}}}function ti(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function ii(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 r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),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 r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Kt(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function ni(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 r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};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 ri(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(s(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(s(r(t)))},i])})).then(i,n)}}function si(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=>Zt(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}),Kt(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Zt(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 oi(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 r=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]})),r.apply(this,arguments)}}function ai(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return oi(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 r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.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||{},r.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 r=this._streams[i.id];if(r)r.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=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=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],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(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 ci(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 di(e,t){Kt(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var ui=Object.freeze({__proto__:null,fixNegotiationNeeded:di,shimAddTrackRemoveTrack:ai,shimAddTrackRemoveTrackWithNative:oi,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:ni,shimGetStats:ri,shimGetUserMedia:ei,shimMediaStream:ti,shimOnTrack:ii,shimPeerConnection:ci,shimSenderReceiverGetStats:si});function li(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){zt("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 hi(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 pi(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,r,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,s)}}function mi(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 fi(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}),Kt(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function vi(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){zt("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function gi(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function yi(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){if(!/^[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 ki(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 bi(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 Ti(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 Si=Object.freeze({__proto__:null,shimAddTransceiver:yi,shimCreateAnswer:Ti,shimCreateOffer:bi,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:ki,shimGetUserMedia:li,shimOnTrack:hi,shimPeerConnection:pi,shimRTCDataChannel:gi,shimReceiverGetStats:fi,shimRemoveStream:vi,shimSenderGetStats:mi});function wi(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),r=1;r<i;r++)n[r-1]=arguments[r];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 Ei(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 Ci(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function Pi(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(Ri(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Ri(e){return e&&void 0!==e.video?Object.assign({},e,{video:Yt(e.video)}):e}function Ii(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?(zt("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 Di(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 _i(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 Li(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Ni=Object.freeze({__proto__:null,shimAudioContext:Li,shimCallbacksAPI:Ci,shimConstraints:Ri,shimCreateOfferLegacy:_i,shimGetUserMedia:Pi,shimLocalStreamsAPI:wi,shimRTCIceServerUrls:Ii,shimRemoteStreamsAPI:Ei,shimTrackEventTransceiver:Di}),Ai={exports:{}};!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 e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},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 e=0;e<n.length;e++)i=n[e].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],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.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],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),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 r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.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 r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[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]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substring(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=u}))),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 r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.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 r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[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 r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},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 r;const s=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" 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 e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?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 e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(Ai);var Oi=Ai.exports,Mi=n(Oi),xi=t({__proto__:null,default:Mi},[Oi]);function Ui(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=Mi.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,Kt(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Bi(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Kt(e,"icecandidate",(e=>{if(e.candidate){const t=Mi.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function Fi(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=Mi.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Mi.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 r=Mi.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return i.apply(this,arguments)}}function Ji(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],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>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},Kt(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function ji(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 Vi(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 qi(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 Ki(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"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var Wi,Gi,Hi,zi,Qi=Object.freeze({__proto__:null,removeExtmapAllowMixed:Vi,shimAddIceCandidateNullOrEmpty:qi,shimConnectionState:ji,shimMaxMessageSize:Fi,shimParameterlessSetLocalDescription:Ki,shimRTCIceCandidate:Ui,shimRTCIceCandidateRelayProtocol:Bi,shimSendThrowTypeError:Ji});!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=Ht,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.mozGetUserMedia)t.browser="firefox",t.version=qt(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=qt(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=qt(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:Qi,extractVersion:qt,disableLog:Wt,disableWarnings:Gt,sdp:xi};switch(n.browser){case"chrome":if(!ui||!ci||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=ui,qi(e,n),Ki(e),ei(e,n),ti(e),ci(e,n),ii(e),ai(e,n),ni(e),ri(e),si(e),di(e,n),Ui(e),Bi(e),ji(e),Fi(e,n),Ji(e),Vi(e,n);break;case"firefox":if(!Si||!pi||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=Si,qi(e,n),Ki(e),li(e,n),pi(e,n),hi(e),vi(e),mi(e),fi(e),gi(e),yi(e),ki(e),bi(e),Ti(e),Ui(e),ji(e),Fi(e,n),Ji(e);break;case"safari":if(!Ni||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=Ni,qi(e,n),Ki(e),Ii(e),_i(e),Ci(e),wi(e),Ei(e),Di(e),Pi(e),Li(e),Ui(e),Bi(e),Fi(e,n),Ji(e),Vi(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window}),function(e){e[e.PUBLISHER=0]="PUBLISHER",e[e.SUBSCRIBER=1]="SUBSCRIBER"}(Wi||(Wi={})),Re.util.setEnumType(Wi,"livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),function(e){e[e.ACTIVE=0]="ACTIVE",e[e.PAUSED=1]="PAUSED"}(Gi||(Gi={})),Re.util.setEnumType(Gi,"livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.TLS=2]="TLS"}(Hi||(Hi={})),Re.util.setEnumType(Hi,"livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]);class Yi extends w{constructor(e){super(),this.message={case:void 0},Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Yi).fromBinary(e,t)}static fromJson(e,t){return(new Yi).fromJson(e,t)}static fromJsonString(e,t){return(new Yi).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Yi,e,t)}}Yi.runtime=Re,Yi.typeName="livekit.SignalRequest",Yi.fields=Re.util.newFieldList((()=>[{no:1,name:"offer",kind:"message",T:an,oneof:"message"},{no:2,name:"answer",kind:"message",T:an,oneof:"message"},{no:3,name:"trickle",kind:"message",T:en,oneof:"message"},{no:4,name:"add_track",kind:"message",T:$i,oneof:"message"},{no:5,name:"mute",kind:"message",T:tn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:dn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:un,oneof:"message"},{no:8,name:"leave",kind:"message",T:ln,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:hn,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Cn,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Rn,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Dn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:pn,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:_n,oneof:"message"}]));class Xi extends w{constructor(e){super(),this.message={case:void 0},Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Xi).fromBinary(e,t)}static fromJson(e,t){return(new Xi).fromJson(e,t)}static fromJsonString(e,t){return(new Xi).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Xi,e,t)}}Xi.runtime=Re,Xi.typeName="livekit.SignalResponse",Xi.fields=Re.util.newFieldList((()=>[{no:1,name:"join",kind:"message",T:nn,oneof:"message"},{no:2,name:"answer",kind:"message",T:an,oneof:"message"},{no:3,name:"offer",kind:"message",T:an,oneof:"message"},{no:4,name:"trickle",kind:"message",T:en,oneof:"message"},{no:5,name:"update",kind:"message",T:cn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:sn,oneof:"message"},{no:8,name:"leave",kind:"message",T:ln,oneof:"message"},{no:9,name:"mute",kind:"message",T:tn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:fn,oneof:"message"},{no:11,name:"room_update",kind:"message",T:vn,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:yn,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:bn,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:wn,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Pn,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:on,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:rn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Ln,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:On,oneof:"message"}]));class Zi extends w{constructor(e){super(),this.codec="",this.cid="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Zi).fromBinary(e,t)}static fromJson(e,t){return(new Zi).fromJson(e,t)}static fromJsonString(e,t){return(new Zi).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Zi,e,t)}}Zi.runtime=Re,Zi.typeName="livekit.SimulcastCodec",Zi.fields=Re.util.newFieldList((()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]));class $i extends w{constructor(e){super(),this.cid="",this.name="",this.type=Me.AUDIO,this.width=0,this.height=0,this.muted=!1,this.disableDtx=!1,this.source=xe.UNKNOWN,this.layers=[],this.simulcastCodecs=[],this.sid="",this.stereo=!1,this.disableRed=!1,this.encryption=Xe.NONE,this.stream="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new $i).fromBinary(e,t)}static fromJson(e,t){return(new $i).fromJson(e,t)}static fromJsonString(e,t){return(new $i).fromJsonString(e,t)}static equals(e,t){return Re.util.equals($i,e,t)}}$i.runtime=Re,$i.typeName="livekit.AddTrackRequest",$i.fields=Re.util.newFieldList((()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:Re.getEnumType(Me)},{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:Re.getEnumType(xe)},{no:9,name:"layers",kind:"message",T:rt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Zi,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:Re.getEnumType(Xe)},{no:15,name:"stream",kind:"scalar",T:9}]));class en extends w{constructor(e){super(),this.candidateInit="",this.target=Wi.PUBLISHER,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new en).fromBinary(e,t)}static fromJson(e,t){return(new en).fromJson(e,t)}static fromJsonString(e,t){return(new en).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(en,e,t)}}en.runtime=Re,en.typeName="livekit.TrickleRequest",en.fields=Re.util.newFieldList((()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Re.getEnumType(Wi)}]));class tn extends w{constructor(e){super(),this.sid="",this.muted=!1,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new tn).fromBinary(e,t)}static fromJson(e,t){return(new tn).fromJson(e,t)}static fromJsonString(e,t){return(new tn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(tn,e,t)}}tn.runtime=Re,tn.typeName="livekit.MuteTrackRequest",tn.fields=Re.util.newFieldList((()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]));class nn extends w{constructor(e){super(),this.otherParticipants=[],this.serverVersion="",this.iceServers=[],this.subscriberPrimary=!1,this.alternativeUrl="",this.serverRegion="",this.pingTimeout=0,this.pingInterval=0,this.sifTrailer=new Uint8Array(0),Re.util.initPartial(e,this)}static fromBinary(e,t){return(new nn).fromBinary(e,t)}static fromJson(e,t){return(new nn).fromJson(e,t)}static fromJsonString(e,t){return(new nn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(nn,e,t)}}nn.runtime=Re,nn.typeName="livekit.JoinResponse",nn.fields=Re.util.newFieldList((()=>[{no:1,name:"room",kind:"message",T:We},{no:2,name:"participant",kind:"message",T:Qe},{no:3,name:"other_participants",kind:"message",T:Qe,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:mn,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:ht},{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:ut},{no:13,name:"sif_trailer",kind:"scalar",T:12}]));class rn extends w{constructor(e){super(),this.iceServers=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new rn).fromBinary(e,t)}static fromJson(e,t){return(new rn).fromJson(e,t)}static fromJsonString(e,t){return(new rn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(rn,e,t)}}rn.runtime=Re,rn.typeName="livekit.ReconnectResponse",rn.fields=Re.util.newFieldList((()=>[{no:1,name:"ice_servers",kind:"message",T:mn,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ht}]));class sn extends w{constructor(e){super(),this.cid="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new sn).fromBinary(e,t)}static fromJson(e,t){return(new sn).fromJson(e,t)}static fromJsonString(e,t){return(new sn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(sn,e,t)}}sn.runtime=Re,sn.typeName="livekit.TrackPublishedResponse",sn.fields=Re.util.newFieldList((()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:nt}]));class on extends w{constructor(e){super(),this.trackSid="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new on).fromBinary(e,t)}static fromJson(e,t){return(new on).fromJson(e,t)}static fromJsonString(e,t){return(new on).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(on,e,t)}}on.runtime=Re,on.typeName="livekit.TrackUnpublishedResponse",on.fields=Re.util.newFieldList((()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));class an extends w{constructor(e){super(),this.type="",this.sdp="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new an).fromBinary(e,t)}static fromJson(e,t){return(new an).fromJson(e,t)}static fromJsonString(e,t){return(new an).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(an,e,t)}}an.runtime=Re,an.typeName="livekit.SessionDescription",an.fields=Re.util.newFieldList((()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]));class cn extends w{constructor(e){super(),this.participants=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new cn).fromBinary(e,t)}static fromJson(e,t){return(new cn).fromJson(e,t)}static fromJsonString(e,t){return(new cn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(cn,e,t)}}cn.runtime=Re,cn.typeName="livekit.ParticipantUpdate",cn.fields=Re.util.newFieldList((()=>[{no:1,name:"participants",kind:"message",T:Qe,repeated:!0}]));class dn extends w{constructor(e){super(),this.trackSids=[],this.subscribe=!1,this.participantTracks=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new dn).fromBinary(e,t)}static fromJson(e,t){return(new dn).fromJson(e,t)}static fromJsonString(e,t){return(new dn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(dn,e,t)}}dn.runtime=Re,dn.typeName="livekit.UpdateSubscription",dn.fields=Re.util.newFieldList((()=>[{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:dt,repeated:!0}]));class un extends w{constructor(t){super(),this.trackSids=[],this.disabled=!1,this.quality=e.VideoQuality.LOW,this.width=0,this.height=0,this.fps=0,this.priority=0,Re.util.initPartial(t,this)}static fromBinary(e,t){return(new un).fromBinary(e,t)}static fromJson(e,t){return(new un).fromJson(e,t)}static fromJsonString(e,t){return(new un).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(un,e,t)}}un.runtime=Re,un.typeName="livekit.UpdateTrackSettings",un.fields=Re.util.newFieldList((()=>[{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:Re.getEnumType(e.VideoQuality)},{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}]));class ln extends w{constructor(t){super(),this.canReconnect=!1,this.reason=e.DisconnectReason.UNKNOWN_REASON,Re.util.initPartial(t,this)}static fromBinary(e,t){return(new ln).fromBinary(e,t)}static fromJson(e,t){return(new ln).fromJson(e,t)}static fromJsonString(e,t){return(new ln).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(ln,e,t)}}ln.runtime=Re,ln.typeName="livekit.LeaveRequest",ln.fields=Re.util.newFieldList((()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Re.getEnumType(e.DisconnectReason)}]));class hn extends w{constructor(e){super(),this.trackSid="",this.layers=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new hn).fromBinary(e,t)}static fromJson(e,t){return(new hn).fromJson(e,t)}static fromJsonString(e,t){return(new hn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(hn,e,t)}}hn.runtime=Re,hn.typeName="livekit.UpdateVideoLayers",hn.fields=Re.util.newFieldList((()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:rt,repeated:!0}]));class pn extends w{constructor(e){super(),this.metadata="",this.name="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new pn).fromBinary(e,t)}static fromJson(e,t){return(new pn).fromJson(e,t)}static fromJsonString(e,t){return(new pn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(pn,e,t)}}pn.runtime=Re,pn.typeName="livekit.UpdateParticipantMetadata",pn.fields=Re.util.newFieldList((()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}]));class mn extends w{constructor(e){super(),this.urls=[],this.username="",this.credential="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new mn).fromBinary(e,t)}static fromJson(e,t){return(new mn).fromJson(e,t)}static fromJsonString(e,t){return(new mn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(mn,e,t)}}mn.runtime=Re,mn.typeName="livekit.ICEServer",mn.fields=Re.util.newFieldList((()=>[{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}]));class fn extends w{constructor(e){super(),this.speakers=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new fn).fromBinary(e,t)}static fromJson(e,t){return(new fn).fromJson(e,t)}static fromJsonString(e,t){return(new fn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(fn,e,t)}}fn.runtime=Re,fn.typeName="livekit.SpeakersChanged",fn.fields=Re.util.newFieldList((()=>[{no:1,name:"speakers",kind:"message",T:at,repeated:!0}]));class vn extends w{constructor(e){super(),Re.util.initPartial(e,this)}static fromBinary(e,t){return(new vn).fromBinary(e,t)}static fromJson(e,t){return(new vn).fromJson(e,t)}static fromJsonString(e,t){return(new vn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(vn,e,t)}}vn.runtime=Re,vn.typeName="livekit.RoomUpdate",vn.fields=Re.util.newFieldList((()=>[{no:1,name:"room",kind:"message",T:We}]));class gn extends w{constructor(e){super(),this.participantSid="",this.quality=Be.POOR,this.score=0,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new gn).fromBinary(e,t)}static fromJson(e,t){return(new gn).fromJson(e,t)}static fromJsonString(e,t){return(new gn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(gn,e,t)}}gn.runtime=Re,gn.typeName="livekit.ConnectionQualityInfo",gn.fields=Re.util.newFieldList((()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Re.getEnumType(Be)},{no:3,name:"score",kind:"scalar",T:2}]));class yn extends w{constructor(e){super(),this.updates=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new yn).fromBinary(e,t)}static fromJson(e,t){return(new yn).fromJson(e,t)}static fromJsonString(e,t){return(new yn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(yn,e,t)}}yn.runtime=Re,yn.typeName="livekit.ConnectionQualityUpdate",yn.fields=Re.util.newFieldList((()=>[{no:1,name:"updates",kind:"message",T:gn,repeated:!0}]));class kn extends w{constructor(e){super(),this.participantSid="",this.trackSid="",this.state=Gi.ACTIVE,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new kn).fromBinary(e,t)}static fromJson(e,t){return(new kn).fromJson(e,t)}static fromJsonString(e,t){return(new kn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(kn,e,t)}}kn.runtime=Re,kn.typeName="livekit.StreamStateInfo",kn.fields=Re.util.newFieldList((()=>[{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:Re.getEnumType(Gi)}]));class bn extends w{constructor(e){super(),this.streamStates=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new bn).fromBinary(e,t)}static fromJson(e,t){return(new bn).fromJson(e,t)}static fromJsonString(e,t){return(new bn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(bn,e,t)}}bn.runtime=Re,bn.typeName="livekit.StreamStateUpdate",bn.fields=Re.util.newFieldList((()=>[{no:1,name:"stream_states",kind:"message",T:kn,repeated:!0}]));class Tn extends w{constructor(t){super(),this.quality=e.VideoQuality.LOW,this.enabled=!1,Re.util.initPartial(t,this)}static fromBinary(e,t){return(new Tn).fromBinary(e,t)}static fromJson(e,t){return(new Tn).fromJson(e,t)}static fromJsonString(e,t){return(new Tn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Tn,e,t)}}Tn.runtime=Re,Tn.typeName="livekit.SubscribedQuality",Tn.fields=Re.util.newFieldList((()=>[{no:1,name:"quality",kind:"enum",T:Re.getEnumType(e.VideoQuality)},{no:2,name:"enabled",kind:"scalar",T:8}]));class Sn extends w{constructor(e){super(),this.codec="",this.qualities=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Sn).fromBinary(e,t)}static fromJson(e,t){return(new Sn).fromJson(e,t)}static fromJsonString(e,t){return(new Sn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Sn,e,t)}}Sn.runtime=Re,Sn.typeName="livekit.SubscribedCodec",Sn.fields=Re.util.newFieldList((()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Tn,repeated:!0}]));class wn extends w{constructor(e){super(),this.trackSid="",this.subscribedQualities=[],this.subscribedCodecs=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new wn).fromBinary(e,t)}static fromJson(e,t){return(new wn).fromJson(e,t)}static fromJsonString(e,t){return(new wn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(wn,e,t)}}wn.runtime=Re,wn.typeName="livekit.SubscribedQualityUpdate",wn.fields=Re.util.newFieldList((()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Tn,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Sn,repeated:!0}]));class En extends w{constructor(e){super(),this.participantSid="",this.allTracks=!1,this.trackSids=[],this.participantIdentity="",Re.util.initPartial(e,this)}static fromBinary(e,t){return(new En).fromBinary(e,t)}static fromJson(e,t){return(new En).fromJson(e,t)}static fromJsonString(e,t){return(new En).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(En,e,t)}}En.runtime=Re,En.typeName="livekit.TrackPermission",En.fields=Re.util.newFieldList((()=>[{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}]));class Cn extends w{constructor(e){super(),this.allParticipants=!1,this.trackPermissions=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Cn).fromBinary(e,t)}static fromJson(e,t){return(new Cn).fromJson(e,t)}static fromJsonString(e,t){return(new Cn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Cn,e,t)}}Cn.runtime=Re,Cn.typeName="livekit.SubscriptionPermission",Cn.fields=Re.util.newFieldList((()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:En,repeated:!0}]));class Pn extends w{constructor(e){super(),this.participantSid="",this.trackSid="",this.allowed=!1,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Pn).fromBinary(e,t)}static fromJson(e,t){return(new Pn).fromJson(e,t)}static fromJsonString(e,t){return(new Pn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Pn,e,t)}}Pn.runtime=Re,Pn.typeName="livekit.SubscriptionPermissionUpdate",Pn.fields=Re.util.newFieldList((()=>[{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}]));class Rn extends w{constructor(e){super(),this.publishTracks=[],this.dataChannels=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Rn).fromBinary(e,t)}static fromJson(e,t){return(new Rn).fromJson(e,t)}static fromJsonString(e,t){return(new Rn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Rn,e,t)}}Rn.runtime=Re,Rn.typeName="livekit.SyncState",Rn.fields=Re.util.newFieldList((()=>[{no:1,name:"answer",kind:"message",T:an},{no:2,name:"subscription",kind:"message",T:dn},{no:3,name:"publish_tracks",kind:"message",T:sn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:In,repeated:!0},{no:5,name:"offer",kind:"message",T:an}]));class In extends w{constructor(e){super(),this.label="",this.id=0,this.target=Wi.PUBLISHER,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new In).fromBinary(e,t)}static fromJson(e,t){return(new In).fromJson(e,t)}static fromJsonString(e,t){return(new In).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(In,e,t)}}In.runtime=Re,In.typeName="livekit.DataChannelInfo",In.fields=Re.util.newFieldList((()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:Re.getEnumType(Wi)}]));class Dn extends w{constructor(e){super(),this.scenario={case:void 0},Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Dn).fromBinary(e,t)}static fromJson(e,t){return(new Dn).fromJson(e,t)}static fromJsonString(e,t){return(new Dn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Dn,e,t)}}Dn.runtime=Re,Dn.typeName="livekit.SimulateScenario",Dn.fields=Re.util.newFieldList((()=>[{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:Re.getEnumType(Hi),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"}]));class _n extends w{constructor(e){super(),this.timestamp=x.zero,this.rtt=x.zero,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new _n).fromBinary(e,t)}static fromJson(e,t){return(new _n).fromJson(e,t)}static fromJsonString(e,t){return(new _n).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(_n,e,t)}}_n.runtime=Re,_n.typeName="livekit.Ping",_n.fields=Re.util.newFieldList((()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]));class Ln extends w{constructor(e){super(),this.lastPingTimestamp=x.zero,this.timestamp=x.zero,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Ln).fromBinary(e,t)}static fromJson(e,t){return(new Ln).fromJson(e,t)}static fromJsonString(e,t){return(new Ln).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Ln,e,t)}}Ln.runtime=Re,Ln.typeName="livekit.Pong",Ln.fields=Re.util.newFieldList((()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]));class Nn extends w{constructor(e){super(),this.regions=[],Re.util.initPartial(e,this)}static fromBinary(e,t){return(new Nn).fromBinary(e,t)}static fromJson(e,t){return(new Nn).fromJson(e,t)}static fromJsonString(e,t){return(new Nn).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(Nn,e,t)}}Nn.runtime=Re,Nn.typeName="livekit.RegionSettings",Nn.fields=Re.util.newFieldList((()=>[{no:1,name:"regions",kind:"message",T:An,repeated:!0}]));class An extends w{constructor(e){super(),this.region="",this.url="",this.distance=x.zero,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new An).fromBinary(e,t)}static fromJson(e,t){return(new An).fromJson(e,t)}static fromJsonString(e,t){return(new An).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(An,e,t)}}An.runtime=Re,An.typeName="livekit.RegionInfo",An.fields=Re.util.newFieldList((()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]));class On extends w{constructor(e){super(),this.trackSid="",this.err=Ve.SE_UNKNOWN,Re.util.initPartial(e,this)}static fromBinary(e,t){return(new On).fromBinary(e,t)}static fromJson(e,t){return(new On).fromJson(e,t)}static fromJsonString(e,t){return(new On).fromJsonString(e,t)}static equals(e,t){return Re.util.equals(On,e,t)}}On.runtime=Re,On.typeName="livekit.SubscriptionResponse",On.fields=Re.util.newFieldList((()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Re.getEnumType(Ve)}]));class Mn extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}class xn extends Mn{constructor(e,t,i){super(1,e),this.status=i,this.reason=t}}class Un extends Mn{constructor(e){super(21,null!=e?e:"device is unsupported")}}class Bn extends Mn{constructor(e){super(20,null!=e?e:"track is invalid")}}class Fn extends Mn{constructor(e){super(10,null!=e?e:"unsupported server")}}class Jn extends Mn{constructor(e){super(12,null!=e?e:"unexpected connection state")}}class jn extends Mn{constructor(e){super(13,null!=e?e:"unable to negotiate")}}e.MediaDeviceFailure=void 0,(zi=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",zi.NotFound="NotFound",zi.DeviceInUse="DeviceInUse",zi.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}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={}));class Vn{}Vn.setTimeout=function(){return setTimeout(...arguments)},Vn.setInterval=function(){return setInterval(...arguments)},Vn.clearTimeout=function(){return clearTimeout(...arguments)},Vn.clearInterval=function(){return clearInterval(...arguments)};const qn=/version\/(\d+(\.?_?\d+)+)/i;let Kn;function Wn(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===Kn||t){const e=Gn.find((e=>{let{test:t}=e;return t.test(i)}));Kn=null==e?void 0:e.describe(i)}return Kn}const Gn=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Hn(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Hn(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Hn(qn,e),os:e.includes("mobile/")?"iOS":"macOS"})}];function Hn(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]||""}const zn="1.14.3";class Qn{constructor(e,t,i,n,r){this.width=e,this.height=t,this.encoding={maxBitrate:i,maxFramerate:n,priority:r}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.width/this.height}}}const Yn=["vp8","h264"],Xn=["vp8","h264","vp9","av1"];function Zn(e){return!!Yn.find((t=>t===e))}var $n;e.AudioPresets=void 0,($n=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},$n.speech={maxBitrate:2e4},$n.music={maxBitrate:32e3},$n.musicStereo={maxBitrate:48e3},$n.musicHighQuality={maxBitrate:64e3},$n.musicHighQualityStereo={maxBitrate:96e3};const er={h90:new Qn(160,90,9e4,20),h180:new Qn(320,180,16e4,20),h216:new Qn(384,216,18e4,20),h360:new Qn(640,360,45e4,20),h540:new Qn(960,540,8e5,25),h720:new Qn(1280,720,17e5,30),h1080:new Qn(1920,1080,3e6,30),h1440:new Qn(2560,1440,5e6,30),h2160:new Qn(3840,2160,8e6,30)},tr={h120:new Qn(160,120,7e4,20),h180:new Qn(240,180,125e3,20),h240:new Qn(320,240,14e4,20),h360:new Qn(480,360,33e4,20),h480:new Qn(640,480,5e5,20),h540:new Qn(720,540,6e5,25),h720:new Qn(960,720,13e5,30),h1080:new Qn(1440,1080,23e5,30),h1440:new Qn(1920,1440,38e5,30)},ir={h360fps3:new Qn(640,360,2e5,3,"medium"),h720fps5:new Qn(1280,720,4e5,5,"medium"),h720fps15:new Qn(1280,720,15e5,15,"medium"),h720fps30:new Qn(1280,720,2e6,30,"medium"),h1080fps15:new Qn(1920,1080,25e5,15,"medium"),h1080fps30:new Qn(1920,1080,4e6,30,"medium")};var nr,rr,sr,or;e.RoomEvent=void 0,(nr=e.RoomEvent||(e.RoomEvent={})).Connected="connected",nr.Reconnecting="reconnecting",nr.Reconnected="reconnected",nr.Disconnected="disconnected",nr.ConnectionStateChanged="connectionStateChanged",nr.StateChanged="connectionStateChanged",nr.MediaDevicesChanged="mediaDevicesChanged",nr.ParticipantConnected="participantConnected",nr.ParticipantDisconnected="participantDisconnected",nr.TrackPublished="trackPublished",nr.TrackSubscribed="trackSubscribed",nr.TrackSubscriptionFailed="trackSubscriptionFailed",nr.TrackUnpublished="trackUnpublished",nr.TrackUnsubscribed="trackUnsubscribed",nr.TrackMuted="trackMuted",nr.TrackUnmuted="trackUnmuted",nr.LocalTrackPublished="localTrackPublished",nr.LocalTrackUnpublished="localTrackUnpublished",nr.LocalAudioSilenceDetected="localAudioSilenceDetected",nr.ActiveSpeakersChanged="activeSpeakersChanged",nr.ParticipantMetadataChanged="participantMetadataChanged",nr.ParticipantNameChanged="participantNameChanged",nr.RoomMetadataChanged="roomMetadataChanged",nr.DataReceived="dataReceived",nr.ConnectionQualityChanged="connectionQualityChanged",nr.TrackStreamStateChanged="trackStreamStateChanged",nr.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",nr.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",nr.AudioPlaybackStatusChanged="audioPlaybackChanged",nr.MediaDevicesError="mediaDevicesError",nr.ParticipantPermissionsChanged="participantPermissionsChanged",nr.SignalConnected="signalConnected",nr.RecordingStatusChanged="recordingStatusChanged",nr.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",nr.EncryptionError="encryptionError",nr.DCBufferStatusChanged="dcBufferStatusChanged",nr.ActiveDeviceChanged="activeDeviceChanged",e.ParticipantEvent=void 0,(rr=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",rr.TrackSubscribed="trackSubscribed",rr.TrackSubscriptionFailed="trackSubscriptionFailed",rr.TrackUnpublished="trackUnpublished",rr.TrackUnsubscribed="trackUnsubscribed",rr.TrackMuted="trackMuted",rr.TrackUnmuted="trackUnmuted",rr.LocalTrackPublished="localTrackPublished",rr.LocalTrackUnpublished="localTrackUnpublished",rr.ParticipantMetadataChanged="participantMetadataChanged",rr.ParticipantNameChanged="participantNameChanged",rr.DataReceived="dataReceived",rr.IsSpeakingChanged="isSpeakingChanged",rr.ConnectionQualityChanged="connectionQualityChanged",rr.TrackStreamStateChanged="trackStreamStateChanged",rr.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",rr.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",rr.MediaDevicesError="mediaDevicesError",rr.AudioStreamAcquired="audioStreamAcquired",rr.ParticipantPermissionsChanged="participantPermissionsChanged",rr.PCTrackAdded="pcTrackAdded",e.EngineEvent=void 0,(sr=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",sr.Connected="connected",sr.Disconnected="disconnected",sr.Resuming="resuming",sr.Resumed="resumed",sr.Restarting="restarting",sr.Restarted="restarted",sr.SignalResumed="signalResumed",sr.SignalRestarted="signalRestarted",sr.Closing="closing",sr.MediaTrackAdded="mediaTrackAdded",sr.ActiveSpeakersUpdate="activeSpeakersUpdate",sr.DataPacketReceived="dataPacketReceived",sr.RTPVideoMapUpdate="rtpVideoMapUpdate",sr.DCBufferStatusChanged="dcBufferStatusChanged",sr.ParticipantUpdate="participantUpdate",sr.RoomUpdate="roomUpdate",sr.SpeakersChanged="speakersChanged",sr.StreamStateChanged="streamStateChanged",sr.ConnectionQualityUpdate="connectionQualityUpdate",sr.SubscriptionError="subscriptionError",sr.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.TrackEvent=void 0,(or=e.TrackEvent||(e.TrackEvent={})).Message="message",or.Muted="muted",or.Unmuted="unmuted",or.Restarted="restarted",or.Ended="ended",or.Subscribed="subscribed",or.Unsubscribed="unsubscribed",or.UpdateSettings="updateSettings",or.UpdateSubscription="updateSubscription",or.AudioPlaybackStarted="audioPlaybackStarted",or.AudioPlaybackFailed="audioPlaybackFailed",or.AudioSilenceDetected="audioSilenceDetected",or.VisibilityChanged="visibilityChanged",or.VideoDimensionsChanged="videoDimensionsChanged",or.ElementAttached="elementAttached",or.ElementDetached="elementDetached",or.UpstreamPaused="upstreamPaused",or.UpstreamResumed="upstreamResumed",or.SubscriptionPermissionChanged="subscriptionPermissionChanged",or.SubscriptionStatusChanged="subscriptionStatusChanged",or.SubscriptionFailed="subscriptionFailed";const ar=[];class cr extends Jt.EventEmitter{constructor(e,t){super(),this.attachedElements=[],this.isMuted=!1,this.streamState=cr.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=cr.Source.Unknown}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let i="audio";this.kind===cr.Kind.Video&&(i="video"),0===this.attachedElements.length&&cr.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===i&&(ar.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&ar.splice(ar.indexOf(t),1)),t||(t=document.createElement(i))),this.attachedElements.includes(t)||this.attachedElements.push(t),dr(this.mediaStreamTrack,t);const n=t.srcObject.getTracks();return n.some((e=>"audio"===e.kind))&&t.play().then((()=>{this.emit(e.TrackEvent.AudioPlaybackStarted)})).catch((i=>{"NotAllowedError"===i.name?this.emit(e.TrackEvent.AudioPlaybackFailed,i):a.warn("could not playback audio",i),t&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===i.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){ur(this.mediaStreamTrack,t);const i=this.attachedElements.indexOf(t);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const i=[];return this.attachedElements.forEach((t=>{ur(this.mediaStreamTrack,t),i.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],i}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)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ar.forEach((e=>{e.parentElement||(t=!1)})),t&&ar.push(e)}}handleAppVisibilityChanged(){return Tt(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState}))}addAppVisibilityListener(){Dr()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Dr()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function dr(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)),Rr()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Rr()||Pr())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function ur(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 lr(e,t,i){var n;const r=null!==(n=function(e){if(void 0!==e)return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}(e))&&void 0!==n?n:{};return!0===r.audio&&(r.audio={}),!0===r.video&&(r.video={}),r.audio&&hr(r.audio,t),r.video&&hr(r.video,i),r}function hr(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function pr(e){const t={};if(e.video)if("object"==typeof e.video){const i={},n=i,r=e.video;Object.keys(r).forEach((e=>{if("resolution"===e)hr(n,r.resolution);else n[e]=r[e]})),t.video=i}else t.video=e.video;else t.video=!1;return e.audio?"object"==typeof e.audio?t.audio=e.audio:t.audio=!0:t.audio=!1,t}function mr(){const e="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(e)return new e({latencyHint:"interactive"})}function fr(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&(n="boolean"==typeof n?{}:n,n=Rr()?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}}function vr(e){const t=e.split("/")[1].toLowerCase();if(!Xn.includes(t))throw Error("Video codec not supported: ".concat(t));return t}!function(e){let t,i,n;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(i=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(n=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Me.AUDIO;case t.Video:return Me.VIDEO;default:return Me.DATA}},e.kindFromProto=function(e){switch(e){case Me.AUDIO:return t.Audio;case Me.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return xe.CAMERA;case i.Microphone:return xe.MICROPHONE;case i.ScreenShare:return xe.SCREEN_SHARE;case i.ScreenShareAudio:return xe.SCREEN_SHARE_AUDIO;default:return xe.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case xe.CAMERA:return i.Camera;case xe.MICROPHONE:return i.Microphone;case xe.SCREEN_SHARE:return i.ScreenShare;case xe.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Gi.ACTIVE:return n.Active;case Gi.PAUSED:return n.Paused;default:return n.Unknown}}}(cr||(cr={}));const gr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function yr(e){return Tt(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}function kr(){return"addTransceiver"in RTCPeerConnection.prototype}function br(){return"addTrack"in RTCPeerConnection.prototype}function Tr(){if(!("getCapabilities"in RTCRtpSender))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}function Sr(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Pr())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}function wr(e){return"av1"===e||"vp9"===e}function Er(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}const Cr={Chrome:"100",Safari:"15",Firefox:"100"};function Pr(){var e;return"Firefox"===(null===(e=Wn())||void 0===e?void 0:e.name)}function Rr(){var e;return"Safari"===(null===(e=Wn())||void 0===e?void 0:e.name)}function Ir(){return!!Dr()&&/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent)}function Dr(){return"undefined"!=typeof document}function _r(){return"ReactNative"==navigator.product}function Lr(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Nr(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ar(){if(!_r())return;let e=Nr();return e?e.platform:void 0}function Or(){if(Dr())return window.devicePixelRatio;if(_r()){let e=Nr();if(e)return e.devicePixelRatio}return 1}function Mr(e,t){const i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){const t=parseInt(i[e],10),s=parseInt(n[e],10);if(t>s)return 1;if(t<s)return-1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function xr(e){for(const t of e)t.target.handleResize(t)}function Ur(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Br=null;const Fr=()=>(Br||(Br=new ResizeObserver(xr)),Br);let Jr=null;const jr=()=>(Jr||(Jr=new IntersectionObserver(Ur,{root:null,rootMargin:"0px"})),Jr);let Vr,qr;function Kr(){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 r=document.createElement("canvas");r.width=e,r.height=t;const s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}function Wr(){if(!qr){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(),[qr]=n.stream.getAudioTracks(),!qr)throw Error("Could not get empty media stream audio track");qr.enabled=!1}return qr.clone()}class Gr{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>Tt(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)}))}}class Hr{constructor(){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 zr(e){if("string"==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 Qr(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}var Yr;!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Yr||(Yr={}));class Xr{constructor(){this.pendingTasks=new Map,this.taskMutex=new Hr,this.nextTaskIndex=0}run(e){return Tt(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Yr.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Yr.RUNNING,yield e()}finally{t.status=Yr.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Tt(this,void 0,void 0,(function*(){return this.run((()=>Tt(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}const Zr=["syncState","trickle","offer","answer","simulate","leave"];class $r{constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.rtt=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.isConnected=!1,this.isReconnecting=!1,this.useJSON=e,this.requestQueue=new Xr,this.queuedRequests=[],this.closingLock=new Hr}join(e,t,i,n){return Tt(this,void 0,void 0,(function*(){this.isConnected=!1,this.options=i;return yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return Tt(this,void 0,void 0,(function*(){if(!this.options)return void a.warn("attempted to reconnect without signal options being set, ignoring");this.isReconnecting=!0,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))}))}connect(e,t,i,n){this.connectOptions=i,e=(e=function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e)).replace(/\/$/,""),e+="/rtc";const r=function(e,t,i){var n;const r=new URLSearchParams;r.set("access_token",e),i.reconnect&&(r.set("reconnect","1"),i.sid&&r.set("sid",i.sid));r.set("auto_subscribe",i.autoSubscribe?"1":"0"),r.set("sdk",_r()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);void 0!==i.publishOnly&&r.set("publish",i.publishOnly);i.adaptiveStream&&r.set("adaptive_stream","1");i.reconnectReason&&r.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&r.set("network",navigator.connection.type);return"?".concat(r.toString())}(t,function(){var e;const t=new lt({sdk:et.JS,protocol:10,version:zn});return _r()&&(t.os=null!==(e=Ar())&&void 0!==e?e:""),t}(),i);return new Promise(((t,s)=>Tt(this,void 0,void 0,(function*(){const o=()=>Tt(this,void 0,void 0,(function*(){this.close(),clearTimeout(c),s(new xn("room connection has been cancelled (signal)"))})),c=setTimeout((()=>{this.close(),s(new xn("room connection has timed out (signal)"))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&o(),null==n||n.addEventListener("abort",o),a.debug("connecting to ".concat(e+r)),this.ws&&(yield this.close()),this.ws=new WebSocket(e+r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(c)},this.ws.onerror=t=>Tt(this,void 0,void 0,(function*(){if(this.isConnected)this.handleWSError(t);else{clearTimeout(c);try{const t=yield fetch("http".concat(e.substring(2),"/validate").concat(r));if(t.status.toFixed(0).startsWith("4")){const e=yield t.text();s(new xn(e,0,t.status))}else s(new xn("Internal error",2,t.status))}catch(e){s(new xn("server was not reachable",1))}}})),this.ws.onmessage=e=>Tt(this,void 0,void 0,(function*(){var r,c,d,u;let l;if("string"==typeof e.data){const t=JSON.parse(e.data);l=Xi.fromJson(t)}else{if(!(e.data instanceof ArrayBuffer))return void a.error("could not decode websocket message: ".concat(typeof e.data));l=Xi.fromBinary(new Uint8Array(e.data))}if(!this.isConnected){let e=!1;if("join"===(null===(r=l.message)||void 0===r?void 0:r.case)?(this.isConnected=!0,null==n||n.removeEventListener("abort",o),this.pingTimeoutDuration=l.message.value.pingTimeout,this.pingIntervalDuration=l.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(a.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.startPingInterval()),t(l.message.value)):i.reconnect?(this.isConnected=!0,null==n||n.removeEventListener("abort",o),this.startPingInterval(),"reconnect"===(null===(c=l.message)||void 0===c?void 0:c.case)?t(null===(d=l.message)||void 0===d?void 0:d.value):(t(),e=!0)):i.reconnect||s(new xn("did not receive join response, got ".concat(null===(u=l.message)||void 0===u?void 0:u.case," instead"))),!e)return}this.signalLatency&&(yield yr(this.signalLatency)),this.handleSignalResponse(l)})),this.ws.onclose=e=>{a.warn("websocket closed",{ev:e}),this.handleOnClose(e.reason)}}))))}close(){return Tt(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();try{if(this.isConnected=!1,this.ws){this.ws.onmessage=null,this.ws.onopen=null,this.ws.onclose=null;const e=new Promise((e=>{this.ws?this.ws.onclose=()=>{e()}:e()}));this.ws.readyState<this.ws.CLOSING&&(this.ws.close(),yield Promise.race([e,yr(250)])),this.ws=void 0}}finally{this.clearPingInterval(),e()}}))}sendOffer(e){a.debug("sending offer",e),this.sendRequest({case:"offer",value:ts(e)})}sendAnswer(e){return a.debug("sending answer"),this.sendRequest({case:"answer",value:ts(e)})}sendIceCandidate(e,t){return a.trace("sending ice candidate",e),this.sendRequest({case:"trickle",value:new en({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new tn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return this.sendRequest({case:"updateMetadata",value:new pn({metadata:e,name:t})})}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 hn({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Cn({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:x.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new _n({timestamp:x.parse(Date.now()),rtt:x.parse(this.rtt)})})])}sendLeave(){return this.sendRequest({case:"leave",value:new ln({canReconnect:!1,reason:e.DisconnectReason.CLIENT_INITIATED})})}sendRequest(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Tt(this,void 0,void 0,(function*(){const i=!t&&!function(e){const t=Zr.indexOf(e.case)>=0;return a.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&this.isReconnecting)return void this.queuedRequests.push((()=>Tt(this,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(t||(yield this.requestQueue.flush()),this.signalLatency&&(yield yr(this.signalLatency)),!this.ws||this.ws.readyState!==this.ws.OPEN)return void a.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case));const n=new Yi({message:e});try{this.useJSON?this.ws.send(n.toJsonString()):this.ws.send(n.toBinary())}catch(e){a.error("error sending signal message",{error:e})}}))}handleSignalResponse(e){var t,i;const n=e.message;if(null!=n)if("answer"===n.case){const e=es(n.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.case){const e=es(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?this.resetPingTimeout():"pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout()):a.debug("unsupported message",n);else a.debug("received unsupported message")}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}this.isReconnecting=!1}handleOnClose(e){return Tt(this,void 0,void 0,(function*(){if(!this.isConnected)return;const t=this.onClose;yield this.close(),a.debug("websocket connection closed: ".concat(e)),t&&t(e)}))}handleWSError(e){a.error("websocket error",e)}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Vn.setTimeout((()=>{a.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):a.warn("ping timeout duration not set")}clearPingTimeout(){this.pingTimeout&&Vn.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(a.debug("start ping interval"),this.pingInterval=Vn.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):a.warn("ping interval duration not set")}clearPingInterval(){a.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&Vn.clearInterval(this.pingInterval)}}function es(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 ts(e){return new an({sdp:e.sdp,type:e.type})}const is="AES-GCM",ns="lk_e2ee",rs={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10};var ss,os;function as(){return ds()||cs()}function cs(){return void 0!==window.RTCRtpScriptTransform}function ds(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function us(e){return Tt(this,void 0,void 0,(function*(){let t=new TextEncoder;return yield crypto.subtle.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])}))}function ls(e){return Tt(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function hs(e,t){const i=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:i,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:i,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,(ss=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",ss.RatchetRequest="ratchetRequest",ss.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(os=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",os.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";class ps extends Jt.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.onKeyRatcheted=(e,t)=>{a.debug("key ratcheted event received",{material:e,keyIndex:t})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},rs),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,i,n){const r={key:t,participantIdentity:i,keyIndex:n};this.keyInfoMap.set("".concat(null!=i?i:"shared","-").concat(null!=n?n:0),r),this.emit(e.KeyProviderEvent.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,i){this.emit(e.KeyProviderEvent.RatchetRequest,t,i)}}function ms(e,t,i){var n,r,s;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(r=i.callback)&&r,c=i.maxWait,d=Date.now(),u=[];function l(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),i=this;return new Promise((function(n,r){var c=o&&void 0===s;if(void 0!==s&&clearTimeout(s),s=setTimeout((function(){if(s=void 0,d=Date.now(),!o){var n=e.apply(i,t);a&&a(n),u.forEach((function(e){return(0,e.resolve)(n)})),u=[]}}),l()),c){var h=e.apply(i,t);return a&&a(h),n(h)}u.push({resolve:n,reject:r})}))};return h.cancel=function(e){void 0!==s&&clearTimeout(s),u.forEach((function(t){return(0,t.reject)(e)})),u=[]},h}const fs="default";class vs{static getInstance(){return void 0===this.instance&&(this.instance=new vs),this.instance}getDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i;return Tt(this,void 0,void 0,(function*(){if((null===(i=vs.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){a.debug("awaiting getUserMedia promise");try{e?yield vs.userMediaPromiseMap.get(e):yield Promise.all(vs.userMediaPromiseMap.values())}catch(e){a.warn("error waiting for media permissons")}}let n=yield navigator.mediaDevices.enumerateDevices();if(t&&(!Rr()||!this.hasDeviceInUse(e))){if(0===n.length||n.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e},i=yield navigator.mediaDevices.getUserMedia(t);n=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return e&&(n=n.filter((t=>t.kind===e))),n}))}normalizeDeviceId(e,t,i){return Tt(this,void 0,void 0,(function*(){if(t!==fs)return t;const n=(yield this.getDevices(e)).find((e=>e.groupId===i&&e.deviceId!==fs));return null==n?void 0:n.deviceId}))}hasDeviceInUse(e){return e?vs.userMediaPromiseMap.has(e):vs.userMediaPromiseMap.size>0}}vs.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],vs.userMediaPromiseMap=new Map;class gs extends cr{get constraints(){return this._constraints}constructor(t,i,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,i),this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>a.debug("track mute bounce got cancelled by an unmute event"))),this.debouncedTrackMuteHandler=ms((()=>Tt(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Tt(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(e.TrackEvent.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new Hr,this.pauseUpstreamLock=new Hr,this.processorLock=new Hr,this.setMediaStreamTrack(t,!0),this._constraints=t.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==cr.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}setMediaStreamTrack(e,t){return Tt(this,void 0,void 0,(function*(){if(e===this._mediaStreamTrack&&!t)return;let i;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{ur(this._mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop()),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&&this.processorElement){if(a.debug("restarting processor"),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");dr(e,this.processorElement),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}this.sender&&(yield this.sender.replaceTrack(null!=i?i:e)),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{dr(null!=i?i:e,t)})))}))}waitForDimensions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;var t;return Tt(this,void 0,void 0,(function*(){if(this.kind===cr.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(t=Wn())||void 0===t?void 0:t.os)&&(yield yr(10));const i=Date.now();for(;Date.now()-i<e;){const e=this.dimensions;if(e)return e;yield yr(50)}throw new Bn("unable to get track dimensions after timeout")}))}getDeviceId(){return Tt(this,void 0,void 0,(function*(){if(this.source===cr.Source.ScreenShare)return;const{deviceId:e,groupId:t}=this._mediaStreamTrack.getSettings(),i=this.kind===cr.Kind.Audio?"audioinput":"videoinput";return vs.getInstance().normalizeDeviceId(i,e,t)}))}mute(){return Tt(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Tt(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Tt(this,void 0,void 0,(function*(){if(!this.sender)throw new Bn("unable to replace an unpublished track");return a.debug("replace MediaStreamTrack"),yield this.setMediaStreamTrack(e),this.providedByUser=t,this.processor&&(yield this.stopProcessor()),this}))}restart(t){return Tt(this,void 0,void 0,(function*(){t||(t=this._constraints),a.debug("restarting track with constraints",t);const i={audio:!1,video:!1};this.kind===cr.Kind.Video?i.video=t:i.audio=t,this.attachedElements.forEach((e=>{ur(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const n=(yield navigator.mediaDevices.getUserMedia(i)).getTracks()[0];return n.addEventListener("ended",this.handleEnded),a.debug("re-acquired MediaStreamTrack"),yield this.setMediaStreamTrack(n),this._constraints=t,this.emit(e.TrackEvent.Restarted,this),this}))}setTrackMuted(t){a.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted")),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.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 Tt(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ir()&&(a.debug("visibility changed, is in Background: ".concat(this.isInBackground)),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(a.debug("track needs to be reacquired, restarting ".concat(this.source)),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;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 Tt(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void a.warn("unable to pause upstream for an unpublished track");this._isUpstreamPaused=!0,this.emit(e.TrackEvent.UpstreamPaused,this);const t=Wn();if("Safari"===(null==t?void 0:t.name)&&Mr(t.version,"12.0")<0)throw new Un("pauseUpstream is not supported on Safari < 12.");yield this.sender.replaceTrack(null)}finally{t()}}))}resumeUpstream(){return Tt(this,void 0,void 0,(function*(){const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void a.warn("unable to resume upstream for an unpublished track");this._isUpstreamPaused=!1,this.emit(e.TrackEvent.UpstreamResumed,this),yield this.sender.replaceTrack(this._mediaStreamTrack)}finally{t()}}))}getRTCStatsReport(){var e;return Tt(this,void 0,void 0,(function*(){if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var i,n;return Tt(this,void 0,void 0,(function*(){const r=yield this.processorLock.lock();try{if(a.debug("setting up processor"),this.processor&&(yield this.stopProcessor()),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement=null!==(i=this.processorElement)&&void 0!==i?i:document.createElement(this.kind),this.processorElement.muted=!0,dr(this._mediaStreamTrack,this.processorElement),this.processorElement.play().catch((e=>a.error("failed to play processor element",{error:e})));const r={kind:this.kind,track:this._mediaStreamTrack,element:this.processorElement};if(yield e.init(r),this.processor=e,this.processor.processedTrack){for(const e of this.attachedElements)e!==this.processorElement&&t&&(ur(this._mediaStreamTrack,e),dr(this.processor.processedTrack,e));yield null===(n=this.sender)||void 0===n?void 0:n.replaceTrack(this.processor.processedTrack)}}finally{r()}}))}getProcessor(){return this.processor}stopProcessor(){var e,t;return Tt(this,void 0,void 0,(function*(){this.processor&&(a.debug("stopping processor"),null===(e=this.processor.processedTrack)||void 0===e||e.stop(),yield this.processor.destroy(),this.processor=void 0,null===(t=this.processorElement)||void 0===t||t.remove(),this.processorElement=void 0,yield this.restart())}))}}class ys extends Jt.EventEmitter{constructor(t){super(),this.onWorkerMessage=t=>{var i,n;const{kind:r,data:s}=t.data;switch(r){case"error":a.error(s.error.message),this.emit(e.EncryptionEvent.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const t=null===(n=this.room)||void 0===n?void 0:n.getParticipantByIdentity(s.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,s.enabled,t)}this.encryptionEnabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,s.material,s.keyIndex)}},this.onWorkerError=t=>{a.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1}setup(e){if(!as())throw new Un("tried to setup end-to-end encryption on an unsupported browser");if(a.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions()}};this.worker&&(a.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){a.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):a.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,i){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==Xe.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(i=>{i===e.ConnectionState.Connected&&t.participants.forEach((e=>{e.tracks.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==Xe.NONE,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,i)=>{var n;const r={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(r)})).on(e.RoomEvent.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(e.RoomEvent.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity),i.getKeys().forEach((e=>{this.postKey(e)}))})),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>Tt(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),i.on(e.KeyProviderEvent.SetKey,(e=>this.postKey(e))).on(e.KeyProviderEvent.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 r;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(r=this.room)||void 0===r?void 0:r.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(s)}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?vr(i.mimeType):void 0)}}setupE2EESender(e,t){e instanceof gs&&t?this.handleSender(t,e.mediaStreamID,void 0):t||a.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return Tt(this,void 0,void 0,(function*(){if(this.worker){if(cs()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(ns in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let r=e.writableStream,s=e.readableStream;if(!r||!s){const t=e.createEncodedStreams();e.writableStream=t.writable,r=t.writable,e.readableStream=t.readable,s=t.readable}const o={kind:"decode",data:{readableStream:s,writableStream:r,trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(o,[s,r])}e[ns]=!0}}))}handleSender(e,t,i){var n;if(!(ns 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(cs()){a.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{a.info("initialize encoded streams");const n=e.createEncodedStreams(),r={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(r,[n.readable,n.writable])}e[ns]=!0}}}var ks={},bs={exports:{}},Ts=bs.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",t+=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":"",t+=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"]}]};Object.keys(Ts).forEach((function(e){Ts[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Ss=bs.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;!function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(i[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=Ss,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(r))return i(c,o,r)}})),t.media=s,t};var s=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(s,{})},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),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},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}}))}))}}(ks);var ws=Ss,Es=/%[sdv%]/g,Cs=function(e){var t=1,i=arguments,n=i.length;return e.replace(Es,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},Ps=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var s=t.names[r];t.name?n.push(i[t.name][s]):n.push(i[t.names[r]])}else n.push(i[t.name]);return Cs.apply(null,n)},Rs=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Is=["i","c","b","a"],Ds=ks,_s=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||Rs,n=t.innerOrder||Is,r=[];return i.forEach((function(t){ws[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push(Ps(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(Ps(t,i,e))}))}))})),e.media.forEach((function(e){r.push(Ps("m",ws.m[0],e)),n.forEach((function(t){ws[t].forEach((function(i){i.name in e&&null!=e[i.name]?r.push(Ps(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){r.push(Ps(t,i,e))}))}))}))})),r.join("\r\n")+"\r\n"},Ls=_s,Ns=Ds.parse;const As="negotiationStarted",Os="negotiationComplete",Ms="rtpVideoPayloadTypes";class xs extends Jt.EventEmitter{get pc(){if(this._pc)return this._pc;throw new Jn("Expected peer connection to be available")}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=ms((e=>{this.emit(As);try{this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),100),this._pc="Chrome"===(null===(i=Wn())||void 0===i?void 0:i.name)?new RTCPeerConnection(e,t):new RTCPeerConnection(e),this._pc.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},this._pc.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},this._pc.onconnectionstatechange=()=>{var e,t,i;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,null!==(i=null===(t=this._pc)||void 0===t?void 0:t.connectionState)&&void 0!==i?i:"closed")},this._pc.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this._pc.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)}}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Tt(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){var t;return Tt(this,void 0,void 0,(function*(){let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],r=Ns(null!==(t=e.sdp)&&void 0!==t?t:"");let s=0;return r.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(s=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===s&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===s&&(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=Ns(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 r of e.fmtp)if(r.payload===i){r.config=r.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(r.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=Ls(n)}if(yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,this.createAndSendOffer();else if("answer"===e.type&&(this.emit(Os),e.sdp)){Ns(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Ms,e.rtp)}))}}))}createAndSendOffer(e){var t;return Tt(this,void 0,void 0,(function*(){if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(a.debug("restarting ICE"),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 a.warn("could not createOffer with closed peer connection");a.debug("starting to negotiate");const i=yield this.pc.createOffer(e),n=Ns(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type?Us(e,[],[]):"video"===e.type&&(!function(e){var t,i,n,r;const s=null===(i=null===(t=e.rtp[0])||void 0===t?void 0:t.codec)||void 0===i?void 0:i.toLowerCase();if(!wr(s))return;let o=0;const a=null===(n=e.ext)||void 0===n?void 0:n.some((e=>e.uri===gr||(e.value>o&&(o=e.value),!1)));a||null===(r=e.ext)||void 0===r||r.push({value:o+1,uri:gr})}(e),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;let n=!1;for(const r of e.fmtp)if(r.payload===i){r.config.includes("x-google-start-bitrate")||(r.config+=";x-google-start-bitrate=".concat(Math.round(.7*t.maxbr))),r.config.includes("x-google-max-bitrate")||(r.config+=";x-google-max-bitrate=".concat(t.maxbr)),n=!0;break}return n||e.fmtp.push({payload:i,config:"x-google-start-bitrate=".concat(Math.round(.7*t.maxbr),";x-google-max-bitrate=").concat(t.maxbr)}),!0})))})),yield this.setMungedSDP(i,Ls(n)),this.onOffer(i)}))}createAndSetAnswer(){var e;return Tt(this,void 0,void 0,(function*(){const t=yield this.pc.createAnswer(),i=Ns(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{"audio"===e.type&&Us(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Ls(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){return this.pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){return this.pc.setConfiguration(e)}canRemoveTrack(){return!!this.pc.removeTrack}removeTrack(e){return this.pc.removeTrack(e)}getConnectionState(){return this.pc.connectionState}getICEConnectionState(){return this.pc.iceConnectionState}getSignallingState(){return this.pc.signalingState}getTransceivers(){return this.pc.getTransceivers()}getSenders(){return this.pc.getSenders()}getLocalDescription(){return this.pc.localDescription}getRemoteDescription(){return this.pc.remoteDescription}getConnectedAddress(){var e;return Tt(this,void 0,void 0,(function*(){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 r=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==r?n.get(r):void 0}))}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)}setMungedSDP(e,t,i){return Tt(this,void 0,void 0,(function*(){if(t){const n=e.sdp;e.sdp=t;try{return a.debug("setting munged ".concat(i?"remote":"local"," description")),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(i){a.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:i,sdp:t}),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let n="unknown error";t instanceof Error?n=t.message:"string"==typeof t&&(n=t);const r={error:n,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(r.remoteSdp=this.pc.remoteDescription),a.error("unable to set ".concat(e.type),r),new jn(n)}}))}}function Us(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))))}const Bs={audioBitrate:e.AudioPresets.music.maxBitrate,audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ir.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!1},Fs={autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},Js={resolution:er.h720.resolution},js={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new bt,disconnectOnPageLeave:!0,expWebAudioMix:!1},Vs={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},qs="_lossy",Ks="_reliable",Ws="leave-reconnect";var Gs;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(Gs||(Gs={}));class Hs extends Jt.EventEmitter{get isClosed(){return this._isClosed}constructor(t){super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Vs.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Gs.New,this._isClosed=!0,this.pendingTrackResolvers={},this.hasPublished=!1,this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.handleDataChannel=e=>{let{channel:t}=e;return Tt(this,void 0,void 0,(function*(){if(t){if(t.label===Ks)this.reliableDCSub=t;else{if(t.label!==qs)return;this.lossyDCSub=t}a.debug("on data channel ".concat(t.id,", ").concat(t.label)),t.onmessage=this.handleDataMessage}}))},this.handleDataMessage=t=>Tt(this,void 0,void 0,(function*(){var i,n;const r=yield this.dataProcessLock.lock();try{let r;if(t.data instanceof ArrayBuffer)r=t.data;else{if(!(t.data instanceof Blob))return void a.error("unsupported data type",t.data);r=yield t.data.arrayBuffer()}const s=st.fromBinary(new Uint8Array(r));"speaker"===(null===(i=s.value)||void 0===i?void 0:i.case)?this.emit(e.EngineEvent.ActiveSpeakersUpdate,s.value.value.speakers):"user"===(null===(n=s.value)||void 0===n?void 0:n.case)&&this.emit(e.EngineEvent.DataPacketReceived,s.value.value,s.kind)}finally{r()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;a.error("DataChannel error on ".concat(t,": ").concat(e.message),i)}else a.error("Unknown DataChannel error on ".concat(t),e)},this.handleBufferedAmountLow=t=>{const i=0===t.currentTarget.maxRetransmits?e.DataPacket_Kind.LOSSY:e.DataPacket_Kind.RELIABLE;this.updateAndEmitDCBufferStatus(i)},this.handleDisconnect=(t,i)=>{if(this._isClosed)return;a.warn("".concat(t," disconnected")),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const n=t=>{a.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),this.close()},r=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});null!==s?(t===Ws&&(s=0),a.debug("reconnecting in ".concat(s,"ms")),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Vn.setTimeout((()=>this.attemptReconnect(i)),s)):n(r)},this.waitForRestarted=()=>new Promise(((t,i)=>{this.pcState===Gs.Connected&&t();const n=()=>{this.off(e.EngineEvent.Disconnected,r),t()},r=()=>{this.off(e.EngineEvent.Restarted,n),i()};this.once(e.EngineEvent.Restarted,n),this.once(e.EngineEvent.Disconnected,r)})),this.updateAndEmitDCBufferStatus=t=>{const i=this.isBufferStatusLow(t);void 0!==i&&i!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,i),this.emit(e.EngineEvent.DCBufferStatusChanged,i,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.isReconnecting&&(this.clearReconnectTimeout(),this.attemptReconnect(je.RR_SIGNAL_DISCONNECTED))},this.client=new $r,this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Hr,this.dataProcessLock=new Hr,this.dcBufferStatus=new Map([[e.DataPacket_Kind.LOSSY,!0],[e.DataPacket_Kind.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(e.EngineEvent.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(e.EngineEvent.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(e.EngineEvent.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(e.EngineEvent.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(e.EngineEvent.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(e.EngineEvent.StreamStateChanged,t)}join(e,t,i,n){return Tt(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 r=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.publisher||this.configure(r),this.subscriberPrimary||this.negotiate(),this.clientConfiguration=r.clientConfiguration,r}catch(r){if(r instanceof xn&&1===r.reason&&(a.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts)),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw r}}))}close(){return Tt(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return Tt(this,void 0,void 0,(function*(){this.publisher&&"closed"!==this.publisher.getSignallingState()&&this.publisher.getSenders().forEach((e=>{var t,i;try{(null===(t=this.publisher)||void 0===t?void 0:t.canRemoveTrack())&&(null===(i=this.publisher)||void 0===i||i.removeTrack(e))}catch(e){a.warn("could not removeTrack",{error:e})}})),this.publisher&&(this.publisher.close(),this.publisher=void 0),this.subscriber&&(this.subscriber.close(),this.subscriber=void 0),this.hasPublished=!1,this.primaryTransport=void 0;const e=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0}))}cleanupClient(){return Tt(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Bn("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 xn("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){var t;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 null===(t=this.publisher)||void 0===t||t.removeTrack(e),!0}catch(e){a.warn("failed to remove track",{error:e,method:"removeTrack"})}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 Tt(this,void 0,void 0,(function*(){if(void 0!==this.primaryTransport)return this.primaryTransport.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(t){var i;if(this.publisher||this.subscriber)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const n=this.makeRTCConfiguration(t);this.publisher=new xs(n,{optional:[{googDscp:!0}]}),this.subscriber=new xs(n),this.emit(e.EngineEvent.TransportsCreated,this.publisher,this.subscriber),this.publisher.onIceCandidate=e=>{a.trace("adding ICE candidate for peer",e),this.client.sendIceCandidate(e,Wi.PUBLISHER)},this.subscriber.onIceCandidate=e=>{this.client.sendIceCandidate(e,Wi.SUBSCRIBER)},this.publisher.onOffer=e=>{this.client.sendOffer(e)};let r=this.publisher,s=this.subscriber,o=t.subscriberPrimary;o&&(r=this.subscriber,s=this.publisher,this.subscriber.onDataChannel=this.handleDataChannel),this.primaryTransport=r,r.onConnectionStateChange=i=>Tt(this,void 0,void 0,(function*(){if(a.debug("primary PC state changed ".concat(i)),"connected"===i){const i=this.pcState===Gs.New;this.pcState=Gs.Connected,i&&this.emit(e.EngineEvent.Connected,t)}else"failed"===i&&this.pcState===Gs.Connected&&(this.pcState=Gs.Disconnected,this.handleDisconnect("primary peerconnection",o?je.RR_SUBSCRIBER_FAILED:je.RR_PUBLISHER_FAILED))})),s.onConnectionStateChange=e=>Tt(this,void 0,void 0,(function*(){a.debug("secondary PC state changed ".concat(e)),"failed"===e&&this.handleDisconnect("secondary peerconnection",o?je.RR_PUBLISHER_FAILED:je.RR_SUBSCRIBER_FAILED)})),this.subscriber.onTrack=t=>{this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},this.createDataChannels()}setupSignalClientCallbacks(){this.client.onAnswer=e=>Tt(this,void 0,void 0,(function*(){this.publisher&&(a.debug("received server answer",{RTCSdpType:e.type,signalingState:this.publisher.getSignallingState().toString()}),yield this.publisher.setRemoteDescription(e))})),this.client.onTrickle=(e,t)=>{this.publisher&&this.subscriber&&(a.trace("got ICE candidate from peer",{candidate:e,target:t}),t===Wi.PUBLISHER?this.publisher.addIceCandidate(e):this.subscriber.addIceCandidate(e))},this.client.onOffer=e=>Tt(this,void 0,void 0,(function*(){if(!this.subscriber)return;a.debug("received server offer",{RTCSdpType:e.type,signalingState:this.subscriber.getSignallingState().toString()}),yield this.subscriber.setRemoteDescription(e);const t=yield this.subscriber.createAndSetAnswer();this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{if(a.debug("received trackPublishedResponse",e),!this.pendingTrackResolvers[e.cid])return void a.error("missing track resolver for ".concat(e.cid));const{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onClose=()=>{this.handleDisconnect("signal",je.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{(null==t?void 0:t.canReconnect)?(this.fullReconnectOnNext=!0,this.primaryTransport=void 0,this.handleDisconnect(Ws)):(this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close()),a.trace("leave request",{leave:t})}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(a.debug("E2EE - setting up transports with insertable streams"),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===Fe.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.publisher&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.publisher.createDataChannel(qs,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.publisher.createDataChannel(Ks,{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)}setPreferredCodec(e,t,i){if(!("getCapabilities"in RTCRtpSender))return;const n=RTCRtpSender.getCapabilities(t);if(!n)return;a.debug("get capabilities",n);const r=[],s=[],o=[];n.codecs.forEach((e=>{const t=e.mimeType.toLowerCase();if("audio/opus"===t)return void r.push(e);t==="video/".concat(i)?"h264"!==i||e.sdpFmtpLine&&e.sdpFmtpLine.includes("profile-level-id=42e01f")?r.push(e):s.push(e):o.push(e)})),function(e){if(!Dr())return!1;if(!("setCodecPreferences"in e))return!1;const t=Wn();if(!(null==t?void 0:t.name)||!t.version)return!1;const i=Cr[t.name];return!!i&&Mr(t.version,i)>=0}(e)&&e.setCodecPreferences(r.concat(s,o))}createSender(e,t,i){return Tt(this,void 0,void 0,(function*(){if(kr()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(br()){a.warn("using add-track fallback");return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new Jn("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return Tt(this,void 0,void 0,(function*(){if(kr())return this.createSimulcastTransceiverSender(e,t,i,n);if(br())return a.debug("using add-track fallback"),this.createRTCRtpSender(e.mediaStreamTrack);throw new Jn("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return Tt(this,void 0,void 0,(function*(){if(!this.publisher)throw new Jn("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream);const r={direction:"sendonly",streams:n};i&&(r.sendEncodings=i);const s=yield this.publisher.addTransceiver(e.mediaStreamTrack,r);return e.kind===cr.Kind.Video&&t.videoCodec&&(this.setPreferredCodec(s,e.kind,t.videoCodec),e.codec=t.videoCodec),s.sender}))}createSimulcastTransceiverSender(e,t,i,n){return Tt(this,void 0,void 0,(function*(){if(!this.publisher)throw new Jn("publisher is closed");const r={direction:"sendonly"};n&&(r.sendEncodings=n);const s=yield this.publisher.addTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return this.setPreferredCodec(s,e.kind,i.videoCodec),e.setSimulcastTrackSender(i.videoCodec,s.sender),s.sender}))}createRTCRtpSender(e){return Tt(this,void 0,void 0,(function*(){if(!this.publisher)throw new Jn("publisher is closed");return this.publisher.addTrack(e)}))}attemptReconnect(t){var i,n,r;return Tt(this,void 0,void 0,(function*(){if(!this._isClosed&&!this.attemptingReconnect){(null===(i=this.clientConfiguration)||void 0===i?void 0:i.resumeConnection)!==Fe.DISABLED&&"closed"!==(null!==(r=null===(n=this.primaryTransport)||void 0===n?void 0:n.getSignallingState())&&void 0!==r?r:"closed")||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let i=!0;t instanceof Jn?(a.debug("received unrecoverable error",{error:t}),i=!1):t instanceof zs||(this.fullReconnectOnNext=!0),i?this.handleDisconnect("reconnect",je.RR_UNKNOWN):(a.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){a.warn("encountered error in reconnect policy",{error:e})}return null}restartConnection(t){var i,n,r;return Tt(this,void 0,void 0,(function*(){try{if(!this.url||!this.token)throw new Jn("could not reconnect, url or token not saved");let n;a.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Restarting),this.client.isConnected&&(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw a.warn("attempted connection restart, without signal options present"),new zs;n=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof xn&&0===e.reason)throw new Jn("could not reconnect, token might be expired");throw new zs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,n),yield this.waitForPCReconnected(),null===(i=this.regionUrlProvider)||void 0===i||i.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(r=this.regionUrlProvider)||void 0===r||r.resetAttempts(),e}}))}resumeConnection(t){var i;return Tt(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new Jn("could not reconnect, url or token not saved");if(!this.publisher||!this.subscriber)throw new Jn("publisher and subscriber connections unset");a.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks();const e=yield this.client.reconnect(this.url,this.token,this.participantSid,t);if(e){const t=this.makeRTCConfiguration(e);this.publisher.setConfiguration(t),this.subscriber.setConfiguration(t)}}catch(e){let t="";if(e instanceof Error&&(t=e.message,a.error(e.message)),e instanceof xn&&0===e.reason)throw new Jn("could not reconnect, token might be expired");throw new zs(t)}if(this.emit(e.EngineEvent.SignalResumed),this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");this.subscriber.restartingIce=!0,this.hasPublished&&(yield this.publisher.createAndSendOffer({iceRestart:!0})),yield this.waitForPCReconnected(),this.client.setReconnected(),"open"===(null===(i=this.reliableDC)||void 0===i?void 0:i.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(t,i){return Tt(this,void 0,void 0,(function*(){if(this.pcState!==Gs.Connected){if(this.pcState!==Gs.New)throw new Jn("Expected peer connection to be new on initial connection");return new Promise(((n,r)=>{const s=()=>{a.warn("closing engine"),Vn.clearTimeout(c),r(new xn("room connection has been cancelled",3))};(null==i?void 0:i.signal.aborted)&&s(),null==i||i.signal.addEventListener("abort",s);const o=()=>{Vn.clearTimeout(c),null==i||i.signal.removeEventListener("abort",s),n()},c=Vn.setTimeout((()=>{this.off(e.EngineEvent.Connected,o),r(new xn("could not establish pc connection"))}),null!=t?t:this.peerConnectionTimeout);this.once(e.EngineEvent.Connected,o)}))}}))}waitForPCReconnected(){var e,t;return Tt(this,void 0,void 0,(function*(){const i=Date.now();let n=i;for(this.pcState=Gs.Reconnecting,a.debug("waiting for peer connection to reconnect");n-i<this.peerConnectionTimeout&&void 0!==this.primaryTransport;){if(n-i>2e3&&"connected"===(null===(e=this.primaryTransport)||void 0===e?void 0:e.getConnectionState())&&(!this.hasPublished||"connected"===(null===(t=this.publisher)||void 0===t?void 0:t.getConnectionState()))&&(this.pcState=Gs.Connected),this.pcState===Gs.Connected)return;yield yr(100),n=Date.now()}throw new xn("could not establish PC connection")}))}sendDataPacket(e,t){return Tt(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)}))}ensureDataTransportConnected(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;var i,n,r;return Tt(this,void 0,void 0,(function*(){const s=t?this.subscriber:this.publisher,o=t?"Subscriber":"Publisher";if(!s)throw new xn("".concat(o," connection not set"));t||(null===(i=this.publisher)||void 0===i?void 0:i.isICEConnected)||"checking"===(null===(n=this.publisher)||void 0===n?void 0:n.getICEConnectionState())||this.negotiate();const a=this.dataChannelForKind(e,t);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+this.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(r=this.dataChannelForKind(e,t))||void 0===r?void 0:r.readyState))return;yield yr(50)}throw new xn("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()))}))}ensurePublisherConnected(e){return Tt(this,void 0,void 0,(function*(){yield this.ensureDataTransportConnected(e,!1)}))}verifyTransport(){if(!this.primaryTransport)return!1;if("closed"===this.primaryTransport.getConnectionState()||"failed"===this.primaryTransport.getConnectionState())return!1;if(this.hasPublished&&this.subscriberPrimary){if(!this.publisher)return!1;if("closed"===this.publisher.getConnectionState()||"failed"===this.publisher.getConnectionState())return!1}return!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return new Promise(((t,i)=>{if(!this.publisher)return void i(new jn("publisher is not defined"));this.hasPublished=!0;const n=()=>{a.debug("engine disconnected while negotiation was ongoing"),s(),t()};this.isClosed&&i("cannot negotiate on closed engine"),this.on(e.EngineEvent.Closing,n);const r=setTimeout((()=>{i("negotiation timed out"),this.handleDisconnect("negotiation",je.RR_SIGNAL_DISCONNECTED)}),this.peerConnectionTimeout),s=()=>{clearTimeout(r),this.off(e.EngineEvent.Closing,n)};this.publisher.once(As,(()=>{var e;null===(e=this.publisher)||void 0===e||e.once(Os,(()=>{s(),t()}))})),this.publisher.once(Ms,(t=>{const i=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();var n;n=t,Xn.includes(n)&&i.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,i)})),this.publisher.negotiate((e=>{s(),i(e),e instanceof jn&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",je.RR_UNKNOWN)}))}))}dataChannelForKind(t,i){if(i){if(t===e.DataPacket_Kind.LOSSY)return this.lossyDCSub;if(t===e.DataPacket_Kind.RELIABLE)return this.reliableDCSub}else{if(t===e.DataPacket_Kind.LOSSY)return this.lossyDC;if(t===e.DataPacket_Kind.RELIABLE)return this.reliableDC}}failNext(){this.shouldFailNext=!0}clearReconnectTimeout(){this.reconnectTimeout&&Vn.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Dr()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Dr()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class zs extends Error{}class Qs{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 Lr(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return Tt(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),a.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return Tt(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 xn("Could not fetch region settings: ".concat(t.statusText),401===t.status?0:void 0,t.status)}))}}const Ys=2e3;function Xs(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 Zs extends gs{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,cr.Kind.Audio,t,i),this.stopOnMute=!1,this.monitorSender=()=>Tt(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void a.error("could not get audio sender stats",{error:e})}e&&this.prevStats&&(this._currentBitrate=Xs(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.checkForSilence()}setDeviceId(e){return Tt(this,void 0,void 0,(function*(){return this._constraints.deviceId===e||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||zr(e)===this.mediaStreamTrack.getSettings().deviceId)}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Tt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source===cr.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(a.debug("stopping mic track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Tt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==zr(this._constraints.deviceId);return this.source!==cr.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(a.debug("reacquiring mic track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return Tt(this,void 0,void 0,(function*(){let t;if(e){const i=pr({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 Tt(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){Dr()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Ys)))}setProcessor(e){var t;return Tt(this,void 0,void 0,(function*(){const i=yield this.processorLock.lock();try{if(!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");if(this.processor&&(yield this.stopProcessor()),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};a.debug("setting up audio processor ".concat(e.name)),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))}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){var e;return Tt(this,void 0,void 0,(function*(){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 Tt(this,void 0,void 0,(function*(){const t=yield function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return Tt(this,void 0,void 0,(function*(){const i=mr();if(i){const n=i.createAnalyser();n.fftSize=2048;const r=n.frequencyBinCount,s=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield yr(t),n.getByteTimeDomainData(s);const o=s.some((e=>128!==e&&0!==e));return i.close(),!o}return!1}))}(this);return t&&(this.isMuted||a.warn("silence detected on local audio track"),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}function $s(e,t){switch(e.kind){case"audio":return new Zs(e,t,!1);case"video":return new po(e,t,!1);default:throw new Bn("unsupported track type: ".concat(e.kind))}}const eo=Object.values(er),to=Object.values(tr),io=Object.values(ir),no=[er.h180,er.h360],ro=[tr.h180,tr.h360],so=e=>[{scaleResolutionDownBy:2,fps:3}].map((t=>{var i;return new Qn(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/t.fps)))),t.fps,e.encoding.priority)})),oo=["q","h","f"];function ao(e,t,i,n){var r,s;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const c=null==n?void 0:n.simulcast,d=null==n?void 0:n.scalabilityMode,u=null==n?void 0:n.videoCodec;if(!o&&!c&&!d||!t||!i)return[{}];o||(o=function(e,t,i,n){const r=function(e,t,i){if(e)return io;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return eo;return to}(e,t,i);let{encoding:s}=r[0];const o=Math.max(t,i);for(let e=0;e<r.length;e+=1){const t=r[e];if(s=t.encoding,t.width>=o)break}if(n)switch(n){case"av1":s=Object.assign({},s),s.maxBitrate=.7*s.maxBitrate;break;case"vp9":s=Object.assign({},s),s.maxBitrate=.85*s.maxBitrate}return s}(e,t,i,u),a.debug("using video encoding",o));const l=new Qn(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(d&&wr(u)){a.debug("using svc with scalabilityMode ".concat(d));const e=new ho(d),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));for(let i=0;i<e.spatial;i+=1)t.push({rid:oo[2-i],maxBitrate:o.maxBitrate/Math.pow(3,i),maxFramerate:l.encoding.maxFramerate});return t[0].scalabilityMode=d,a.debug("encodings",t),t}if(!c)return[o];let h,p=[];if(p=e?null!==(r=lo(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==r?r:co(e,l):null!==(s=lo(null==n?void 0:n.videoSimulcastLayers))&&void 0!==s?s:co(e,l),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return uo(t,i,[e,h,l]);if(n>=480)return uo(t,i,[e,l])}return uo(t,i,[l])}function co(e,t){if(e)return so(t);const{width:i,height:n}=t,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?no:ro}function uo(e,t,i){const n=[];if(i.forEach(((i,r)=>{if(r>=oo.length)return;const s=Math.min(e,t),o={rid:oo[r],scaleResolutionDownBy:Math.max(1,s/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate};i.encoding.maxFramerate&&(o.maxFramerate=i.encoding.maxFramerate);const a=Pr()||0===r;i.encoding.priority&&a&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),n.push(o)})),_r()&&"ios"===Ar()){let e;n.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;n.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,a.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),a.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return n}function lo(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 ho{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 po extends gs{constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];super(e,cr.Kind.Video,t,i),this.simulcastCodecs=new Map,this.monitorSender=()=>Tt(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void a.error("could not get audio sender stats",{error:e})}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const r=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=Xs(t,r)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Hr}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Dr())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()}),Ys))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});var t,i,n,r,s;return Tt(this,void 0,void 0,(function*(){yield e.pauseUpstream.call(this);try{for(var o,a=!0,c=wt(this.simulcastCodecs.values());o=yield c.next(),!(t=o.done);a=!0){r=o.value,a=!1;const e=r;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(null)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});var t,i,n,r,s;return Tt(this,void 0,void 0,(function*(){yield e.resumeUpstream.call(this);try{for(var o,a=!0,c=wt(this.simulcastCodecs.values());o=yield c.next(),!(t=o.done);a=!0){r=o.value,a=!1;const e=r;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(e.mediaStreamTrack)}}catch(e){i={error:e}}finally{try{a||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 Tt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==cr.Source.Camera||this.isUserProvided||(a.debug("stopping camera track"),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Tt(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.source!==cr.Source.Camera||this.isUserProvided||(a.debug("reacquiring camera track"),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){var e;return Tt(this,void 0,void 0,(function*(){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 r={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,framesSent:e.framesSent,timestamp:e.timestamp,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges},s=i.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.roundTripTime),t.push(r)}})),t}))}setPublishingQuality(t){const i=[];for(let n=e.VideoQuality.LOW;n<=e.VideoQuality.HIGH;n+=1)i.push(new Tn({quality:n,enabled:n<=t}));a.debug("setting publishing quality. max quality ".concat(t)),this.setPublishingLayers(i)}setDeviceId(e){return Tt(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===zr(e)||(this._constraints.deviceId=e,this.isMuted||(yield this.restartTrack()),this.isMuted||zr(e)===this._mediaStreamTrack.getSettings().deviceId)}))}restartTrack(e){var t,i,n,r;return Tt(this,void 0,void 0,(function*(){let s;if(e){const t=pr({video:e});"boolean"!=typeof t.video&&(s=t.video)}yield this.restart(s);try{for(var o,a=!0,c=wt(this.simulcastCodecs.values());o=yield c.next(),!(t=o.done);a=!0){r=o.value,a=!1;const e=r;e.sender&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}setProcessor(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});var n,r,s,o,a,c;return Tt(this,void 0,void 0,(function*(){if(yield i.setProcessor.call(this,e,t),null===(a=this.processor)||void 0===a?void 0:a.processedTrack)try{for(var d,u=!0,l=wt(this.simulcastCodecs.values());d=yield l.next(),!(n=d.done);u=!0){o=d.value,u=!1;const e=o;yield null===(c=e.sender)||void 0===c?void 0:c.replaceTrack(this.processor.processedTrack)}}catch(e){r={error:e}}finally{try{u||n||!(s=l.return)||(yield s.call(l))}finally{if(r)throw r.error}}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))throw new Error("".concat(e," already added"));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){var t,i,n,r,s,o,c;return Tt(this,void 0,void 0,(function*(){if(a.debug("setting publishing codecs",{codecs:e,currentCodec:this.codec}),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=wt(e);n=yield i.next(),!(r=n.done);t=!0){c=n.value,t=!1;const e=c;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(a.debug("try setPublishingCodec for ".concat(e.codec),t),t&&t.sender)t.encodings&&(a.debug("try setPublishingLayersForSender ".concat(e.codec)),yield mo(t.sender,t.encodings,e.qualities,this.senderLock));else for(const t of e.qualities)if(t.enabled){d.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(e){s={error:e}}finally{try{t||r||!(o=i.return)||(yield o.call(i))}finally{if(s)throw s.error}}return d}))}setPublishingLayers(e){return Tt(this,void 0,void 0,(function*(){a.debug("setting publishing layers",e),this.sender&&this.encodings&&(yield mo(this.sender,this.encodings,e,this.senderLock))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Tt(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ir()&&this.isInBackground&&this.source===cr.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function mo(e,t,i,n){return Tt(this,void 0,void 0,(function*(){const r=yield n.lock();a.debug("setPublishingLayersForSender",{sender:e,qualities:i,senderEncodings:t});try{const n=e.getParameters(),{encodings:r}=n;if(!r)return;if(r.length!==t.length)return void a.warn("cannot set publishing layers, encodings mismatch");let s=!1;!1&&r[0].scalabilityMode||r.forEach(((e,n)=>{var r;let o=null!==(r=e.rid)&&void 0!==r?r:"";""===o&&(o="q");const c=fo(o),d=i.find((e=>e.quality===c));d&&e.active!==d.enabled&&(s=!0,e.active=d.enabled,a.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled")),Pr()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))})),s&&(n.encodings=r,a.debug("setting encodings",n.encodings),yield e.setParameters(n))}finally{r()}}))}function fo(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function vo(t,i,n,r){if(!n)return[new rt({quality:e.VideoQuality.HIGH,width:t,height:i,bitrate:0,ssrc:0})];if(r){const r=n[0].scalabilityMode,s=new ho(r),o=[];for(let r=0;r<s.spatial;r+=1)o.push(new rt({quality:e.VideoQuality.HIGH-r,width:Math.ceil(t/Math.pow(2,r)),height:Math.ceil(i/Math.pow(2,r)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(3,r)):0,ssrc:0}));return o}return n.map((e=>{var n,r,s;const o=null!==(n=e.scaleResolutionDownBy)&&void 0!==n?n:1;let a=fo(null!==(r=e.rid)&&void 0!==r?r:"");return new rt({quality:a,width:Math.ceil(t/o),height:Math.ceil(i/o),bitrate:null!==(s=e.maxBitrate)&&void 0!==s?s:0,ssrc:0})}))}class go extends cr{constructor(e,t,i,n){super(e,i),this.sid=t,this.receiver=n}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const i=n=>{n.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",i),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",i)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){var e;return Tt(this,void 0,void 0,(function*(){if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),Ys))}}class yo extends go{constructor(e,t,i,n,r){super(e,t,cr.Kind.Audio,i),this.monitorReceiver=()=>Tt(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=Xs(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.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;_r()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(_r())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Tt(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Er(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.elementVolume&&(e.volume=this.elementVolume),this.sinkId&&Er(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(a.debug("using audio context mapping"),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),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(t,i){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(i.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{n.connect(e),n=e})),this.gainNode=t.createGain(),n.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}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 Tt(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",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 ko extends go{constructor(e,t,i,n){super(e,t,cr.Kind.Video,i),this.elementInfos=[],this.monitorReceiver=()=>Tt(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=Xs(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=ms((()=>{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?ur(this._mediaStreamTrack,t):dr(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 bo(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()):a.warn("visibility resize observer not triggered")}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void a.warn("stopObservingElementInfo ignored");const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.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 e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Tt(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:"video",framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation})})),e}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Tt(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var t,i;const n=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),r=!(null!==(i=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),o=this.elementInfos.some((e=>e.visible))&&!r||s;this.lastVisible!==o&&(!o&&Date.now()-n<100?Vn.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=o,this.emit(e.TrackEvent.VisibilityChanged,o,this)))}updateDimensions(){var t,i;let n=0,r=0;const s=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*s,i=e.height()*s;t+i>n+r&&(n=t,r=i)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===n&&(null===(i=this.lastDimensions)||void 0===i?void 0:i.height)===r||(this.lastDimensions={width:n,height:r},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return Or();if(!t){return Or()>2?2:1}return t}}class bo{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.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e;this.isPiP=!0,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=!1,null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:To(e),this.isPiP=Dr()&&document.pictureInPictureElement===e,this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){this.isIntersecting=To(this.element),this.isPiP=document.pictureInPictureElement===this.element,this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,jr().observe(this.element),Fr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP)}stopObserving(){var e,t;null===(e=jr())||void 0===e||e.unobserve(this.element),null===(t=Fr())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP)}}function To(e){let t=e.offsetTop,i=e.offsetLeft;const n=e.offsetWidth,r=e.offsetHeight,{hidden:s}=e,{opacity:o,display:a}=getComputedStyle(e);for(;e.offsetParent;)t+=(e=e.offsetParent).offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+r>window.pageYOffset&&i+n>window.pageXOffset&&!s&&(""===o||parseFloat(o)>0)&&"none"!==a}class So extends Jt.EventEmitter{constructor(t,i,n){super(),this.metadataMuted=!1,this.encryption=Xe.NONE,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.setMaxListeners(100),this.kind=t,this.trackSid=i,this.trackName=n,this.source=cr.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==Xe.NONE}get audioTrack(){if(this.track instanceof Zs||this.track instanceof yo)return this.track}get videoTrack(){if(this.track instanceof po||this.track instanceof ko)return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=cr.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===cr.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,a.debug("update publication info",{info:e})}}!function(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(So||(So={}));class wo extends So{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,i,n){super(t,i.sid,i.name),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.updateInfo(i),this.setTrack(n)}setTrack(t){this.track&&this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),super.setTrack(t),t&&t.on(e.TrackEvent.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}mute(){var e;return Tt(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){var e;return Tt(this,void 0,void 0,(function*(){return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){var e;return Tt(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){var e;return Tt(this,void 0,void 0,(function*(){yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}}e.ConnectionQuality=void 0,function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Unknown="unknown"}(e.ConnectionQuality||(e.ConnectionQuality={}));class Eo extends Jt.EventEmitter{get isEncrypted(){return this.tracks.size>0&&Array.from(this.tracks.values()).every((e=>e.isEncrypted))}constructor(t,i,n,r){super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.setMaxListeners(100),this.sid=t,this.identity=i,this.name=n,this.metadata=r,this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map}getTracks(){return Array.from(this.tracks.values())}getTrack(e){for(const[,t]of this.tracks)if(t.source===e)return t}getTrackByName(e){for(const[,t]of this.tracks)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrack(cr.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrack(cr.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrack(cr.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),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,a.trace("update participant info",{info:e}),!0)}_setMetadata(t){const i=this.metadata!==t,n=this.metadata;this.metadata=t,i&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,n)}_setName(t){const i=this.name!==t;this.name=t,i&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}setPermissions(t){var i,n,r,s,o;const a=this.permissions,c=t.canPublish!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublish)||t.canSubscribe!==(null===(n=this.permissions)||void 0===n?void 0:n.canSubscribe)||t.canPublishData!==(null===(r=this.permissions)||void 0===r?void 0:r.canPublishData)||t.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||t.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}));return this.permissions=t,c&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,a),c}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const i=this._connectionQuality;this._connectionQuality=function(t){switch(t){case Be.EXCELLENT:return e.ConnectionQuality.Excellent;case Be.GOOD:return e.ConnectionQuality.Good;case Be.POOR:return e.ConnectionQuality.Poor;default:return e.ConnectionQuality.Unknown}}(t),i!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTracks.forEach((t=>(t.track instanceof yo||t.track instanceof Zs)&&t.track.setAudioContext(e)))}addTrackPublication(t){t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const i=t;switch(i.track&&(i.track.sid=t.trackSid),this.tracks.set(t.trackSid,t),t.kind){case cr.Kind.Audio:this.audioTracks.set(t.trackSid,t);break;case cr.Kind.Video:this.videoTracks.set(t.trackSid,t)}}}class Co extends So{constructor(t,i,n){super(t,i.sid,i.name),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=e.VideoQuality.HIGH,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},this.handleVisibilityChange=e=>{a.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),{trackSid:this.trackSid}),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{a.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),{trackSid:this.trackSid}),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(i)}setSubscribed(t){const i=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const r=new dn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new dt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(i),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return!1===this.subscribed?So.SubscriptionStatus.Unsubscribed:super.isSubscribed?So.SubscriptionStatus.Subscribed:So.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?So.PermissionStatus.Allowed:So.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}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||(this.track instanceof ko&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&this.track instanceof ko&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(t){const i=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==t&&(r&&(r.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),r.off(e.TrackEvent.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,r)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(i))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const i=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):i!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const i=this.subscriptionStatus;t!==i&&this.emit(e.TrackEvent.SubscriptionStatusChanged,i,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return this.kind===cr.Kind.Video&&this.isAdaptiveStream?(a.warn("adaptive stream is enabled, cannot change video track settings",{trackSid:this.trackSid}),!1):!!this.isDesired||(a.warn("cannot update track settings when not subscribed",{trackSid:this.trackSid}),!1)}get isAdaptiveStream(){return this.track instanceof ko&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new un({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(t.width=Math.ceil(this.videoDimensions.width),t.height=Math.ceil(this.videoDimensions.height)):void 0!==this.currentVideoQuality?t.quality=this.currentVideoQuality:t.quality=e.VideoQuality.HIGH,this.emit(e.TrackEvent.UpdateSettings,t)}}class Po extends Eo{static fromParticipantInfo(e,t){return new Po(e,t.sid,t.identity,t.name,t.metadata)}constructor(e,t,i,n,r){super(t,i||"",n,r),this.signalClient=e,this.tracks=new Map,this.audioTracks=new Map,this.videoTracks=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{a.debug("send update settings",e),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,i)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,i)})),t.on(e.TrackEvent.Subscribed,(i=>{this.emit(e.ParticipantEvent.TrackSubscribed,i,t)})),t.on(e.TrackEvent.Unsubscribed,(i=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,i,t)})),t.on(e.TrackEvent.SubscriptionFailed,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,i)}))}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:cr.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrack(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:cr.Source.Microphone;const t=this.getTrack(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,i,n,r,s,o){let c=this.getTrackPublication(i);if(c||i.startsWith("TR")||this.tracks.forEach((e=>{c||t.kind!==e.kind.toString()||(c=e)})),!c)return 0===o?(a.error("could not find published track",{participant:this.sid,trackSid:i}),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i)):(void 0===o&&(o=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,i,n,r,s,o-1)}),150));if("ended"===t.readyState)return a.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",{participant:this.sid,trackSid:i}),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i);let d;return d="video"===t.kind?new ko(t,i,r,s):new yo(t,i,r,this.audioContext,this.audioOutput),d.source=c.source,d.isMuted=c.isMuted,d.setMediaStream(n),d.start(),c.setTrack(d),this.volumeMap.has(c.source)&&d instanceof yo&&d.setVolume(this.volumeMap.get(c.source)),c}get hasMetadata(){return!!this.participantInfo}getTrackPublication(e){return this.tracks.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const i=new Map,n=new Map;return t.tracks.forEach((e=>{var r;let s=this.getTrackPublication(e.sid);if(s)s.updateInfo(e);else{const i=cr.kindFromProto(e.type);if(!i)return;s=new Co(i,e,null===(r=this.signalClient.connectOptions)||void 0===r?void 0:r.autoSubscribe),s.updateInfo(e),n.set(e.sid,s);const o=Array.from(this.tracks.values()).find((e=>e.source===(null==s?void 0:s.source)));o&&s.source!==cr.Source.Unknown&&a.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),{oldTrack:o,newTrack:s,participant:this,participantInfo:t}),this.addTrackPublication(s)}i.set(e.sid,s)})),this.tracks.forEach((e=>{i.has(e.trackSid)||(a.trace("detected removed track on remote participant, unpublishing",{publication:e,participantSid:this.sid}),this.unpublishTrack(e.trackSid,!0))})),n.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,i){const n=this.tracks.get(t);if(!n)return;const{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.tracks.delete(t),n.kind){case cr.Kind.Audio:this.audioTracks.delete(t);break;case cr.Kind.Video:this.videoTracks.delete(t)}i&&this.emit(e.ParticipantEvent.TrackUnpublished,n)}setAudioOutput(e){return Tt(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTracks.forEach((i=>{var n;i.track instanceof yo&&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 a.trace("participant event",{participant:this.sid,event:e,args:i}),super.emit(e,...i)}}class Ro extends Eo{constructor(e,t,i,n){super(e,t),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Xe.NONE,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Gr)},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=>a.warn(e))),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.updateTrackSubscriptionPermissions=()=>{a.debug("updating track subscription permissions",{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 En({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):a.error("could not update mute status for unpublished track",e)},this.onTrackUpstreamPaused=e=>{a.debug("upstream paused"),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{a.debug("upstream resumed"),this.onTrackMuted(e,e.isMuted)},this.handleSubscribedQualityUpdate=e=>Tt(this,void 0,void 0,(function*(){var t,i,n,r,s,o;if(!(null===(s=this.roomOptions)||void 0===s?void 0:s.dynacast))return;const c=this.videoTracks.get(e.trackSid);if(c)if(e.subscribedCodecs.length>0){if(!c.videoTrack)return;const s=yield c.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var d,u=!0,l=wt(s);!(t=(d=yield l.next()).done);u=!0){r=d.value,u=!1;const e=r;Zn(e)&&(a.debug("publish ".concat(e," for ").concat(c.videoTrack.sid)),yield this.publishAdditionalCodecForTrack(c.videoTrack,e,c.options))}}catch(e){i={error:e}}finally{try{u||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(o=c.videoTrack)||void 0===o?void 0:o.setPublishingLayers(e.subscribedQualities));else a.warn("received subscribed quality update for unknown track",{method:"handleSubscribedQualityUpdate",sid:e.trackSid})})),this.handleLocalTrackUnpublished=e=>{const t=this.tracks.get(e.trackSid);t?this.unpublishTrack(t.track):a.warn("received unpublished event for unknown track",{method:"handleLocalTrackUnpublished",trackSid:e.trackSid})},this.handleTrackEnded=e=>Tt(this,void 0,void 0,(function*(){if(e.source===cr.Source.ScreenShare||e.source===cr.Source.ScreenShareAudio)a.debug("unpublishing local track due to TrackEnded",{track:e.sid}),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(e instanceof Zs||e instanceof po)try{if(Dr())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===cr.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw a.warn("user has revoked access to ".concat(e.source)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(a.debug("track ended, attempting to use a different device"),yield e.restartTrack())}catch(t){a.warn("could not restart track, muting instead"),yield e.mute()}})),this.audioTracks=new Map,this.videoTracks=new Map,this.tracks=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Xe.NONE}getTrack(e){const t=super.getTrack(e);if(t)return t}getTrackByName(e){const t=super.getTrackByName(e);if(t)return t}setupEngine(t){this.engine=t,this.engine.client.onRemoteMuteChanged=(e,t)=>{const i=this.tracks.get(e);i&&i.track&&(t?i.mute():i.unmute())},this.engine.client.onSubscribedQualityUpdate=this.handleSubscribedQualityUpdate,this.engine.client.onLocalTrackUnpublished=this.handleLocalTrackUnpublished,this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.SignalRestarted,this.handleReconnected).on(e.EngineEvent.SignalResumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.Disconnected,this.handleDisconnected)}setMetadata(e){var t;this.engine.client.sendUpdateLocalMetadata(e,null!==(t=this.name)&&void 0!==t?t:"")}setName(e){var t;this.engine.client.sendUpdateLocalMetadata(null!==(t=this.metadata)&&void 0!==t?t:"",e)}setCameraEnabled(e,t,i){return this.setTrackEnabled(cr.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(cr.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(cr.Source.ScreenShare,e,t,i)}setPermissions(t){const i=this.permissions,n=super.setPermissions(t);return n&&i&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,i),n}setE2EEEnabled(e){return Tt(this,void 0,void 0,(function*(){this.encryptionType=e?Xe.GCM:Xe.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,i,n,r){var s,o;return Tt(this,void 0,void 0,(function*(){a.debug("setTrackEnabled",{source:t,enabled:i});let c=this.getTrack(t);if(i)if(c)yield c.unmute();else{let i;if(this.pendingPublishing.has(t))return void a.info("skipping duplicate published source",{source:t});this.pendingPublishing.add(t);try{switch(t){case cr.Source.Camera:i=yield this.createTracks({video:null===(s=n)||void 0===s||s});break;case cr.Source.Microphone:i=yield this.createTracks({audio:null===(o=n)||void 0===o||o});break;case cr.Source.ScreenShare:i=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Bn(t)}const e=[];for(const t of i)a.info("publishing track",{localTrack:t}),e.push(this.publishTrack(t,r));const d=yield Promise.all(e);[c]=d}catch(t){throw null==i||i.forEach((e=>{e.stop()})),t instanceof Error&&!(t instanceof Bn)&&this.emit(e.ParticipantEvent.MediaDevicesError,t),t}finally{this.pendingPublishing.delete(t)}}else if(c&&c.track)if(t===cr.Source.ScreenShare){c=yield this.unpublishTrack(c.track);const e=this.getTrack(cr.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield c.mute();return c}))}enableCameraAndMicrophone(){return Tt(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(cr.Source.Camera)&&!this.pendingPublishing.has(cr.Source.Microphone)){this.pendingPublishing.add(cr.Source.Camera),this.pendingPublishing.add(cr.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(cr.Source.Camera),this.pendingPublishing.delete(cr.Source.Microphone)}}}))}createTracks(t){var i,n;return Tt(this,void 0,void 0,(function*(){const r=pr(lr(t,null===(i=this.roomOptions)||void 0===i?void 0:i.audioCaptureDefaults,null===(n=this.roomOptions)||void 0===n?void 0:n.videoCaptureDefaults));let s;try{s=yield navigator.mediaDevices.getUserMedia(r)}catch(e){throw e instanceof Error&&(r.audio&&(this.microphoneError=e),r.video&&(this.cameraError=e)),e}return r.audio&&(this.microphoneError=void 0,this.emit(e.ParticipantEvent.AudioStreamAcquired)),r.video&&(this.cameraError=void 0),s.getTracks().map((e=>{const i="audio"===e.kind;let n;i?t.audio:t.video;const o=i?r.audio:r.video;"boolean"!=typeof o&&(n=o);const a=$s(e,n);return a.kind===cr.Kind.Video?a.source=cr.Source.Camera:a.kind===cr.Kind.Audio&&(a.source=cr.Source.Microphone),a.mediaStream=s,a}))}))}createScreenTracks(t){return Tt(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Un("getDisplayMedia not supported");const i=fr(t),n=yield navigator.mediaDevices.getDisplayMedia(i),r=n.getVideoTracks();if(0===r.length)throw new Bn("no video track found");const s=new po(r[0],void 0,!1);s.source=cr.Source.ScreenShare;const o=[s];if(n.getAudioTracks().length>0){this.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new Zs(n.getAudioTracks()[0],void 0,!1,this.audioContext);t.source=cr.Source.ScreenShareAudio,o.push(t)}return o}))}publishTrack(e,t){var i,n,r,s;return Tt(this,void 0,void 0,(function*(){let o,c;if(yield null===(i=this.reconnectFuture)||void 0===i?void 0:i.promise,e instanceof gs&&this.pendingPublishPromises.has(e)&&(yield this.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)o=e.getConstraints();else{let t;switch(o=e.constraints,e.source){case cr.Source.Microphone:t="audioinput";break;case cr.Source.Camera:t="videoinput"}t&&this.activeDeviceMap.has(t)&&(o=Object.assign(Object.assign({},o),{deviceId:this.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Zs(e,o,!0,this.audioContext);break;case"video":e=new po(e,o,!0);break;default:throw new Bn("unsupported MediaStreamTrack kind ".concat(e.kind))}if(e instanceof Zs&&e.setAudioContext(this.audioContext),this.tracks.forEach((t=>{t.track&&t.track===e&&(c=t)})),c)return a.warn("track has already been published, skipping"),c;const d="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(n=null==t?void 0:t.forceStereo)&&void 0!==n?n:d;u&&(t||(t={}),void 0===t.dtx&&a.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work."),void 0===t.red&&a.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(r=t.dtx)&&void 0!==r||(t.dtx=!1),null!==(s=t.red)&&void 0!==s||(t.red=!1));const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),t);Rr()&&this.roomOptions.e2ee&&(a.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari"),l.simulcast=!1),l.source&&(e.source=l.source);const h=this.publish(e,l,u);this.pendingPublishPromises.set(e,h);try{return yield h}catch(e){throw e}finally{this.pendingPublishPromises.delete(e)}}))}publish(t,i,n){var r,s,o,c,d,u,l,h,p,m,f,v,g;return Tt(this,void 0,void 0,(function*(){Array.from(this.tracks.values()).find((e=>t instanceof gs&&e.source===t.source))&&t.source!==cr.Source.Unknown&&a.info("publishing a second track with the same source: ".concat(t.source)),i.stopMicTrackOnMute&&t instanceof Zs&&(t.stopOnMute=!0),t.source===cr.Source.ScreenShare&&Pr()&&(i.simulcast=!1),"av1"!==i.videoCodec||Tr()||(i.videoCodec=void 0),"vp9"!==i.videoCodec||Sr()||(i.videoCodec=void 0),void 0===i.videoCodec&&(i.videoCodec="vp8");const y=i.videoCodec;t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed);const k=new $i({cid:t.mediaStreamTrack.id,name:i.name,type:cr.kindToProto(t.kind),muted:t.isMuted,source:cr.sourceToProto(t.source),disableDtx:!(null===(r=i.dtx)||void 0===r||r),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(null===(s=i.red)||void 0===s||s),stream:null==i?void 0:i.stream});let b;if(t.kind===cr.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(t){const i=null!==(c=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==c?c:er.h720.resolution;e={width:i.width,height:i.height},a.error("could not determine track dimensions, using defaults",e)}k.width=e.width,k.height=e.height,t instanceof po&&(wr(y)&&(t.source===cr.Source.ScreenShare&&"vp9"===y&&(i.scalabilityMode="L1T3"),i.scalabilityMode=null!==(d=i.scalabilityMode)&&void 0!==d?d:"L3T3_KEY"),k.simulcastCodecs=[new Zi({codec:y,cid:t.mediaStreamTrack.id})],i.backupCodec&&y!==i.backupCodec.codec&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),k.simulcastCodecs.push(new Zi({codec:i.backupCodec.codec,cid:""})))),b=ao(t.source===cr.Source.ScreenShare,k.width,k.height,i),k.layers=vo(k.width,k.height,b,wr(i.videoCodec))}else t.kind===cr.Kind.Audio&&(b=[{maxBitrate:null!==(l=null===(u=i.audioPreset)||void 0===u?void 0:u.maxBitrate)&&void 0!==l?l:i.audioBitrate,priority:null!==(p=null===(h=i.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==p?p:"high",networkPriority:null!==(f=null===(m=i.audioPreset)||void 0===m?void 0:m.priority)&&void 0!==f?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Jn("cannot publish track when not connected");const T=yield this.engine.addTrack(k);let S;if(T.codecs.forEach((e=>{void 0===S&&(S=e.mimeType)})),S&&t.kind===cr.Kind.Video){const e=vr(S);e!==y&&(a.debug("falling back to server selected codec",{codec:e}),i.videoCodec=e,b=ao(t.source===cr.Source.ScreenShare,k.width,k.height,i))}const w=new wo(t.kind,T,t);if(w.options=i,t.sid=T.sid,!this.engine.publisher)throw new Jn("publisher is closed");if(a.debug("publishing ".concat(t.kind," with encodings"),{encodings:b,trackInfo:T}),t.sender=yield this.engine.createSender(t,i,b),b)if(Pr()&&t.kind===cr.Kind.Audio){let e;for(const i of this.engine.publisher.getTransceivers())if(i.sender===t.sender){e=i;break}e&&this.engine.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(v=b[0])||void 0===v?void 0:v.maxBitrate)?b[0].maxBitrate/1e3:0})}else t.codec&&wr(t.codec)&&(null===(g=b[0])||void 0===g?void 0:g.maxBitrate)&&this.engine.publisher.setTrackCodecBitrate({cid:k.cid,codec:t.codec,maxbr:b[0].maxBitrate/1e3});return yield this.engine.negotiate(),t instanceof po?t.startMonitor(this.engine.client):t instanceof Zs&&t.startMonitor(),this.addTrackPublication(w),this.emit(e.ParticipantEvent.LocalTrackPublished,w),w}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){var n;return Tt(this,void 0,void 0,(function*(){let r;if(this.tracks.forEach((t=>{t.track&&t.track===e&&(r=t)})),!r)throw new Bn("track is not published");if(!(e instanceof po))throw new Bn("track is not a video track");const s=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,r,s,o;if(!i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&a.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const c=e.mediaStreamTrack.getSettings(),d=null!==(n=c.width)&&void 0!==n?n:null===(r=e.dimensions)||void 0===r?void 0:r.width,u=null!==(s=c.height)&&void 0!==s?s:null===(o=e.dimensions)||void 0===o?void 0:o.height;return ao(e.source===cr.Source.ScreenShare,d,u,i)}(e,t,s);if(!o)return void a.info("backup codec has been disabled, ignoring request to add additional codec for track");const c=e.addSimulcastTrack(t,o),d=new $i({cid:c.mediaStreamTrack.id,type:cr.kindToProto(e.kind),muted:e.isMuted,source:cr.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=vo(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new Jn("cannot publish track when not connected");const u=yield this.engine.addTrack(d);yield this.engine.createSimulcastSender(e,c,s,o),yield this.engine.negotiate(),a.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:u})}))}unpublishTrack(t,i){var n,r;return Tt(this,void 0,void 0,(function*(){const s=this.getPublicationForTrack(t);if(a.debug("unpublishing track",{track:t,method:"unpublishTrack"}),!s||!s.track)return void a.warn("track was not unpublished because no publication was found",{track:t,method:"unpublishTrack"});(t=s.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),void 0===i&&(i=null===(r=null===(n=this.roomOptions)||void 0===n?void 0:n.stopLocalTrackOnUnpublish)||void 0===r||r),i&&t.stop();let o=!1;const c=t.sender;if(t.sender=void 0,this.engine.publisher&&"closed"!==this.engine.publisher.getConnectionState()&&c)try{for(const e of this.engine.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),t instanceof po){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(o=!0),e.sender=void 0);t.simulcastCodecs.clear()}}catch(e){a.warn("failed to unpublish track",{error:e,method:"unpublishTrack"})}switch(this.tracks.delete(s.trackSid),s.kind){case cr.Kind.Audio:this.audioTracks.delete(s.trackSid);break;case cr.Kind.Video:this.videoTracks.delete(s.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return Tt(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>e instanceof wo))}))}republishAllTracks(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Tt(this,void 0,void 0,(function*(){const i=[];this.tracks.forEach((t=>{t.track&&(e&&(t.options=Object.assign(Object.assign({},t.options),e)),i.push(t))})),yield Promise.all(i.map((e=>Tt(this,void 0,void 0,(function*(){const i=e.track;yield this.unpublishTrack(i,!1),t&&!i.isMuted&&(i instanceof Zs||i instanceof po)&&!i.isUserProvided&&(a.debug("restarting existing track",{track:e.trackSid}),yield i.restartTrack()),yield this.publishTrack(i,e.options)})))))}))}publishData(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return Tt(this,void 0,void 0,(function*(){const n=Array.isArray(i)?i:null==i?void 0:i.destination,r=[],s=Array.isArray(i)?void 0:i.topic;void 0!==n&&n.forEach((e=>{e instanceof Po?r.push(e.sid):r.push(e)}));const o=new st({kind:t,value:{case:"user",value:new ct({participantSid:this.sid,payload:e,destinationSids:r,topic:s})}});yield this.engine.sendDataPacket(o,t)}))}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isConnected&&this.updateTrackSubscriptionPermissions()}updateInfo(e){return e.sid===this.sid&&(!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.tracks.get(e.sid);if(n){const r=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;r!==e.muted&&(a.debug("updating server mute state after reconcile",{sid:e.sid,muted:r}),this.engine.client.sendMuteTrack(e.sid,r))}})),!0))}getPublicationForTrack(e){let t;return this.tracks.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(n instanceof Zs||n instanceof po)&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}publishedTracksInfo(){const e=[];return this.tracks.forEach((t=>{void 0!==t.track&&e.push(new sn({cid:t.track.mediaStreamID,track:t.trackInfo}))})),e}dataChannelsInfo(){const t=[],i=(e,i)=>{void 0!==(null==e?void 0:e.id)&&null!==e.id&&t.push(new In({label:e.label,id:e.id,target:i}))};return i(this.engine.dataChannelForKind(e.DataPacket_Kind.LOSSY),Wi.PUBLISHER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.RELIABLE),Wi.PUBLISHER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.LOSSY,!0),Wi.SUBSCRIBER),i(this.engine.dataChannelForKind(e.DataPacket_Kind.RELIABLE,!0),Wi.SUBSCRIBER),t}}var Io;e.ConnectionState=void 0,(Io=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Io.Connecting="connecting",Io.Connected="connected",Io.Reconnecting="reconnecting";const Do=e.ConnectionState;class _o extends Jt.EventEmitter{constructor(t){var i,n;super(),i=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.connect=(t,i,n)=>Tt(this,void 0,void 0,(function*(){var r;const s=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return a.info("already connected to room ".concat(this.name)),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.getServerUrl().toString())!==t&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Lr(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Qs(t,i):this.regionUrlProvider.updateToken(i),this.regionUrlProvider.fetchRegionSettings().catch((e=>{a.warn("could not fetch region settings",{error:e})})));const o=(e,r,c)=>Tt(this,void 0,void 0,(function*(){var d;this.abortController&&this.abortController.abort();const u=new AbortController;this.abortController=u,null==s||s();try{yield this.attemptConnection(null!=c?c:t,i,n,u),this.abortController=void 0,e()}catch(t){if(this.regionUrlProvider&&t instanceof xn&&3!==t.reason&&0!==t.reason){let i=null;try{i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(d=this.abortController)||void 0===d?void 0:d.signal)}catch(e){if(e instanceof xn&&(401===e.status||3===e.reason))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void r(e)}i?(a.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i)),yield o(e,r,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),r(t))}else this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),r(t)}})),c=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Gr(((e,t)=>{o(e,t,c)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,r,s)=>Tt(this,void 0,void 0,(function*(){const o=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,publishOnly:n.publishOnly,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},s.signal);let c=o.serverInfo;if(c||(c={version:o.serverVersion,region:o.serverRegion}),a.debug("connected to Livekit Server ".concat(Object.entries(c).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", "))),!o.serverVersion)throw new Fn("unknown server version");return"0.15.1"===o.serverVersion&&this.options.dynacast&&(a.debug("disabling dynacast due to server version"),r.dynacast=!1),o})),this.applyJoinResponse=e=>{const t=e.participant;this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room),this.options.e2ee&&this.e2eeManager&&this.e2eeManager.setSifTrailer(e.sifTrailer)},this.attemptConnection=(t,i,n,r)=>Tt(this,void 0,void 0,(function*(){var s,o;this.state===e.ConnectionState.Reconnecting?(a.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine()):this.maybeCreateEngine(),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Vs),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(t,i,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=new xn("could not establish signal connection");throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof xn&&(t.reason=e.reason,t.status=e.status),a.debug("error trying to establish signal connection",{error:e}),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new xn("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}Dr()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Dr()&&(document.addEventListener("freeze",this.onPageLeave),null===(o=navigator.mediaDevices)||void 0===o||o.addEventListener("devicechange",this.handleDeviceChange)),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Tt(i,void 0,void 0,(function*(){var i,n,r,s;const o=yield this.disconnectLock.lock();try{if(this.state===e.ConnectionState.Disconnected)return void a.debug("already disconnected");a.info("disconnect from room",{identity:this.localParticipant.identity}),this.state!==e.ConnectionState.Connecting&&this.state!==e.ConnectionState.Reconnecting||(a.warn("abort connection attempt"),null===(i=this.abortController)||void 0===i||i.abort(),null===(r=null===(n=this.connectFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,new xn("Client initiated disconnect")),this.connectFuture=void 0),(null===(s=this.engine)||void 0===s?void 0:s.client.isConnected)&&(yield this.engine.client.sendLeave()),this.engine&&(yield this.engine.close()),this.handleDisconnect(t,e.DisconnectReason.CLIENT_INITIATED),this.engine=void 0}finally{o()}}))},this.onPageLeave=()=>Tt(this,void 0,void 0,(function*(){yield this.disconnect()})),this.startAudio=()=>Tt(this,void 0,void 0,(function*(){const t=[],i=Wn();if(i&&"iOS"===i.os){const i="livekit-dummy-audio-el";let n=document.getElementById(i);if(!n){n=document.createElement("audio"),n.id=i,n.autoplay=!0,n.hidden=!0;const t=Wr();t.enabled=!0;const r=new MediaStream([t]);n.srcObject=r,document.addEventListener("visibilitychange",(()=>{n&&(n.srcObject=document.hidden?null:r)})),document.body.append(n),this.once(e.RoomEvent.Disconnected,(()=>{null==n||n.remove()}))}t.push(n)}this.participants.forEach((e=>{e.audioTracks.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}})),this.handleRestarting=()=>{this.clearConnectionReconcile();for(const e of this.participants.values())this.handleParticipantDisconnected(e.sid,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=t=>Tt(this,void 0,void 0,(function*(){a.debug("signal reconnected to server",{region:t.serverRegion}),this.cachedParticipantSids=[],this.applyJoinResponse(t);try{const e=[];this.localParticipant.tracks.forEach((t=>{t.track&&e.push(t)})),yield Promise.all(e.map((e=>Tt(this,void 0,void 0,(function*(){const t=e.track;this.localParticipant.unpublishTrack(t,!1),t.isMuted||((t instanceof Zs||t instanceof po)&&t.source!==cr.Source.ScreenShare&&t.source!==cr.Source.ScreenShareAudio&&!t.isUserProvided&&(a.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),a.debug("publishing new track",{track:e.trackSid}),yield this.localParticipant.publishTrack(t,e.options))})))))}catch(e){a.error("error trying to re-publish tracks after reconnection",{error:e})}try{yield this.engine.waitForRestarted(),a.debug("fully reconnected to server",{region:t.serverRegion})}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.participants.forEach((t=>{this.emit(e.RoomEvent.ParticipantConnected,t)}))})),this.handleParticipantUpdates=e=>{e.forEach((e=>{if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);const t=this.identityToSid.get(e.identity);t&&t!==e.sid&&this.handleParticipantDisconnected(t,this.participants.get(t));let i=this.participants.get(e.sid);const n=!i;e.state===Ye.DISCONNECTED?this.handleParticipantDisconnected(e.sid,i):(i=this.getOrCreateParticipant(e.sid,e),n||i.updateInfo(e))}))},this.handleActiveSpeakersUpdate=t=>{const i=[],n={};t.forEach((e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),i.push(this.localParticipant);else{const t=this.participants.get(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),i.push(t))}})),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.participants.forEach((e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleSpeakersChanged=t=>{const i=new Map;this.activeSpeakers.forEach((e=>{i.set(e.sid,e)})),t.forEach((e=>{let t=this.participants.get(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?i.set(e.sid,t):i.delete(e.sid))}));const n=Array.from(i.values());n.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const i=this.participants.get(t.participantSid);if(!i)return;const n=i.getTrackPublication(t.trackSid);n&&n.track&&(n.track.streamState=cr.streamStateFromProto(t.state),i.emit(e.ParticipantEvent.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,n,n.track.streamState,i))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.participants.get(e.participantSid);if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.participants.values()).find((t=>t.tracks.has(e.trackSid)));if(!t)return;const i=t.getTrackPublication(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=(t,i)=>{const n=this.participants.get(t.participantSid);this.emit(e.RoomEvent.DataReceived,t.payload,n,i,t.topic),null==n||n.emit(e.ParticipantEvent.DataReceived,t.payload,i)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{a.warn("could not playback audio",t),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Tt(this,void 0,void 0,(function*(){this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const i=this.roomInfo;this.roomInfo=t,i&&i.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==i?void 0:i.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.participants.get(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onLocalTrackPublished=t=>Tt(this,void 0,void 0,(function*(){var i;if(this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),t.track instanceof Zs){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const n=yield null===(i=t.track)||void 0===i?void 0:i.getDeviceId(),r=(s=t.source)===cr.Source.Microphone?"audioinput":s===cr.Source.Camera?"videoinput":void 0;var s;r&&n&&n!==this.localParticipant.activeDeviceMap.get(r)&&(this.localParticipant.activeDeviceMap.set(r,n),this.emit(e.RoomEvent.ActiveDeviceChanged,r,n))})),this.onLocalTrackUnpublished=t=>{this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=t=>{this.emit(e.RoomEvent.MediaDevicesError,t)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.setMaxListeners(100),this.participants=new Map,this.cachedParticipantSids=[],this.identityToSid=new Map,this.options=Object.assign(Object.assign({},js),t),this.options.audioCaptureDefaults=Object.assign(Object.assign({},Fs),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Js),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Bs),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Hr,this.localParticipant=new Ro("","",this.engine,this.options),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",zr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",zr(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",zr(this.options.audioOutput.deviceId)),this.options.e2ee&&this.setupE2EE()}setE2EEEnabled(e){return Tt(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 t;this.options.e2ee&&(this.e2eeManager=new ys(this.options.e2ee),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,i)=>{i instanceof Ro&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,i)})),this.e2eeManager.on(e.EncryptionEvent.EncryptionError,(t=>this.emit(e.RoomEvent.EncryptionError,t))),null===(t=this.e2eeManager)||void 0===t||t.setup(this))}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}get sid(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.sid)&&void 0!==t?t:""}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 Hs(this.options),this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting),this.cachedParticipantSids=Array.from(this.participants.keys())})).on(e.EngineEvent.Resumed,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.updateSubscriptions();Array.from(this.participants.values()).filter((e=>!this.cachedParticipantSids.includes(e.sid))).forEach((t=>this.emit(e.RoomEvent.ParticipantConnected,t))),this.cachedParticipantSids=[]})).on(e.EngineEvent.SignalResumed,(()=>{this.state===e.ConnectionState.Reconnecting&&this.sendSyncState()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.DCBufferStatusChanged,((t,i)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,i)})),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 vs.getInstance().getDevices(e,t)}prepareConnection(t,i){return Tt(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){a.debug("prepareConnection to ".concat(t));try{if(Lr(new URL(t))&&i){this.regionUrlProvider=new Qs(t,i);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=n,yield fetch(Qr(n),{method:"HEAD"}),a.debug("prepared connection to ".concat(n)))}else yield fetch(Qr(t),{method:"HEAD"})}catch(e){a.warn("could not prepare connection",{error:e})}}}))}getParticipantByIdentity(e){if(this.localParticipant.identity===e)return this.localParticipant;const t=this.identityToSid.get(e);return t?this.participants.get(t):void 0}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(t,i){return Tt(this,void 0,void 0,(function*(){let n,r=()=>{};switch(t){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":n=new Dn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new Dn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new Dn({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new Dn({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":n=new Dn({scenario:{case:"switchCandidateProtocol",value:"force-tls"===t?2:1}}),r=()=>Tt(this,void 0,void 0,(function*(){const t=this.engine.client.onLeave;t&&t(new ln({reason:e.DisconnectReason.CLIENT_INITIATED,canReconnect:!0}))}));break;case"subscriber-bandwidth":if(void 0===i||"number"!=typeof i)throw new Error("subscriber-bandwidth requires a number as argument");n=new Dn({scenario:{case:"subscriberBandwidth",value:BigInt(i)}})}n&&(this.engine.client.sendSimulateScenario(n),r())}))}get canPlaybackAudio(){return this.audioEnabled}getActiveAudioOutputDevice(){var e,t;return null!==(t=null===(e=this.options.audioOutput)||void 0===e?void 0:e.deviceId)&&void 0!==t?t:""}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,i){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var r,s,o;return Tt(this,void 0,void 0,(function*(){let a=!1,c=!0;const d=n?{exact:i}:i;if("audioinput"===t){const e=this.options.audioCaptureDefaults.deviceId;this.options.audioCaptureDefaults.deviceId=d,a=e!==d;const t=Array.from(this.localParticipant.audioTracks.values()).filter((e=>e.source===cr.Source.Microphone));try{c=(yield Promise.all(t.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(d)})))).every((e=>!0===e))}catch(t){throw this.options.audioCaptureDefaults.deviceId=e,t}}else if("videoinput"===t){const e=this.options.videoCaptureDefaults.deviceId;this.options.videoCaptureDefaults.deviceId=d,a=e!==d;const t=Array.from(this.localParticipant.videoTracks.values()).filter((e=>e.source===cr.Source.Camera));try{c=(yield Promise.all(t.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(d)})))).every((e=>!0===e))}catch(t){throw this.options.videoCaptureDefaults.deviceId=e,t}}else if("audiooutput"===t){if(!Er()&&!this.options.expWebAudioMix||this.options.expWebAudioMix&&this.audioContext&&!("setSinkId"in this.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");null!==(r=(o=this.options).audioOutput)&&void 0!==r||(o.audioOutput={});const e=this.options.audioOutput.deviceId;this.options.audioOutput.deviceId=i,a=e!==d;try{this.options.expWebAudioMix?null===(s=this.audioContext)||void 0===s||s.setSinkId(i):yield Promise.all(Array.from(this.participants.values()).map((e=>e.setAudioOutput({deviceId:i}))))}catch(t){throw this.options.audioOutput.deviceId=e,t}}return a&&c&&(this.localParticipant.activeDeviceMap.set(t,i),this.emit(e.RoomEvent.ActiveDeviceChanged,t,i)),c}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.participants.clear(),this.maybeCreateEngine()}onTrackAdded(t,i,n){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const r=()=>{this.onTrackAdded(t,i,n),s()},s=()=>{this.off(e.RoomEvent.Reconnected,r),this.off(e.RoomEvent.Connected,r),this.off(e.RoomEvent.Disconnected,s)};return this.once(e.RoomEvent.Reconnected,r),this.once(e.RoomEvent.Connected,r),void this.once(e.RoomEvent.Disconnected,s)}if(this.state===e.ConnectionState.Disconnected)return void a.warn("skipping incoming track after Room disconnected");const r=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(i.id),s=r[0];let o=r[1],c=t.id;if(o&&o.startsWith("TR")&&(c=o),s===this.localParticipant.sid)return void a.warn("tried to create RemoteParticipant for local participant");const d=this.participants.get(s);if(!d)return void a.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s));let u;this.options.adaptiveStream&&(u="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),d.addSubscribedMediaTrack(t,c,i,n,u)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.state!==e.ConnectionState.Disconnected){this.regionUrl=void 0;try{this.participants.forEach((e=>{e.tracks.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.tracks.forEach((e=>{var i,n;e.track&&this.localParticipant.unpublishTrack(e.track,t),t&&(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop())})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).off(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.tracks.clear(),this.localParticipant.videoTracks.clear(),this.localParticipant.audioTracks.clear(),this.participants.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.expWebAudioMix&&(this.audioContext.close(),this.audioContext=void 0),Dr()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=navigator.mediaDevices)||void 0===n||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,i)}}}handleParticipantDisconnected(t,i){this.participants.delete(t),i&&(this.identityToSid.delete(i.identity),i.tracks.forEach((e=>{i.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,i))}acquireAudioContext(){var t,i;return Tt(this,void 0,void 0,(function*(){if("boolean"!=typeof this.options.expWebAudioMix&&this.options.expWebAudioMix.audioContext?this.audioContext=this.options.expWebAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(t=mr())&&void 0!==t?t:void 0),this.audioContext&&"suspended"===this.audioContext.state)try{yield this.audioContext.resume()}catch(e){a.warn(e)}this.options.expWebAudioMix&&this.participants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext);const n="running"===(null===(i=this.audioContext)||void 0===i?void 0:i.state);n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,n))}))}createParticipant(e,t){let i;return i=t?Po.fromParticipantInfo(this.engine.client,t):new Po(this.engine.client,e,"",void 0,void 0),this.options.expWebAudioMix&&i.setAudioContext(this.audioContext),i}getOrCreateParticipant(t,i){if(this.participants.has(t))return this.participants.get(t);const n=this.createParticipant(t,i);return this.participants.set(t,n),this.identityToSid.set(i.identity,i.sid),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,n),n.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,n)})).on(e.ParticipantEvent.TrackSubscribed,((t,i)=>{t.kind===cr.Kind.Audio&&(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)),this.emit(e.RoomEvent.TrackSubscribed,t,i,n)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,n)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,i)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,(t=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,n)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,n)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,n)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,n)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,n)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,n)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,i)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,i,n)})),i&&n.updateInfo(i),n}sendSyncState(){var e,t,i,n;const r=null===(e=this.engine.subscriber)||void 0===e?void 0:e.getLocalDescription(),s=null===(t=this.engine.subscriber)||void 0===t?void 0:t.getRemoteDescription();if(!r)return;const o=null===(n=null===(i=this.connOptions)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=new Array;this.participants.forEach((e=>{e.tracks.forEach((e=>{e.isDesired!==o&&a.push(e.trackSid)}))})),this.engine.client.sendSyncState(new Rn({answer:ts({sdp:r.sdp,type:r.type}),offer:s?ts({sdp:s.sdp,type:s.type}):void 0,subscription:new dn({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:this.localParticipant.publishedTracksInfo(),dataChannels:this.localParticipant.dataChannelsInfo()}))}updateSubscriptions(){for(const e of this.participants.values())for(const t of e.videoTracks.values())t.isSubscribed&&t instanceof Co&&t.emitTrackUpdate()}registerConnectionReconcile(){this.clearConnectionReconcile();let t=0;this.connectionReconcileInterval=Vn.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?t=0:(t++,a.warn("detected connection state mismatch",{numFailures:t}),t>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e.DisconnectReason.STATE_MISMATCH)))}),2e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Vn.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitWhenConnected(t){if(this.state===e.ConnectionState.Connected){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this.emit(t,...n)}return!1}simulateParticipants(t){var i,n;return Tt(this,void 0,void 0,(function*(){const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new We({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:x.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Qe({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected),r.video){const t=new wo(cr.Kind.Video,new nt({source:xe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Me.AUDIO,name:"video-dummy"}),new po(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Kr(null!==(i=160*s.aspectRatios[0])&&void 0!==i?i:1,160,!0,!0)));this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(r.audio){const t=new wo(cr.Kind.Audio,new nt({source:xe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Me.AUDIO}),new Zs(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Wr()));this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<s.count-1;e+=1){let t=new Qe({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:Ye.ACTIVE,tracks:[],joinedAt:x.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=Kr(null!==(n=160*s.aspectRatios[e%s.aspectRatios.length])&&void 0!==n?n:1,160,!1,!0),o=new nt({source:xe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Me.AUDIO});i.addSubscribedMediaTrack(r,o.sid,new MediaStream([r])),t.tracks=[...t.tracks,o]}if(s.audio){const e=Wr(),n=new nt({source:xe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Me.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e])),t.tracks=[...t.tracks,n]}i.updateInfo(t)}}))}emit(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return t!==e.RoomEvent.ActiveSpeakersChanged&&a.debug("room event ".concat(t),{event:t,args:n}),super.emit(t,...n)}}var Lo;!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(Lo||(Lo={}));class No extends Jt.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=Lo.IDLE,this.logs=[],this.errorsAsWarnings=!1,this.url=e,this.token=t,this.name=this.constructor.name,this.room=new _o(i.roomOptions),this.connectOptions=i.connectOptions,i.errorsAsWarnings&&(this.errorsAsWarnings=i.errorsAsWarnings)}run(e){return Tt(this,void 0,void 0,(function*(){if(this.status!==Lo.IDLE)throw Error("check is running already");this.setStatus(Lo.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==Lo.SKIPPED&&this.setStatus(this.isSuccess()?Lo.SUCCESS:Lo.FAILED),e&&e(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(){return Tt(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(yield this.room.connect(this.url,this.token)),this.room}))}disconnect(){return Tt(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(Lo.SKIPPED)}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}function Ao(e){var t,i;return Tt(this,void 0,void 0,(function*(){null!=e||(e={}),null!==(t=e.audio)&&void 0!==t||(e.audio=!0),null!==(i=e.video)&&void 0!==i||(e.video=!0);const n=pr(lr(e,Fs,Js)),r=navigator.mediaDevices.getUserMedia(n);e.audio&&(vs.userMediaPromiseMap.set("audioinput",r),r.catch((()=>vs.userMediaPromiseMap.delete("audioinput")))),e.video&&(vs.userMediaPromiseMap.set("videoinput",r),r.catch((()=>vs.userMediaPromiseMap.delete("videoinput"))));const s=yield r;return s.getTracks().map((t=>{const i="audio"===t.kind;let r;i?e.audio:e.video;const o=i?n.audio:n.video;"boolean"!=typeof o&&(r=o),r?r.deviceId=t.getSettings().deviceId:r={deviceId:t.getSettings().deviceId};const a=$s(t,r);return a.kind===cr.Kind.Video?a.source=cr.Source.Camera:a.kind===cr.Kind.Audio&&(a.source=cr.Source.Microphone),a.mediaStream=s,a}))}))}function Oo(e){return Tt(this,void 0,void 0,(function*(){return(yield Ao({audio:!1,video:e}))[0]}))}function Mo(e){return Tt(this,void 0,void 0,(function*(){return(yield Ao({audio:e,video:!1}))[0]}))}class xo extends No{get description(){return"Can publish audio"}perform(){var e;return Tt(this,void 0,void 0,(function*(){const t=yield this.connect(),i=yield Mo();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let r=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"audio"===e.mediaType&&(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))}))}}class Uo extends No{get description(){return"Can publish video"}perform(){var e;return Tt(this,void 0,void 0,(function*(){const t=yield this.connect(),i=yield Oo();t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let r=0;if(n.forEach((e=>{"outbound-rtp"===e.type&&"video"===e.mediaType&&(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))}))}}class Bo extends No{get description(){return"Resuming connection after interruption"}perform(){var t;return Tt(this,void 0,void 0,(function*(){const i=yield this.connect();let n,r=!1,s=!1;const o=new Promise((e=>{setTimeout(e,5e3),n=e}));i.on(e.RoomEvent.Reconnecting,(()=>{r=!0})).on(e.RoomEvent.Reconnected,(()=>{s=!0,n(!0)})),null===(t=i.engine.client.ws)||void 0===t||t.close();const a=i.engine.client.onClose;if(a&&a(""),yield o,!r)throw new Error("Did not attempt to reconnect");if(!s||i.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class Fo extends No{get description(){return"Can connect via TURN"}perform(){var e,t;return Tt(this,void 0,void 0,(function*(){const i=new $r,n=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,s=!1,o=!1;for(let e of n.iceServers)for(let t of e.urls)t.startsWith("turn:")?(s=!0,o=!0):t.startsWith("turns:")&&(s=!0,o=!0,r=!0),t.startsWith("stun:")&&(o=!0);o?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class Jo extends No{get description(){return"Establishing WebRTC connection"}perform(){return Tt(this,void 0,void 0,(function*(){let t=!1,i=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{const e=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(n,r)=>{if(n.candidate){const e=new RTCIceCandidate(n);let r="".concat(e.protocol," ").concat(e.address,":").concat(e.port," ").concat(e.type);e.address&&(!function(e){const t=e.split(".");if(4===t.length){if("10"===t[0])return!0;if("192"===t[0]&&"168"===t[1])return!0;if("172"===t[0]){const e=parseInt(t[1],10);if(e>=16&&e<=31)return!0}}return!1}(e.address)?"tcp"===e.protocol&&"passive"===e.tcpType?(t=!0,r+=" (passive)"):"udp"===e.protocol&&(i=!0):r+=" (private)"),this.appendMessage(r)}e&&e(n,r)},this.room.engine.subscriber&&(this.room.engine.subscriber.onIceCandidateError=e=>{e instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(e.errorCode," ").concat(e.errorText," ").concat(e.url))})}));try{yield this.connect(),a.info("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}t||this.appendWarning("Server is not configured for ICE/TCP"),i||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class jo extends No{get description(){return"Connecting to signal connection via WebSocket"}perform(){var e,t,i;return Tt(this,void 0,void 0,(function*(){(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let n=new $r;const r=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),(null===(e=r.serverInfo)||void 0===e?void 0:e.edition)===$e.Cloud&&(null===(t=r.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(i=r.serverInfo)||void 0===i?void 0:i.region)),yield n.close()}))}}class Vo extends Jt.EventEmitter{constructor(e,t){super(),this.checkResults=new Map,this.url=e,this.token=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Lo.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((e=>e.status!==Lo.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return Tt(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token),n=e=>{this.updateCheck(t,e)};i.on("update",n);const r=yield i.run();return i.off("update",n),r}))}checkWebsocket(){return Tt(this,void 0,void 0,(function*(){return this.createAndRunCheck(jo)}))}checkWebRTC(){return Tt(this,void 0,void 0,(function*(){return this.createAndRunCheck(Jo)}))}checkTURN(){return Tt(this,void 0,void 0,(function*(){return this.createAndRunCheck(Fo)}))}checkReconnect(){return Tt(this,void 0,void 0,(function*(){return this.createAndRunCheck(Bo)}))}checkPublishAudio(){return Tt(this,void 0,void 0,(function*(){return this.createAndRunCheck(xo)}))}checkPublishVideo(){return Tt(this,void 0,void 0,(function*(){return this.createAndRunCheck(Uo)}))}}const qo=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),Ko=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function Wo(e){var t;const i=e.trim().toLowerCase();if(""!==i)return qo.has(i)?qo.get(i):null===(t=Array.from(Ko.entries()).find((e=>{let[t]=e;return i.includes(t)})))||void 0===t?void 0:t[1]}e.BaseKeyProvider=ps,e.ConnectionCheck=Vo,e.ConnectionError=xn,e.CriticalTimers=Vn,e.DefaultReconnectPolicy=bt,e.DeviceUnsupportedError=Un,e.ExternalE2EEKeyProvider=class extends ps{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(Object.assign(Object.assign({},e),{sharedKey:!0,ratchetWindowSize:0,failureTolerance:-1}))}setKey(e){return Tt(this,void 0,void 0,(function*(){const t="string"==typeof e?yield us(e):yield ls(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=Mn,e.LocalAudioTrack=Zs,e.LocalParticipant=Ro,e.LocalTrack=gs,e.LocalTrackPublication=wo,e.LocalVideoTrack=po,e.NegotiationError=jn,e.Participant=Eo,e.PublishDataError=class extends Mn{constructor(e){super(13,null!=e?e:"unable to publish data")}},e.RemoteAudioTrack=yo,e.RemoteParticipant=Po,e.RemoteTrack=go,e.RemoteTrackPublication=Co,e.RemoteVideoTrack=ko,e.Room=_o,e.RoomState=Do,e.ScreenSharePresets=ir,e.Track=cr,e.TrackInvalidError=Bn,e.TrackPublication=So,e.UnexpectedConnectionState=Jn,e.UnsupportedServer=Fn,e.VideoPreset=Qn,e.VideoPresets=er,e.VideoPresets43=tr,e.attachToElement=dr,e.createAudioAnalyser=function(e,t){const i=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=mr();if(!n)throw new Error("Audio Context not supported on this browser");const r=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,s=n.createMediaStreamSource(new MediaStream([r])),o=n.createAnalyser();o.minDecibels=i.minDecibels,o.maxDecibels=i.maxDecibels,o.fftSize=i.fftSize,o.smoothingTimeConstant=i.smoothingTimeConstant,s.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:o,cleanup:()=>Tt(this,void 0,void 0,(function*(){yield n.close(),i.cloneTrack&&r.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=ls,e.createKeyMaterialFromString=us,e.createLocalAudioTrack=Mo,e.createLocalScreenTracks=function(e){return Tt(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===e.resolution&&(e.resolution=ir.h1080fps15.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new Un("getDisplayMedia not supported");const t=fr(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new Bn("no video track found");const r=new po(n[0],void 0,!1);r.source=cr.Source.ScreenShare;const s=[r];if(i.getAudioTracks().length>0){const e=new Zs(i.getAudioTracks()[0],void 0,!1);e.source=cr.Source.ScreenShareAudio,s.push(e)}return s}))},e.createLocalTracks=Ao,e.createLocalVideoTrack=Oo,e.deriveKeys=function(e,t){return Tt(this,void 0,void 0,(function*(){const i=hs(e.algorithm.name,t),n=yield crypto.subtle.deriveKey(i,e,{name:is,length:128},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:n}}))},e.detachTrack=ur,e.facingModeFromDeviceLabel=Wo,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;const n=e instanceof gs?e.mediaStreamTrack:e,r=n.getSettings();let s={facingMode:null!==(i=t.defaultFacingMode)&&void 0!==i?i:"user",confidence:"low"};if("facingMode"in r){const e=r.facingMode;a.debug("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(s={facingMode:e,confidence:"high"})}if(["low","medium"].includes(s.confidence)){a.debug("Try to get facing mode from device label: (".concat(n.label,")"));const e=Wo(n.label);void 0!==e&&(s=e)}return s},e.getEmptyAudioStreamTrack=Wr,e.getEmptyVideoStreamTrack=function(){return Vr||(Vr=Kr()),Vr.clone()},e.importKey=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:is},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return Tt(this,void 0,void 0,(function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===i?["deriveBits","deriveKey"]:["encrypt","decrypt"])}))},e.isBackupCodec=Zn,e.isBrowserSupported=function(){return kr()||br()},e.isE2EESupported=as,e.isInsertableStreamSupported=ds,e.isScriptTransformSupported=cs,e.isVideoFrame=function(e){return"type"in e},e.needsRbspUnescaping=function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1},e.parseRbsp=function(e){const t=[];for(var i=e.length,n=0;n<e.length;)i-n>=3&&!e[n]&&!e[n+1]&&3==e[n+2]?(t.push(e[n++]),t.push(e[n++]),n++):t.push(e[n++]);return new Uint8Array(t)},e.protocolVersion=10,e.ratchet=function(e,t){return Tt(this,void 0,void 0,(function*(){const i=hs(e.algorithm.name,t);return crypto.subtle.deriveBits(i,e,256)}))},e.setLogExtension=function(t){const i=a.methodFactory;a.methodFactory=(n,r,s)=>{const o=i(n,r,s),a=e.LogLevel[n],c=a>=r&&a<e.LogLevel.silent;return(e,i)=>{i?o(e,i):o(e),c&&t(a,e,i)}},a.setLevel(a.getLevel())},e.setLogLevel=function(e,t){t&&o.getLogger(t).setLevel(e);for(const t of Object.values(o.getLoggers()))t.setLevel(e)},e.supportsAV1=Tr,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsDynacast=function(){return kr()},e.supportsVP9=Sr,e.version=zn,e.videoCodecs=Xn,e.writeRbsp=function(e){const t=[];for(var i=0,n=0;n<e.length;++n){var r=e[n];r<=3&&i>=2&&(t.push(3),i=0),t.push(r),0==r?++i:i=0}return new Uint8Array(t)}}));
|
2
2
|
//# sourceMappingURL=livekit-client.umd.js.map
|